From 152a9c115e29b5e90ca46f094f12c4be480750e3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?=
Date: Wed, 4 Nov 2026 22:43:30 +0900
Subject: [PATCH] =?UTF-8?q?feat(musicvideo):=20=E6=9B=B2=E3=81=A8=E7=B4=A0?=
=?UTF-8?q?=E6=9D=90=E3=82=92=E7=94=BB=E9=9D=A2=E5=85=A8=E4=BD=93=E3=81=A7?=
=?UTF-8?q?=E6=8E=A2=E3=81=9B=E3=82=8B=E3=83=96=E3=83=A9=E3=82=A6=E3=82=B6?=
=?UTF-8?q?=E3=83=BC=E3=81=AB=E5=A4=89=E6=9B=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Models/MusicVideoExportDestination.swift | 7 +-
.../Models/MusicVideoMusicBrowser.swift | 121 ++++
.../Models/MusicVideoSourceBrowser.swift | 102 +++
.../Views/MusicVideoMusicPickerSheet.swift | 209 -------
.../Views/MusicVideoMusicPickerView.swift | 404 ++++++++++++
.../Views/MusicVideoSourcePickerSheet.swift | 338 ----------
.../Views/MusicVideoSourcePickerView.swift | 581 ++++++++++++++++++
.../MusicVideo/Views/MusicVideoView.swift | 131 ++--
.../MusicVideoMusicBrowserTests.swift | 190 ++++++
.../MusicVideoSourceBrowserTests.swift | 175 ++++++
10 files changed, 1660 insertions(+), 598 deletions(-)
create mode 100644 ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift
create mode 100644 ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift
delete mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift
create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift
delete mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift
create mode 100644 ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift
create mode 100644 ArkServerTests/MusicVideoMusicBrowserTests.swift
create mode 100644 ArkServerTests/MusicVideoSourceBrowserTests.swift
diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift
index a8254ab..2d41cd3 100644
--- a/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift
+++ b/ArkServer/Features/MusicVideo/Models/MusicVideoExportDestination.swift
@@ -63,6 +63,8 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
let count: Int
let totalDuration: Double
let latestImport: Date
+ /// 表紙に使う動画(アルバムの最初の動画)。動画が1本もなければ nil。
+ var coverVideoID: UUID? = nil
/// 写真だけのアルバムを除いた一覧を作る。表示名(`Album.displayTitle`)がメインアクター上なので,こちらもそうする。
@MainActor
@@ -74,11 +76,13 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
var count = 0
var total = 0.0
var latest = Date.distantPast
+ var cover: UUID?
for id in album.videoIDs {
guard let item = byID[id], item.mediaType == .video, !item.isInTrash else { continue }
count += 1
total += item.duration
latest = max(latest, item.importDate)
+ if cover == nil { cover = item.id }
}
let components = album.name.components(separatedBy: "/")
return MusicVideoAlbumEntry(
@@ -88,7 +92,8 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
parent: components.count > 1 ? components.dropLast().joined(separator: " / ") : "",
count: count,
totalDuration: total,
- latestImport: latest
+ latestImport: latest,
+ coverVideoID: cover
)
}
}
diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift
new file mode 100644
index 0000000..5d9dcdc
--- /dev/null
+++ b/ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift
@@ -0,0 +1,121 @@
+// ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift
+
+import Foundation
+import UniformTypeIdentifiers
+
+// 曲を選ぶ画面の、フォルダの走査と、一覧の絞り込み・並べ替え。画面から切り離して、テストできるようにしてある。
+
+/// 曲のファイル1つぶん。
+nonisolated struct MusicVideoMusicFile: Identifiable, Hashable, Sendable {
+ let url: URL
+ let size: Int64
+ let modified: Date
+ /// 選んだフォルダからの相対の場所("/" 区切り)。選んだフォルダの直下なら空。
+ let folder: String
+
+ var id: URL { url }
+ var title: String { url.deletingPathExtension().lastPathComponent }
+}
+
+/// 曲一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.musicPicker.order`)と同じにしてある。
+nonisolated enum MusicVideoMusicOrder: String, CaseIterable, Identifiable, Sendable {
+ case name = "名前"
+ case recent = "新しい順"
+ var id: String { rawValue }
+}
+
+/// 左に並べるフォルダ1つぶん。階層の途中のフォルダも含み、数は、その下(サブフォルダ)の曲も合わせた数。
+nonisolated struct MusicVideoMusicFolder: Identifiable, Hashable, Sendable {
+ /// 選んだフォルダからの相対の場所("/" 区切り)。
+ let path: String
+ let count: Int
+
+ var id: String { path }
+ var components: [String] { path.split(separator: "/").map(String.init) }
+ /// 表示名(階層の最後)。
+ var name: String { components.last ?? path }
+ /// 階層の深さ(直下のフォルダが 0)。
+ var depth: Int { max(0, components.count - 1) }
+}
+
+nonisolated enum MusicVideoMusicBrowser {
+ /// これを超える曲は、先頭からここまでだけ集める(巨大なフォルダで固まらないように)。
+ static let fileLimit = 2000
+
+ /// フォルダの中(サブフォルダも含む)の音声ファイルを集める。隠しファイルとパッケージの中は除く。
+ static func scan(folder: URL, limit: Int = fileLimit) -> (files: [MusicVideoMusicFile], hitLimit: Bool) {
+ let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey]
+ guard let enumerator = FileManager.default.enumerator(
+ at: folder,
+ includingPropertiesForKeys: keys,
+ options: [.skipsHiddenFiles, .skipsPackageDescendants]
+ ) else { return ([], false) }
+
+ let rootComponents = folder.standardizedFileURL.pathComponents
+ var found: [MusicVideoMusicFile] = []
+ for case let url as URL in enumerator {
+ guard let type = UTType(filenameExtension: url.pathExtension), type.conforms(to: .audio) else { continue }
+ let values = try? url.resourceValues(forKeys: Set(keys))
+ guard values?.isRegularFile == true else { continue }
+ found.append(MusicVideoMusicFile(
+ url: url,
+ size: Int64(values?.fileSize ?? 0),
+ modified: values?.contentModificationDate ?? .distantPast,
+ folder: relativeFolder(of: url, root: rootComponents)
+ ))
+ if found.count >= limit { return (found, true) }
+ }
+ return (found, false)
+ }
+
+ /// `url` のあるフォルダの、選んだフォルダからの相対の場所。選んだフォルダの外にあるように見えるとき(別名の道筋など)は空にする。
+ static func relativeFolder(of url: URL, root: [String]) -> String {
+ let parent = url.deletingLastPathComponent().standardizedFileURL.pathComponents
+ guard parent.count >= root.count, Array(parent.prefix(root.count)) == root else { return "" }
+ return parent.dropFirst(root.count).joined(separator: "/")
+ }
+
+ /// その場所(`folder`)とその下のフォルダにある曲か。`folder` が nil なら、すべて。
+ static func isIn(_ file: MusicVideoMusicFile, folder: String?) -> Bool {
+ guard let folder, !folder.isEmpty else { return true }
+ return file.folder == folder || file.folder.hasPrefix(folder + "/")
+ }
+
+ /// 曲一覧。`folder` はその場所とその下に絞る。`query` は曲名に含まれる語(大文字小文字は区別しない)。
+ static func visible(
+ _ files: [MusicVideoMusicFile],
+ folder: String?,
+ order: MusicVideoMusicOrder,
+ query: String
+ ) -> [MusicVideoMusicFile] {
+ var result = files.filter { isIn($0, folder: folder) }
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty { result = result.filter { $0.title.localizedCaseInsensitiveContains(trimmed) } }
+ switch order {
+ case .name: result.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
+ case .recent: result.sort { $0.modified > $1.modified }
+ }
+ return result
+ }
+
+ /// 曲のあるフォルダの一覧(階層の途中も含む)。階層の順に並ぶ。選んだフォルダの直下の曲は、どのフォルダにも入らない。
+ static func folders(in files: [MusicVideoMusicFile]) -> [MusicVideoMusicFolder] {
+ var counts: [String: Int] = [:]
+ for file in files where !file.folder.isEmpty {
+ var path = ""
+ for part in file.folder.split(separator: "/") {
+ path = path.isEmpty ? String(part) : path + "/" + part
+ counts[path, default: 0] += 1
+ }
+ }
+ return counts
+ .map { MusicVideoMusicFolder(path: $0.key, count: $0.value) }
+ .sorted { lhs, rhs in
+ // 親の次にその子が来るよう、階層の部品ごとに自然順で比べる。
+ for (left, right) in zip(lhs.components, rhs.components) where left != right {
+ return left.localizedStandardCompare(right) == .orderedAscending
+ }
+ return lhs.components.count < rhs.components.count
+ }
+ }
+}
diff --git a/ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift b/ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift
new file mode 100644
index 0000000..d5e72fc
--- /dev/null
+++ b/ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift
@@ -0,0 +1,102 @@
+// ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift
+
+import Foundation
+
+// 素材を選ぶ画面の、一覧の絞り込みと並べ替え。画面から切り離して、テストできるようにしてある。
+
+/// アルバム一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.picker.albumOrder`)と同じにしてある。
+nonisolated enum MusicVideoAlbumOrder: String, CaseIterable, Identifiable, Sendable {
+ case name = "名前"
+ case count = "件数の多い順"
+ case recent = "最近追加した順"
+ var id: String { rawValue }
+}
+
+/// 動画一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.picker.videoOrder`)と同じにしてある。
+nonisolated enum MusicVideoVideoOrder: String, CaseIterable, Identifiable, Sendable {
+ case recent = "追加が新しい順"
+ case longest = "長い順"
+ case name = "名前"
+ var id: String { rawValue }
+}
+
+nonisolated enum MusicVideoSourceBrowser {
+ /// アルバム一覧。
+ /// - Parameters:
+ /// - hidesEmpty: 動画が1本もないアルバムを隠す。
+ /// - onlyIDs: 指定すると、そのアルバムだけに絞る(「選択中のみ」)。nil なら絞らない。
+ /// - query: 名前か階層に含まれる語。空なら絞らない。
+ static func albums(
+ _ rows: [MusicVideoAlbumEntry],
+ order: MusicVideoAlbumOrder,
+ hidesEmpty: Bool,
+ onlyIDs: Set?,
+ query: String
+ ) -> [MusicVideoAlbumEntry] {
+ var result = rows
+ if hidesEmpty { result = result.filter { $0.count > 0 } }
+ if let onlyIDs { result = result.filter { onlyIDs.contains($0.id) } }
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty { result = result.filter { $0.matches(query: trimmed) } }
+ switch order {
+ case .name:
+ func key(_ entry: MusicVideoAlbumEntry) -> String { entry.parent + "/" + entry.title }
+ result.sort { key($0).localizedStandardCompare(key($1)) == .orderedAscending }
+ case .count:
+ result.sort { $0.count > $1.count }
+ case .recent:
+ result.sort { $0.latestImport > $1.latestImport }
+ }
+ return result
+ }
+
+ /// 動画一覧。
+ /// - Parameters:
+ /// - minimumLength: これより短い動画は出さない(秒)。
+ /// - onlyIDs: 指定すると、その動画だけに絞る(「選択中のみ」)。nil なら絞らない。
+ static func videos(
+ _ items: [VideoItem],
+ order: MusicVideoVideoOrder,
+ minimumLength: Double,
+ favoritesOnly: Bool,
+ onlyIDs: Set?,
+ query: String
+ ) -> [VideoItem] {
+ var result = items.filter { $0.duration >= minimumLength }
+ if favoritesOnly { result = result.filter(\.isFavorite) }
+ if let onlyIDs { result = result.filter { onlyIDs.contains($0.id) } }
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty { result = result.filter { $0.originalFilename.localizedCaseInsensitiveContains(trimmed) } }
+ switch order {
+ case .recent:
+ result.sort { $0.importDate > $1.importDate }
+ case .longest:
+ result.sort { $0.duration > $1.duration }
+ case .name:
+ result.sort { $0.originalFilename.localizedStandardCompare($1.originalFilename) == .orderedAscending }
+ }
+ return result
+ }
+
+ /// 素材にできる動画(動画で、ゴミ箱の外)。
+ static func usableVideos(_ videos: [VideoItem]) -> [VideoItem] {
+ videos.filter { $0.mediaType == .video && !$0.isInTrash }
+ }
+
+ /// アルバムに入っている動画(動画で、ゴミ箱の外)。アルバムの並びのまま。
+ static func videos(in album: Album, from videosByID: [UUID: VideoItem]) -> [VideoItem] {
+ album.videoIDs.compactMap { id in
+ guard let item = videosByID[id], item.mediaType == .video, !item.isInTrash else { return nil }
+ return item
+ }
+ }
+
+ /// 選んだアルバムに入っている動画の ID。「アルバムで選択済み」の印に使う。
+ static func videoIDs(inAlbums albums: [Album], selected: Set, from videosByID: [UUID: VideoItem]) -> Set {
+ var ids = Set()
+ for album in albums where selected.contains(album.id) {
+ for item in videos(in: album, from: videosByID) { ids.insert(item.id) }
+ }
+ return ids
+ }
+}
diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift
deleted file mode 100644
index b5a0e79..0000000
--- a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift
+++ /dev/null
@@ -1,209 +0,0 @@
-// ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerSheet.swift
-
-import AppKit
-import SwiftUI
-import UniformTypeIdentifiers
-
-/// 曲を置いてあるフォルダから、曲を探して選ぶシート。フォルダは一度選べば覚える。
-struct MusicVideoMusicPickerSheet: View {
- @ObservedObject var viewModel: MusicVideoViewModel
- /// 試聴の状態。画面の更新を受けるため、ViewModel の中のものをここでも監視する。
- @ObservedObject private var preview: MusicPreviewPlayer
- @Environment(\.dismiss) private var dismiss
-
- init(viewModel: MusicVideoViewModel) {
- self.viewModel = viewModel
- _preview = ObservedObject(wrappedValue: viewModel.preview)
- }
-
- struct MusicFile: Identifiable, Hashable, Sendable {
- let url: URL
- let size: Int64
- let modified: Date
- var id: URL { url }
- var title: String { url.deletingPathExtension().lastPathComponent }
- }
-
- enum Order: String, CaseIterable, Identifiable {
- case name = "名前"
- case recent = "新しい順"
- var id: String { rawValue }
- }
-
- @State private var files: [MusicFile] = []
- @State private var isLoading = false
- @State private var didHitLimit = false
- @State private var searchText = ""
- @AppStorage("musicVideo.musicPicker.order") private var order: Order = .name
-
- private static let fileLimit = 2000
-
- private var visibleFiles: [MusicFile] {
- let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
- var result = query.isEmpty ? files : files.filter { $0.title.localizedCaseInsensitiveContains(query) }
- switch order {
- case .name: result.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
- case .recent: result.sort { $0.modified > $1.modified }
- }
- return result
- }
-
- var body: some View {
- VStack(spacing: 0) {
- SheetHeader(
- icon: "music.note.list",
- title: "曲を選ぶ",
- subtitle: viewModel.musicFolderURL?.path ?? "曲を置いてあるフォルダを選んでください"
- )
- .padding(20)
-
- HStack(spacing: 12) {
- TextField("曲名で検索", text: $searchText)
- .textFieldStyle(.roundedBorder)
- Picker("並べ替え", selection: $order) {
- ForEach(Order.allCases) { Text($0.rawValue).tag($0) }
- }
- .frame(width: 180)
- Button("フォルダを選ぶ…", action: chooseFolder)
- }
- .padding(.horizontal, 20)
- .padding(.bottom, 12)
-
- Divider()
-
- content
-
- Divider()
- HStack {
- Text(footerText)
- .font(.appCaption)
- .foregroundStyle(NeomorphicTheme.muted)
- if let message = preview.failureMessage {
- Label(message, systemImage: "exclamationmark.triangle.fill")
- .font(.appCaption)
- .foregroundStyle(NeomorphicTheme.caution)
- }
- Spacer()
- Button("閉じる") { dismiss() }
- .keyboardShortcut(.cancelAction)
- }
- .padding(16)
- }
- .frame(minWidth: 640, idealWidth: 700, minHeight: 520, idealHeight: 620)
- .appSheet()
- .task(id: viewModel.musicFolderURL) { await load() }
- // シートを閉じたら、試聴の音も止める。
- .onDisappear { viewModel.preview.stop() }
- }
-
- @ViewBuilder
- private var content: some View {
- if viewModel.musicFolderURL == nil {
- placeholder(icon: "folder.badge.plus", message: "「フォルダを選ぶ…」で,曲を置いてあるフォルダを選んでください")
- } else if isLoading {
- VStack(spacing: 10) {
- ProgressView()
- Text("曲を探しています…").font(.appBody).foregroundStyle(NeomorphicTheme.muted)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- } else if visibleFiles.isEmpty {
- placeholder(icon: "music.note", message: files.isEmpty ? "このフォルダに曲が見つかりませんでした" : "条件に合う曲がありません")
- } else {
- List(visibleFiles) { file in
- HStack(spacing: 10) {
- // 左の再生ボタンで試聴、曲名の側を押すとその曲を使う。
- MusicPreviewButton(preview: preview, url: file.url) { viewModel.togglePreview(file.url) }
- Button {
- viewModel.chooseMusic(file.url)
- dismiss()
- } label: {
- HStack(spacing: 10) {
- Text(file.title)
- .font(.appBody)
- .lineLimit(1)
- .truncationMode(.middle)
- Spacer(minLength: 8)
- Text(ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file))
- .font(.appMicro.monospacedDigit())
- .foregroundStyle(NeomorphicTheme.muted)
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel("\(file.title)を使う")
- }
- }
- .listStyle(.plain)
- }
- }
-
- private func placeholder(icon: String, message: String) -> some View {
- VStack(spacing: 8) {
- Image(systemName: icon).font(.system(size: 28, weight: .light))
- Text(message).font(.appBody).multilineTextAlignment(.center)
- }
- .foregroundStyle(NeomorphicTheme.muted)
- .padding(24)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- }
-
- private var footerText: String {
- guard viewModel.musicFolderURL != nil, !isLoading else { return "" }
- let shown = visibleFiles.count
- let base = shown == files.count ? "\(files.count)曲" : "\(shown) / \(files.count)曲"
- return didHitLimit ? "\(base)(多いため先頭\(Self.fileLimit)曲まで)" : base
- }
-
- private func chooseFolder() {
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.allowsMultipleSelection = false
- panel.prompt = "選択"
- panel.message = "曲を置いてあるフォルダを選んでください(中のフォルダも探します)"
- if let current = viewModel.musicFolderURL { panel.directoryURL = current }
- if panel.runModal() == .OK, let url = panel.url {
- viewModel.setMusicFolder(url)
- }
- }
-
- private func load() async {
- guard let folder = viewModel.musicFolderURL else {
- files = []
- return
- }
- isLoading = true
- let limit = Self.fileLimit
- let result = await Task.detached(priority: .userInitiated) {
- Self.scan(folder: folder, limit: limit)
- }.value
- guard !Task.isCancelled else { return }
- files = result.files
- didHitLimit = result.hitLimit
- isLoading = false
- }
-
- /// フォルダの中(サブフォルダも含む)の音声ファイルを集める。
- nonisolated private static func scan(folder: URL, limit: Int) -> (files: [MusicFile], hitLimit: Bool) {
- let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey]
- guard let enumerator = FileManager.default.enumerator(
- at: folder,
- includingPropertiesForKeys: keys,
- options: [.skipsHiddenFiles, .skipsPackageDescendants]
- ) else { return ([], false) }
-
- var found: [MusicFile] = []
- for case let url as URL in enumerator {
- guard let type = UTType(filenameExtension: url.pathExtension), type.conforms(to: .audio) else { continue }
- let values = try? url.resourceValues(forKeys: Set(keys))
- guard values?.isRegularFile == true else { continue }
- found.append(MusicFile(
- url: url,
- size: Int64(values?.fileSize ?? 0),
- modified: values?.contentModificationDate ?? .distantPast
- ))
- if found.count >= limit { return (found, true) }
- }
- return (found, false)
- }
-}
diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift
new file mode 100644
index 0000000..8ef9304
--- /dev/null
+++ b/ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift
@@ -0,0 +1,404 @@
+// ArkServer/Features/MusicVideo/Views/MusicVideoMusicPickerView.swift
+
+import AppKit
+import SwiftUI
+
+/// 曲を置いてあるフォルダから、曲を探して選ぶ画面。ポップアップではなく、ミュージックビデオの画面いっぱいに出す。
+///
+/// 左に、最近使った曲と、フォルダの階層(サブフォルダごとの曲数つき)。右に、曲の一覧。
+/// 各行の再生ボタンで試聴でき、行を押すとその曲を使う。フォルダは一度選べば覚える。
+struct MusicVideoMusicPickerView: View {
+ @ObservedObject var viewModel: MusicVideoViewModel
+ /// 試聴の状態。画面の更新を受けるため、ViewModel の中のものをここでも監視する。
+ @ObservedObject private var preview: MusicPreviewPlayer
+ let close: () -> Void
+
+ @State private var files: [MusicVideoMusicFile] = []
+ @State private var folders: [MusicVideoMusicFolder] = []
+ @State private var isLoading = false
+ @State private var didHitLimit = false
+ @State private var searchText = ""
+ /// 右に出す曲の範囲(フォルダの相対の場所)。nil なら、すべて。
+ @State private var scope: String?
+ @State private var hoveredID: URL?
+ @AppStorage("musicVideo.musicPicker.order") private var order: MusicVideoMusicOrder = .name
+
+ private static let leftPaneWidth: CGFloat = 320
+ private static let recentLimit = 8
+
+ init(viewModel: MusicVideoViewModel, close: @escaping () -> Void) {
+ self.viewModel = viewModel
+ self.close = close
+ _preview = ObservedObject(wrappedValue: viewModel.preview)
+ }
+
+ private var visibleFiles: [MusicVideoMusicFile] {
+ MusicVideoMusicBrowser.visible(files, folder: scope, order: order, query: searchText)
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider().overlay(NeomorphicTheme.separator)
+ HStack(spacing: 0) {
+ leftPane
+ Divider().overlay(NeomorphicTheme.separator)
+ rightPane
+ }
+ Divider().overlay(NeomorphicTheme.separator)
+ footer
+ }
+ .background(NeomorphicTheme.canvas)
+ .foregroundStyle(NeomorphicTheme.ink)
+ .task(id: viewModel.musicFolderURL) { await load() }
+ // 画面を閉じたら、試聴の音も止める。
+ .onDisappear { viewModel.preview.stop() }
+ }
+
+ // MARK: - 上の帯
+
+ private var header: some View {
+ HStack(spacing: 16) {
+ Button(action: close) {
+ Label("戻る", systemImage: "chevron.left")
+ }
+ .buttonStyle(.quiet)
+ .keyboardShortcut(.cancelAction)
+ .help("ミュージックビデオの画面へ戻ります(Esc)")
+ .accessibilityIdentifier("musicvideo.musicBack")
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text("曲を選ぶ")
+ .font(.appTitle)
+ Text(viewModel.musicFolderURL?.path ?? "曲を置いてあるフォルダを選んでください")
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ Spacer(minLength: 12)
+ Button("フォルダを選ぶ…", action: chooseFolder)
+ .buttonStyle(.quiet)
+ .accessibilityIdentifier("musicvideo.musicChooseFolder")
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 14)
+ }
+
+ // MARK: - 左: 最近使った曲・フォルダ
+
+ private var leftPane: some View {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 2) {
+ let recent = Array(viewModel.recentMusicURLs.prefix(Self.recentLimit))
+ if !recent.isEmpty {
+ sectionTitle("最近使った曲")
+ ForEach(recent, id: \.self) { recentRow($0) }
+ }
+ if viewModel.musicFolderURL != nil, !isLoading {
+ sectionTitle("フォルダ")
+ folderRow(path: nil, name: "すべての曲", count: files.count, depth: 0)
+ ForEach(folders) { folder in
+ folderRow(path: folder.path, name: folder.name, count: folder.count, depth: folder.depth)
+ }
+ }
+ }
+ .padding(8)
+ }
+ .frame(width: Self.leftPaneWidth)
+ .background(NeomorphicTheme.sidebar)
+ }
+
+ private func sectionTitle(_ text: String) -> some View {
+ Text(text)
+ .font(.appCaptionStrong)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .padding(.horizontal, 10)
+ .padding(.top, 10)
+ .padding(.bottom, 4)
+ .accessibilityAddTraits(.isHeader)
+ }
+
+ /// 最近使った曲: 左の再生ボタンで試聴、行を押すとその曲を使う。
+ private func recentRow(_ url: URL) -> some View {
+ HStack(spacing: 10) {
+ MusicPreviewButton(preview: preview, url: url) { viewModel.togglePreview(url) }
+ Button {
+ choose(url)
+ } label: {
+ HStack(spacing: 6) {
+ Text(url.deletingPathExtension().lastPathComponent)
+ .font(.appBody)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 4)
+ if isCurrent(url) {
+ Image(systemName: "checkmark")
+ .font(.appMicro)
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help("この曲に合わせて映像を作る")
+ .accessibilityLabel("\(url.deletingPathExtension().lastPathComponent)を使う")
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 4)
+ }
+
+ private func folderRow(path: String?, name: String, count: Int, depth: Int) -> some View {
+ let isScope = scope == path
+ return Button {
+ scope = path
+ } label: {
+ HStack(spacing: 8) {
+ Image(systemName: path == nil ? "music.note.list" : "folder")
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .frame(width: 18)
+ Text(name)
+ .font(path == nil ? .appBodyStrong : .appBody)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 4)
+ Text(count.formatted())
+ .font(.appCaption.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ .padding(.leading, 10 + CGFloat(depth) * 14)
+ .padding(.trailing, 10)
+ .padding(.vertical, 6)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(isScope ? NeomorphicTheme.selection : Color.clear)
+ )
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("\(name) \(count)曲")
+ .accessibilityAddTraits(isScope ? .isSelected : [])
+ }
+
+ // MARK: - 右: 曲の一覧
+
+ private var scopeTitle: String {
+ guard let scope, !scope.isEmpty else { return "すべての曲" }
+ return scope.replacingOccurrences(of: "/", with: " / ")
+ }
+
+ private var rightPane: some View {
+ VStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(scopeTitle)
+ .font(.appHeadline)
+ .lineLimit(1)
+ .truncationMode(.head)
+ if viewModel.musicFolderURL != nil, !isLoading {
+ Text("\(visibleFiles.count.formatted())曲")
+ .font(.appCaption.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ Spacer(minLength: 8)
+ }
+ HStack(spacing: 12) {
+ TextField("曲名で検索", text: $searchText)
+ .textFieldStyle(.roundedBorder)
+ .frame(minWidth: 160)
+ Picker("並べ替え", selection: $order) {
+ ForEach(MusicVideoMusicOrder.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .labelsHidden()
+ .fixedSize()
+ }
+ .font(.appCaption)
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 14)
+
+ Divider().overlay(NeomorphicTheme.separator)
+
+ content
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ if viewModel.musicFolderURL == nil {
+ VStack(spacing: 14) {
+ Image(systemName: "folder.badge.plus")
+ .font(.system(size: 34, weight: .light))
+ Text("曲を置いてあるフォルダを選んでください")
+ .font(.appBody)
+ Button("フォルダを選ぶ…", action: chooseFolder)
+ .buttonStyle(.borderedProminent)
+ }
+ .foregroundStyle(NeomorphicTheme.muted)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if isLoading {
+ VStack(spacing: 10) {
+ ProgressView()
+ Text("曲を探しています…").font(.appBody).foregroundStyle(NeomorphicTheme.muted)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if visibleFiles.isEmpty {
+ placeholder(icon: "music.note", message: files.isEmpty ? "このフォルダに曲が見つかりませんでした" : "条件に合う曲がありません")
+ } else {
+ ScrollView {
+ LazyVStack(spacing: 2) {
+ ForEach(visibleFiles) { songRow($0) }
+ }
+ .padding(10)
+ }
+ }
+ }
+
+ /// いま選んでいる曲か。`/var` と `/private/var` のように、同じファイルでも URL の形が違うことがあるので、
+ /// 標準化したパスで比べる。
+ private func isCurrent(_ url: URL) -> Bool {
+ guard let current = viewModel.musicURL else { return false }
+ return current.standardizedFileURL.path == url.standardizedFileURL.path
+ }
+
+ private func songRow(_ file: MusicVideoMusicFile) -> some View {
+ let isCurrent = isCurrent(file.url)
+ let isHovered = hoveredID == file.id
+ return HStack(spacing: 12) {
+ MusicPreviewButton(preview: preview, url: file.url) { viewModel.togglePreview(file.url) }
+ Button {
+ choose(file.url)
+ } label: {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(file.title)
+ .font(.appBody)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if !file.folder.isEmpty {
+ Text(file.folder.replacingOccurrences(of: "/", with: " / "))
+ .font(.appMicro)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ }
+ Spacer(minLength: 8)
+ if isCurrent {
+ Text("使用中")
+ .font(.appMicroStrong)
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ if file.modified != .distantPast {
+ Text(file.modified.formatted(date: .numeric, time: .omitted))
+ .font(.appMicro.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ Text(ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file))
+ .font(.appMicro.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ .frame(width: 64, alignment: .trailing)
+ Text("使う")
+ .font(.appCaptionStrong)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 4)
+ .background(
+ Capsule().fill(isHovered ? NeomorphicTheme.controlSelected : NeomorphicTheme.control)
+ )
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help("この曲に合わせて映像を作る")
+ .accessibilityLabel("\(file.title)を使う")
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(isHovered ? NeomorphicTheme.hover : Color.clear)
+ )
+ .onHover { inside in
+ if inside { hoveredID = file.id } else if hoveredID == file.id { hoveredID = nil }
+ }
+ }
+
+ private func placeholder(icon: String, message: String) -> some View {
+ VStack(spacing: 8) {
+ Image(systemName: icon).font(.system(size: 28, weight: .light))
+ Text(message).font(.appBody).multilineTextAlignment(.center)
+ }
+ .foregroundStyle(NeomorphicTheme.muted)
+ .padding(24)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ // MARK: - 下の帯
+
+ private var footer: some View {
+ HStack(spacing: 12) {
+ Text(footerText)
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ if let message = preview.failureMessage {
+ Label(message, systemImage: "exclamationmark.triangle.fill")
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.caution)
+ }
+ Spacer()
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 12)
+ .background(NeomorphicTheme.canvas)
+ }
+
+ private var footerText: String {
+ guard viewModel.musicFolderURL != nil, !isLoading else { return "" }
+ let shown = visibleFiles.count
+ let base = shown == files.count ? "\(files.count)曲" : "\(shown) / \(files.count)曲"
+ return didHitLimit ? "\(base)(多いため先頭\(MusicVideoMusicBrowser.fileLimit)曲まで)" : base
+ }
+
+ // MARK: - 操作
+
+ private func choose(_ url: URL) {
+ viewModel.chooseMusic(url)
+ close()
+ }
+
+ private func chooseFolder() {
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = false
+ panel.canChooseDirectories = true
+ panel.allowsMultipleSelection = false
+ panel.prompt = "選択"
+ panel.message = "曲を置いてあるフォルダを選んでください(中のフォルダも探します)"
+ if let current = viewModel.musicFolderURL { panel.directoryURL = current }
+ if panel.runModal() == .OK, let url = panel.url {
+ viewModel.setMusicFolder(url)
+ }
+ }
+
+ private func load() async {
+ guard let folder = viewModel.musicFolderURL else {
+ files = []
+ folders = []
+ scope = nil
+ return
+ }
+ isLoading = true
+ let limit = MusicVideoMusicBrowser.fileLimit
+ let result = await Task.detached(priority: .userInitiated) {
+ MusicVideoMusicBrowser.scan(folder: folder, limit: limit)
+ }.value
+ guard !Task.isCancelled else { return }
+ files = result.files
+ folders = MusicVideoMusicBrowser.folders(in: result.files)
+ didHitLimit = result.hitLimit
+ // 見ていたフォルダが、読み直した結果に無ければ、すべてへ戻す。
+ if let scope, !folders.contains(where: { $0.path == scope }) { self.scope = nil }
+ isLoading = false
+ }
+}
diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift
deleted file mode 100644
index 45f6f78..0000000
--- a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift
+++ /dev/null
@@ -1,338 +0,0 @@
-// ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerSheet.swift
-
-import SwiftUI
-
-/// 素材にする動画を選ぶシート。アルバム単位と動画単位のどちらでも、まとめて選べる。
-/// 数百のアルバムや千本以上の動画から探せるよう、検索・並べ替え・絞り込みを備える。
-struct MusicVideoSourcePickerSheet: View {
- @ObservedObject var viewModel: MusicVideoViewModel
- @ObservedObject var dataManager: LibraryViewModel
- @Environment(\.dismiss) private var dismiss
-
- private enum Tab: String, CaseIterable, Hashable {
- case albums = "アルバム"
- case videos = "動画"
- }
-
- enum AlbumOrder: String, CaseIterable, Identifiable {
- case name = "名前"
- case count = "件数の多い順"
- case recent = "最近追加した順"
- var id: String { rawValue }
- }
-
- enum VideoOrder: String, CaseIterable, Identifiable {
- case recent = "追加が新しい順"
- case longest = "長い順"
- case name = "名前"
- var id: String { rawValue }
- }
-
- @State private var tab: Tab = .albums
- @State private var searchText = ""
- @AppStorage("musicVideo.picker.albumOrder") private var albumOrder: AlbumOrder = .name
- @AppStorage("musicVideo.picker.videoOrder") private var videoOrder: VideoOrder = .recent
- @AppStorage("musicVideo.picker.hideEmpty") private var hidesEmptyAlbums = true
- @AppStorage("musicVideo.picker.minimumLength") private var minimumLength = 5.0
- @State private var onlySelected = false
- @State private var favoritesOnly = false
- @State private var albumRows: [MusicVideoAlbumEntry] = []
- /// 動画タブの一覧(動画だけ・ゴミ箱外)。ライブラリが変わったときだけ作り直す。
- @State private var allVideos: [VideoItem] = []
-
- private var query: String { searchText.trimmingCharacters(in: .whitespacesAndNewlines) }
-
- var body: some View {
- VStack(spacing: 0) {
- SheetHeader(
- icon: "film.stack",
- title: "素材を選ぶ",
- subtitle: "アルバムと動画は,どちらも組み合わせて選べます"
- )
- .padding(20)
-
- controls
- .padding(.horizontal, 20)
- .padding(.bottom, 12)
-
- Divider()
-
- Group {
- switch tab {
- case .albums: albumList
- case .videos: videoList
- }
- }
-
- Divider()
- footer
- .padding(16)
- }
- .frame(minWidth: 760, idealWidth: 800, minHeight: 620, idealHeight: 700)
- .appSheet()
- .onAppear(perform: rebuild)
- .onChange(of: dataManager.albums) { rebuild() }
- .onChange(of: dataManager.videos) { rebuild() }
- }
-
- // MARK: - 操作部
-
- private var controls: some View {
- VStack(spacing: 10) {
- HStack(spacing: 12) {
- FlatSegmentedControl(
- options: Tab.allCases,
- title: { tab in
- switch tab {
- case .albums: return "アルバム(\(viewModel.selectedAlbumIDs.count))"
- case .videos: return "動画(\(viewModel.selectedVideoIDs.count))"
- }
- },
- selection: $tab,
- width: 280
- )
- TextField(tab == .albums ? "アルバム名で検索" : "動画名で検索", text: $searchText)
- .textFieldStyle(.roundedBorder)
- }
- HStack(spacing: 14) {
- switch tab {
- case .albums:
- Picker("並べ替え", selection: $albumOrder) {
- ForEach(AlbumOrder.allCases) { Text($0.rawValue).tag($0) }
- }
- .frame(width: 210)
- Toggle("空を隠す", isOn: $hidesEmptyAlbums)
- .fixedSize()
- .help("動画が1本もないアルバムを一覧から隠します")
- case .videos:
- Picker("並べ替え", selection: $videoOrder) {
- ForEach(VideoOrder.allCases) { Text($0.rawValue).tag($0) }
- }
- .frame(width: 210)
- Picker("長さ", selection: $minimumLength) {
- Text("すべて").tag(1.0)
- Text("5秒以上").tag(5.0)
- Text("10秒以上").tag(10.0)
- Text("30秒以上").tag(30.0)
- }
- .frame(width: 150)
- Toggle("お気に入りのみ", isOn: $favoritesOnly)
- .fixedSize()
- }
- Toggle("選択中のみ", isOn: $onlySelected)
- .fixedSize()
- Spacer(minLength: 0)
- Button("表示中を選択") { selectAllVisible() }
- .help("いま一覧に出ているものをすべて選びます")
- Button("表示中を解除") { deselectAllVisible() }
- .help("いま一覧に出ているものの選択をすべて外します")
- }
- .font(.appCaption)
- }
- }
-
- // MARK: - アルバム
-
- private var visibleAlbums: [MusicVideoAlbumEntry] {
- var rows = albumRows
- if hidesEmptyAlbums { rows = rows.filter { $0.count > 0 } }
- if onlySelected { rows = rows.filter { viewModel.selectedAlbumIDs.contains($0.id) } }
- if !query.isEmpty { rows = rows.filter { $0.matches(query: query) } }
- switch albumOrder {
- case .name:
- rows.sort { ($0.parent + "/" + $0.title).localizedStandardCompare($1.parent + "/" + $1.title) == .orderedAscending }
- case .count:
- rows.sort { $0.count > $1.count }
- case .recent:
- rows.sort { $0.latestImport > $1.latestImport }
- }
- return rows
- }
-
- private var albumList: some View {
- let rows = visibleAlbums
- return Group {
- if rows.isEmpty {
- emptyState("条件に合うアルバムがありません")
- } else {
- List(rows) { row in
- let isSelected = viewModel.selectedAlbumIDs.contains(row.id)
- Button {
- if isSelected { viewModel.selectedAlbumIDs.remove(row.id) } else { viewModel.selectedAlbumIDs.insert(row.id) }
- } label: {
- HStack(spacing: 10) {
- checkmark(isSelected)
- VStack(alignment: .leading, spacing: 2) {
- Text(row.title)
- .font(.appBody)
- .lineLimit(1)
- .truncationMode(.middle)
- if !row.parent.isEmpty {
- Text(row.parent)
- .font(.appMicro)
- .foregroundStyle(NeomorphicTheme.muted)
- .lineLimit(1)
- .truncationMode(.head)
- }
- }
- Spacer(minLength: 8)
- VStack(alignment: .trailing, spacing: 2) {
- Text("\(row.count)本")
- .font(.appCaption.monospacedDigit())
- Text(durationText(row.totalDuration))
- .font(.appMicro.monospacedDigit())
- .foregroundStyle(NeomorphicTheme.muted)
- }
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel("\(row.title) \(row.count)本")
- .accessibilityAddTraits(isSelected ? .isSelected : [])
- }
- .listStyle(.plain)
- }
- }
- }
-
- // MARK: - 動画
-
- private var visibleVideos: [VideoItem] {
- var items = allVideos.filter { $0.duration >= minimumLength }
- if favoritesOnly { items = items.filter(\.isFavorite) }
- if onlySelected { items = items.filter { viewModel.selectedVideoIDs.contains($0.id) } }
- if !query.isEmpty { items = items.filter { $0.originalFilename.localizedCaseInsensitiveContains(query) } }
- switch videoOrder {
- case .recent:
- items.sort { $0.importDate > $1.importDate }
- case .longest:
- items.sort { $0.duration > $1.duration }
- case .name:
- items.sort { $0.originalFilename.localizedStandardCompare($1.originalFilename) == .orderedAscending }
- }
- return items
- }
-
- private var videoList: some View {
- let items = visibleVideos
- return Group {
- if items.isEmpty {
- emptyState("条件に合う動画がありません")
- } else {
- List(items) { video in
- let isSelected = viewModel.selectedVideoIDs.contains(video.id)
- Button {
- if isSelected { viewModel.selectedVideoIDs.remove(video.id) } else { viewModel.selectedVideoIDs.insert(video.id) }
- } label: {
- HStack(spacing: 10) {
- checkmark(isSelected)
- MacVideoThumbnailView(videoItem: video, dataManager: dataManager, showsPlayGlyph: false)
- .frame(width: 80, height: 45)
- .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
- Text(video.originalFilename)
- .font(.appBody)
- .lineLimit(2)
- .truncationMode(.middle)
- Spacer(minLength: 8)
- if video.isFavorite {
- Image(systemName: "heart.fill")
- .font(.appMicro)
- .foregroundStyle(NeomorphicTheme.muted)
- }
- Text(durationText(video.duration))
- .font(.appMicro.monospacedDigit())
- .foregroundStyle(NeomorphicTheme.muted)
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel(video.originalFilename)
- .accessibilityAddTraits(isSelected ? .isSelected : [])
- }
- .listStyle(.plain)
- }
- }
- }
-
- // MARK: - 共通部品
-
- /// 選択の印。サイドバーの複数選択と同じく、色を付けず、選択中は文字色・未選択は控えめな色にする。
- private func checkmark(_ isSelected: Bool) -> some View {
- Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
- .font(.system(size: 15))
- .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted)
- .frame(width: 18)
- }
-
- private func emptyState(_ message: String) -> some View {
- VStack(spacing: 8) {
- Image(systemName: "magnifyingglass")
- .font(.system(size: 28, weight: .light))
- Text(message)
- .font(.appBody)
- }
- .foregroundStyle(NeomorphicTheme.muted)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- }
-
- private var footer: some View {
- HStack(spacing: 12) {
- VStack(alignment: .leading, spacing: 2) {
- Text("使える動画 \(viewModel.candidateCount.formatted())本")
- .font(.appBodyStrong)
- Text(summaryDetail)
- .font(.appCaption)
- .foregroundStyle(NeomorphicTheme.muted)
- }
- Spacer()
- Button("すべて解除") { viewModel.clearSourceSelection() }
- .disabled(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty && !viewModel.includeFavorites)
- Button("完了") { dismiss() }
- .keyboardShortcut(.defaultAction)
- .accessibilityIdentifier("musicvideo.sourceDone")
- }
- }
-
- private var summaryDetail: String {
- var parts: [String] = []
- if !viewModel.selectedAlbumIDs.isEmpty { parts.append("アルバム \(viewModel.selectedAlbumIDs.count)個") }
- if !viewModel.selectedVideoIDs.isEmpty { parts.append("動画 \(viewModel.selectedVideoIDs.count)本") }
- if viewModel.includeFavorites { parts.append("お気に入り") }
- let selection = parts.isEmpty ? "まだ何も選ばれていません" : parts.joined(separator: "・")
- let limit = viewModel.sourceLimit
- return viewModel.candidateCount > limit
- ? "\(selection)(解析は無作為に選ぶ\(limit)本まで)"
- : selection
- }
-
- private func durationText(_ seconds: Double) -> String {
- let total = Int(seconds.rounded())
- if total >= 3600 { return String(format: "%d時間%02d分", total / 3600, (total % 3600) / 60) }
- return String(format: "%d:%02d", total / 60, total % 60)
- }
-
- // MARK: - 選択の一括操作
-
- private func selectAllVisible() {
- switch tab {
- case .albums: viewModel.selectedAlbumIDs.formUnion(visibleAlbums.map(\.id))
- case .videos: viewModel.selectedVideoIDs.formUnion(visibleVideos.map(\.id))
- }
- }
-
- private func deselectAllVisible() {
- switch tab {
- case .albums: viewModel.selectedAlbumIDs.subtract(visibleAlbums.map(\.id))
- case .videos: viewModel.selectedVideoIDs.subtract(visibleVideos.map(\.id))
- }
- }
-
- // MARK: - 一覧の作成
-
- private func rebuild() {
- let videos = dataManager.videos
- allVideos = videos.filter { $0.mediaType == .video && !$0.isInTrash }
-
- albumRows = MusicVideoAlbumEntry.entries(albums: dataManager.albums, videos: videos)
- }
-}
diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift
new file mode 100644
index 0000000..da7ed42
--- /dev/null
+++ b/ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift
@@ -0,0 +1,581 @@
+// ArkServer/Features/MusicVideo/Views/MusicVideoSourcePickerView.swift
+
+import SwiftUI
+
+/// 素材にする動画を選ぶ画面。ポップアップではなく、ミュージックビデオの画面いっぱいに出す。
+///
+/// 左にアルバム(表紙つき)、右に動画のサムネイルを並べる。
+/// アルバムは、チェックで「アルバムごと素材にする」、行を押すと「右にそのアルバムの動画を出す」。
+/// 動画は、サムネイルを見ながら1本ずつ選べる。数百のアルバムや千本以上の動画から探せるよう、
+/// 検索・並べ替え・絞り込みを備える。
+struct MusicVideoSourcePickerView: View {
+ @ObservedObject var viewModel: MusicVideoViewModel
+ @ObservedObject var dataManager: LibraryViewModel
+ let close: () -> Void
+
+ /// 右に出す動画の範囲。
+ private enum Scope: Hashable {
+ case all
+ case album(UUID)
+ }
+
+ @State private var scope: Scope = .all
+ @State private var albumSearch = ""
+ @State private var videoSearch = ""
+ @AppStorage("musicVideo.picker.albumOrder") private var albumOrder: MusicVideoAlbumOrder = .name
+ @AppStorage("musicVideo.picker.videoOrder") private var videoOrder: MusicVideoVideoOrder = .recent
+ @AppStorage("musicVideo.picker.hideEmpty") private var hidesEmptyAlbums = true
+ @AppStorage("musicVideo.picker.minimumLength") private var minimumLength = 5.0
+ @State private var onlySelected = false
+ @State private var favoritesOnly = false
+
+ @State private var albumRows: [MusicVideoAlbumEntry] = []
+ /// 素材にできる動画(動画だけ・ゴミ箱外)。ライブラリが変わったときだけ作り直す。
+ @State private var allVideos: [VideoItem] = []
+ @State private var videosByID: [UUID: VideoItem] = [:]
+ /// 選んだアルバムに入っている動画。「アルバムで選択済み」の印に使う。
+ @State private var albumVideoIDs: Set = []
+
+ private static let albumPaneWidth: CGFloat = 340
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider().overlay(NeomorphicTheme.separator)
+ HStack(spacing: 0) {
+ albumPane
+ Divider().overlay(NeomorphicTheme.separator)
+ videoPane
+ }
+ Divider().overlay(NeomorphicTheme.separator)
+ footer
+ }
+ .background(NeomorphicTheme.canvas)
+ .foregroundStyle(NeomorphicTheme.ink)
+ .onAppear {
+ viewModel.pausePlayback()
+ rebuild()
+ }
+ .onChange(of: dataManager.albums) { rebuild() }
+ .onChange(of: dataManager.videos) { rebuild() }
+ .onChange(of: viewModel.selectedAlbumIDs) { updateAlbumVideoIDs() }
+ }
+
+ // MARK: - 上の帯
+
+ private var header: some View {
+ HStack(spacing: 16) {
+ Button(action: close) {
+ Label("戻る", systemImage: "chevron.left")
+ }
+ .buttonStyle(.quiet)
+ .keyboardShortcut(.cancelAction)
+ .help("ミュージックビデオの画面へ戻ります(Esc)")
+ .accessibilityIdentifier("musicvideo.sourceBack")
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text("素材を選ぶ")
+ .font(.appTitle)
+ Text("アルバムと動画は,どちらも組み合わせて選べます")
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ Spacer(minLength: 12)
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 14)
+ }
+
+ // MARK: - 左: アルバム
+
+ private var visibleAlbums: [MusicVideoAlbumEntry] {
+ MusicVideoSourceBrowser.albums(
+ albumRows,
+ order: albumOrder,
+ hidesEmpty: hidesEmptyAlbums,
+ onlyIDs: nil,
+ query: albumSearch
+ )
+ }
+
+ private var albumPane: some View {
+ let rows = visibleAlbums
+ return VStack(spacing: 0) {
+ VStack(spacing: 8) {
+ searchField("アルバム名で検索", text: $albumSearch)
+ HStack(spacing: 10) {
+ Picker("並べ替え", selection: $albumOrder) {
+ ForEach(MusicVideoAlbumOrder.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .labelsHidden()
+ .fixedSize()
+ Toggle("空を隠す", isOn: $hidesEmptyAlbums)
+ .fixedSize()
+ .help("動画が1本もないアルバムを一覧から隠します")
+ Spacer(minLength: 0)
+ Menu {
+ Button("表示中のアルバムをすべて選ぶ") { viewModel.selectedAlbumIDs.formUnion(rows.map(\.id)) }
+ Button("表示中のアルバムの選択を外す") { viewModel.selectedAlbumIDs.subtract(rows.map(\.id)) }
+ } label: {
+ Text("まとめて")
+ }
+ .menuStyle(.button)
+ .buttonStyle(.quiet)
+ .menuIndicator(.visible)
+ .fixedSize()
+ }
+ .font(.appCaption)
+ }
+ .padding(12)
+
+ Divider().overlay(NeomorphicTheme.separator)
+
+ ScrollView {
+ LazyVStack(spacing: 2) {
+ allVideosRow
+ if rows.isEmpty {
+ Text("条件に合うアルバムがありません")
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .padding(.top, 24)
+ }
+ ForEach(rows) { albumRow($0) }
+ }
+ .padding(8)
+ }
+ }
+ .frame(width: Self.albumPaneWidth)
+ .background(NeomorphicTheme.sidebar)
+ }
+
+ private var allVideosRow: some View {
+ let isScope = scope == .all
+ return Button {
+ scope = .all
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: "film.stack")
+ .font(.system(size: 15))
+ .foregroundStyle(NeomorphicTheme.muted)
+ .frame(width: 28 + 64 + 10 - 28, height: 36)
+ Text("すべての動画")
+ .font(.appBodyStrong)
+ Spacer(minLength: 4)
+ Text(allVideos.count.formatted())
+ .font(.appCaption.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ .padding(.leading, 34)
+ .padding(.trailing, 8)
+ .padding(.vertical, 4)
+ .background(rowBackground(isScope))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("すべての動画 \(allVideos.count)本")
+ .accessibilityAddTraits(isScope ? .isSelected : [])
+ }
+
+ private func albumRow(_ entry: MusicVideoAlbumEntry) -> some View {
+ let isSelected = viewModel.selectedAlbumIDs.contains(entry.id)
+ let isScope = scope == .album(entry.id)
+ return HStack(spacing: 0) {
+ // 左のチェック: アルバムごと素材にする。
+ Button {
+ toggleAlbum(entry.id)
+ } label: {
+ checkmark(isSelected)
+ .frame(width: 34, height: 44)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(isSelected ? "このアルバムを素材から外す" : "このアルバムごと素材にする")
+ .accessibilityLabel("\(entry.title)を素材にする")
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+
+ // 行: 右に、このアルバムの動画を出す。
+ Button {
+ scope = .album(entry.id)
+ } label: {
+ HStack(spacing: 10) {
+ thumbnail(for: entry.coverVideoID, width: 64, height: 36)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(entry.title)
+ .font(.appBody)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if !entry.parent.isEmpty {
+ Text(entry.parent)
+ .font(.appMicro)
+ .foregroundStyle(NeomorphicTheme.muted)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ }
+ Spacer(minLength: 4)
+ Text(entry.count.formatted())
+ .font(.appCaption.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ .padding(.trailing, 8)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("\(entry.title) \(entry.count)本")
+ }
+ .padding(.vertical, 2)
+ .background(rowBackground(isScope))
+ }
+
+ private func rowBackground(_ isScope: Bool) -> some View {
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(isScope ? NeomorphicTheme.selection : Color.clear)
+ }
+
+ private func toggleAlbum(_ id: UUID) {
+ if viewModel.selectedAlbumIDs.contains(id) {
+ viewModel.selectedAlbumIDs.remove(id)
+ } else {
+ viewModel.selectedAlbumIDs.insert(id)
+ }
+ }
+
+ // MARK: - 右: 動画
+
+ /// 右に出す動画のもと(範囲で決まる)。
+ private var scopeVideos: [VideoItem] {
+ switch scope {
+ case .all:
+ return allVideos
+ case .album(let id):
+ guard let album = dataManager.albums.first(where: { $0.id == id }) else { return allVideos }
+ return MusicVideoSourceBrowser.videos(in: album, from: videosByID)
+ }
+ }
+
+ private var scopeTitle: String {
+ if case .album(let id) = scope, let entry = albumRows.first(where: { $0.id == id }) { return entry.title }
+ return "すべての動画"
+ }
+
+ private var visibleVideos: [VideoItem] {
+ MusicVideoSourceBrowser.videos(
+ scopeVideos,
+ order: videoOrder,
+ minimumLength: minimumLength,
+ favoritesOnly: favoritesOnly,
+ onlyIDs: onlySelected ? viewModel.selectedVideoIDs.union(albumVideoIDs) : nil,
+ query: videoSearch
+ )
+ }
+
+ private var videoPane: some View {
+ let videos = visibleVideos
+ return VStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(scopeTitle)
+ .font(.appHeadline)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text("\(videos.count.formatted())本")
+ .font(.appCaption.monospacedDigit())
+ .foregroundStyle(NeomorphicTheme.muted)
+ Spacer(minLength: 8)
+ if case .album(let id) = scope {
+ let isSelected = viewModel.selectedAlbumIDs.contains(id)
+ Button(isSelected ? "アルバムの選択を外す" : "このアルバムごと選ぶ") { toggleAlbum(id) }
+ .buttonStyle(.quiet)
+ }
+ Menu {
+ Button("表示中の動画をすべて選ぶ") { viewModel.selectedVideoIDs.formUnion(videos.map(\.id)) }
+ Button("表示中の動画の選択を外す") { viewModel.selectedVideoIDs.subtract(videos.map(\.id)) }
+ } label: {
+ Text("まとめて")
+ }
+ .menuStyle(.button)
+ .buttonStyle(.quiet)
+ .menuIndicator(.visible)
+ .fixedSize()
+ }
+
+ // 幅が広ければ1段、狭ければ2段にする(検索欄がつぶれないように、検索欄には最小の幅を持たせる)。
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 12) {
+ searchField("動画名で検索", text: $videoSearch)
+ .frame(minWidth: 200)
+ videoOrderPicker
+ minimumLengthPicker
+ videoToggles
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 12) {
+ searchField("動画名で検索", text: $videoSearch)
+ .frame(minWidth: 160)
+ videoOrderPicker
+ minimumLengthPicker
+ }
+ HStack(spacing: 12) { videoToggles }
+ }
+ }
+ .font(.appCaption)
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 14)
+
+ Divider().overlay(NeomorphicTheme.separator)
+
+ if videos.isEmpty {
+ VStack(spacing: 8) {
+ Image(systemName: "magnifyingglass")
+ .font(.system(size: 28, weight: .light))
+ Text("条件に合う動画がありません")
+ .font(.appBody)
+ }
+ .foregroundStyle(NeomorphicTheme.muted)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ ScrollView {
+ LazyVGrid(
+ columns: [GridItem(.adaptive(minimum: 176, maximum: 260), spacing: 16, alignment: .top)],
+ alignment: .leading,
+ spacing: 16
+ ) {
+ ForEach(videos) { videoCard($0) }
+ }
+ .padding(20)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ private var videoOrderPicker: some View {
+ Picker("並べ替え", selection: $videoOrder) {
+ ForEach(MusicVideoVideoOrder.allCases) { Text($0.rawValue).tag($0) }
+ }
+ .labelsHidden()
+ .fixedSize()
+ }
+
+ private var minimumLengthPicker: some View {
+ Picker("長さ", selection: $minimumLength) {
+ Text("すべての長さ").tag(1.0)
+ Text("5秒以上").tag(5.0)
+ Text("10秒以上").tag(10.0)
+ Text("30秒以上").tag(30.0)
+ }
+ .labelsHidden()
+ .fixedSize()
+ }
+
+ @ViewBuilder
+ private var videoToggles: some View {
+ Toggle("お気に入りのみ", isOn: $favoritesOnly)
+ .fixedSize()
+ Toggle("選択中のみ", isOn: $onlySelected)
+ .fixedSize()
+ }
+
+ private func videoCard(_ video: VideoItem) -> some View {
+ let individually = viewModel.selectedVideoIDs.contains(video.id)
+ let viaAlbum = albumVideoIDs.contains(video.id)
+ let isSelected = individually || viaAlbum
+ return Button {
+ // アルバムごと選んでいる動画は、ここでは外せない(アルバムの選択を外す)。
+ guard !viaAlbum else { return }
+ if individually { viewModel.selectedVideoIDs.remove(video.id) } else { viewModel.selectedVideoIDs.insert(video.id) }
+ } label: {
+ VStack(alignment: .leading, spacing: 6) {
+ Color.clear
+ .aspectRatio(16.0 / 9.0, contentMode: .fit)
+ .overlay { MusicVideoSourceThumbnail(video: video, dataManager: dataManager) }
+ .overlay(alignment: .topLeading) {
+ Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 18))
+ .foregroundStyle(.white)
+ .opacity(isSelected ? (viaAlbum && !individually ? 0.75 : 1) : 0.7)
+ .shadow(color: .black.opacity(0.55), radius: 2)
+ .padding(8)
+ }
+ .overlay(alignment: .topTrailing) {
+ if video.isFavorite {
+ Image(systemName: "heart.fill")
+ .font(.appMicro)
+ .foregroundStyle(.white)
+ .shadow(color: .black.opacity(0.55), radius: 2)
+ .padding(8)
+ }
+ }
+ .overlay(alignment: .bottomLeading) {
+ if viaAlbum {
+ badge("アルバム")
+ .padding(6)
+ }
+ }
+ .overlay(alignment: .bottomTrailing) {
+ badge(durationText(video.duration))
+ .padding(6)
+ }
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .overlay {
+ RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .strokeBorder(isSelected ? NeomorphicTheme.ink : Color.white.opacity(0.06), lineWidth: isSelected ? 2 : 1)
+ }
+ Text(video.originalFilename)
+ .font(.appCaption)
+ .lineLimit(2)
+ .truncationMode(.middle)
+ .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted)
+ .multilineTextAlignment(.leading)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(viaAlbum ? "アルバムごと選んでいます.外すには、左でアルバムの選択を外してください" : video.originalFilename)
+ .accessibilityLabel(video.originalFilename)
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ }
+
+ /// サムネイルの上に重ねる、読みやすい小さな札。
+ private func badge(_ text: String) -> some View {
+ Text(text)
+ .font(.appMicro.monospacedDigit())
+ .foregroundStyle(.white)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(Capsule().fill(Color.black.opacity(0.62)))
+ }
+
+ // MARK: - 下の帯
+
+ private var footer: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("使える動画 \(viewModel.candidateCount.formatted())本")
+ .font(.appBodyStrong)
+ Text(summaryDetail)
+ .font(.appCaption)
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ Spacer()
+ Button("すべて解除") { viewModel.clearSourceSelection() }
+ .disabled(viewModel.selectedAlbumIDs.isEmpty && viewModel.selectedVideoIDs.isEmpty && !viewModel.includeFavorites)
+ Button("完了", action: close)
+ .buttonStyle(.borderedProminent)
+ .keyboardShortcut(.defaultAction)
+ .accessibilityIdentifier("musicvideo.sourceDone")
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 14)
+ .background(NeomorphicTheme.canvas)
+ }
+
+ private var summaryDetail: String {
+ var parts: [String] = []
+ if !viewModel.selectedAlbumIDs.isEmpty { parts.append("アルバム \(viewModel.selectedAlbumIDs.count)個") }
+ if !viewModel.selectedVideoIDs.isEmpty { parts.append("動画 \(viewModel.selectedVideoIDs.count)本") }
+ if viewModel.includeFavorites { parts.append("お気に入り") }
+ let selection = parts.isEmpty ? "まだ何も選ばれていません" : parts.joined(separator: "・")
+ let limit = viewModel.sourceLimit
+ return viewModel.candidateCount > limit
+ ? "\(selection)(解析は無作為に選ぶ\(limit)本まで)"
+ : selection
+ }
+
+ // MARK: - 共通の部品
+
+ private func searchField(_ prompt: String, text: Binding) -> some View {
+ TextField(prompt, text: text)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ /// 選択の印。色を付けず、選択中は文字色・未選択は控えめな色にする。
+ private func checkmark(_ isSelected: Bool) -> some View {
+ Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 16))
+ .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted)
+ }
+
+ /// 動画のサムネイル。動画が無いとき(空のアルバム)は、枠だけを出す。
+ @ViewBuilder
+ private func thumbnail(for id: UUID?, width: CGFloat, height: CGFloat) -> some View {
+ if let id, let item = videosByID[id] {
+ MusicVideoSourceThumbnail(video: item, dataManager: dataManager)
+ .frame(width: width, height: height)
+ .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
+ } else {
+ RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(NeomorphicTheme.control)
+ .frame(width: width, height: height)
+ .overlay {
+ Image(systemName: "film")
+ .font(.appMicro)
+ .foregroundStyle(NeomorphicTheme.muted)
+ }
+ }
+ }
+
+ private func durationText(_ seconds: Double) -> String {
+ let total = Int(seconds.rounded())
+ if total >= 3600 { return String(format: "%d:%02d:%02d", total / 3600, (total % 3600) / 60, total % 60) }
+ return String(format: "%d:%02d", total / 60, total % 60)
+ }
+
+ // MARK: - 一覧の作成
+
+ private func rebuild() {
+ allVideos = MusicVideoSourceBrowser.usableVideos(dataManager.videos)
+ videosByID = Dictionary(allVideos.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
+ albumRows = MusicVideoAlbumEntry.entries(albums: dataManager.albums, videos: dataManager.videos)
+ // 見ていたアルバムが無くなっていたら、すべての動画へ戻す。
+ if case .album(let id) = scope, !dataManager.albums.contains(where: { $0.id == id }) { scope = .all }
+ updateAlbumVideoIDs()
+ }
+
+ private func updateAlbumVideoIDs() {
+ albumVideoIDs = MusicVideoSourceBrowser.videoIDs(
+ inAlbums: dataManager.albums,
+ selected: viewModel.selectedAlbumIDs,
+ from: videosByID
+ )
+ }
+}
+
+// MARK: - サムネイル
+
+/// 動画のサムネイルを、枠いっぱいに(縦横比を保って、はみ出しは切り落として)出す。
+/// `MacVideoThumbnailView` は正方形で出す部品なので、16:9 の枠には使えない。画像だけを取り出して使う。
+/// 読み込みのキャッシュ(メモリ・ディスク)と同時生成数の制限は、`MacVideoThumbnailView` と共有している。
+private struct MusicVideoSourceThumbnail: View {
+ let video: VideoItem
+ let dataManager: LibraryViewModel
+ @EnvironmentObject private var appSettings: AppSettings
+ @State private var image: NSImage?
+
+ var body: some View {
+ Color.clear
+ .overlay {
+ if let image {
+ Image(nsImage: image)
+ .resizable()
+ .scaledToFill()
+ } else {
+ LinearGradient(
+ colors: [Color.primary.opacity(0.08), Color.primary.opacity(0.16)],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ }
+ }
+ .clipped()
+ .task(id: video.id) {
+ image = await MacVideoThumbnailView.loadThumbnail(
+ for: video,
+ dataManager: dataManager,
+ thumbnailOption: appSettings.thumbnailOption,
+ customThumbnailTime: appSettings.customThumbnailTime
+ )
+ }
+ }
+}
diff --git a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift
index 3d3cab6..a6105df 100644
--- a/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift
+++ b/ArkServer/Features/MusicVideo/Views/MusicVideoView.swift
@@ -15,6 +15,8 @@ struct MusicVideoView: View {
@State private var isDropTargeted = false
@State private var isShowingSourcePicker = false
+ /// 素材・曲を選ぶ画面から戻ったとき、スクロールして見せる欄(`sourceAnchor` か `musicAnchor`)。
+ @State private var returnAnchor: String?
@State private var isShowingMusicPicker = false
@State private var isShowingExportAlbumPicker = false
/// プレビューを全画面で開く。
@@ -24,6 +26,8 @@ struct MusicVideoView: View {
@State private var dragStartRatio: Double?
private static let topAnchor = "musicvideo.top"
+ private static let sourceAnchor = "musicvideo.source"
+ private static let musicAnchor = "musicvideo.music"
/// プレビューを上に固定できる窓の高さ。これより低いときは、プレビューも一緒にスクロールする。
private static let pinnedPreviewMinimumHeight: CGFloat = 640
@@ -36,6 +40,67 @@ struct MusicVideoView: View {
private static let inlinePreviewContentHeight: CGFloat = 480
var body: some View {
+ Group {
+ if isShowingSourcePicker {
+ // 素材を選ぶあいだは、画面全体を使う(ポップアップにしない)。
+ MusicVideoSourcePickerView(viewModel: viewModel, dataManager: dataManager) {
+ isShowingSourcePicker = false
+ }
+ } else if isShowingMusicPicker {
+ // 曲を選ぶあいだも、画面全体を使う。
+ MusicVideoMusicPickerView(viewModel: viewModel) {
+ isShowingMusicPicker = false
+ }
+ } else {
+ mainContent
+ }
+ }
+ .background(CommandDeckBackground())
+ .navigationTitle("ミュージックビデオ")
+ // 設定画面と同じく、スイッチなどの「入」の色は青にする(内容側の既定は文字色の中立色)。
+ .tint(NeomorphicTheme.accent)
+ .overlay {
+ if isDropTargeted {
+ RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)
+ .strokeBorder(NeomorphicTheme.accent, style: StrokeStyle(lineWidth: 2, dash: [8, 6]))
+ .padding(8)
+ .allowsHitTesting(false)
+ }
+ }
+ .onDrop(of: [.fileURL], isTargeted: $isDropTargeted, perform: handleMusicDrop)
+ .onAppear { viewModel.attach(dataManager: dataManager) }
+ .onDisappear { viewModel.stopAllPlayback() }
+ .sheet(isPresented: $isShowingExportAlbumPicker) {
+ MusicVideoExportAlbumSheet(dataManager: dataManager, fileName: viewModel.suggestedFileName) { destination in
+ viewModel.exportToLibrary(dataManager: dataManager, destination: destination)
+ }
+ }
+ .alert(
+ "処理に失敗しました",
+ isPresented: Binding(
+ get: { viewModel.errorMessage != nil },
+ set: { if !$0 { viewModel.clearError() } }
+ )
+ ) {
+ Button("OK", role: .cancel) { viewModel.clearError() }
+ } message: {
+ Text(viewModel.errorMessage ?? "不明なエラーです.")
+ }
+ .alert(
+ "書き出しが完了しました",
+ isPresented: Binding(
+ get: { viewModel.resultMessage != nil },
+ set: { if !$0 { viewModel.clearResultMessage() } }
+ )
+ ) {
+ Button("OK", role: .cancel) { viewModel.clearResultMessage() }
+ } message: {
+ Text(viewModel.resultMessage ?? "")
+ }
+ }
+
+ /// ミュージックビデオの本体(プレビュー・曲・素材・調整項目)。
+ private var mainContent: some View {
GeometryReader { geometry in
// 調整項目を変えたときの変化をその場で見られるよう、窓が十分に高ければ、プレビューを上に固定する。
let pinsPreview = viewModel.plan != nil && geometry.size.height >= Self.pinnedPreviewMinimumHeight
@@ -74,7 +139,9 @@ struct MusicVideoView: View {
MusicVideoCutEditorView(viewModel: viewModel, dataManager: dataManager)
}
musicSection
+ .id(Self.musicAnchor)
sourceSection
+ .id(Self.sourceAnchor)
MusicVideoTuningSections(viewModel: viewModel)
}
.frame(maxWidth: settingsColumnWidth)
@@ -86,59 +153,17 @@ struct MusicVideoView: View {
.onChange(of: viewModel.plan != nil) { _, hasPlan in
if hasPlan { withAnimation { proxy.scrollTo(Self.topAnchor, anchor: .top) } }
}
+ // 素材・曲を選ぶ画面から戻ったときは、その欄を見せる。
+ .onAppear {
+ guard let anchor = returnAnchor else { return }
+ returnAnchor = nil
+ proxy.scrollTo(anchor, anchor: .top)
+ }
}
actionBar
}
}
- .background(CommandDeckBackground())
- .navigationTitle("ミュージックビデオ")
- // 設定画面と同じく、スイッチなどの「入」の色は青にする(内容側の既定は文字色の中立色)。
- .tint(NeomorphicTheme.accent)
- .overlay {
- if isDropTargeted {
- RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous)
- .strokeBorder(NeomorphicTheme.accent, style: StrokeStyle(lineWidth: 2, dash: [8, 6]))
- .padding(8)
- .allowsHitTesting(false)
- }
- }
- .onDrop(of: [.fileURL], isTargeted: $isDropTargeted, perform: handleMusicDrop)
- .onAppear { viewModel.attach(dataManager: dataManager) }
- .onDisappear { viewModel.stopAllPlayback() }
- .sheet(isPresented: $isShowingSourcePicker) {
- MusicVideoSourcePickerSheet(viewModel: viewModel, dataManager: dataManager)
- }
- .sheet(isPresented: $isShowingMusicPicker) {
- MusicVideoMusicPickerSheet(viewModel: viewModel)
- }
- .sheet(isPresented: $isShowingExportAlbumPicker) {
- MusicVideoExportAlbumSheet(dataManager: dataManager, fileName: viewModel.suggestedFileName) { destination in
- viewModel.exportToLibrary(dataManager: dataManager, destination: destination)
- }
- }
- .alert(
- "処理に失敗しました",
- isPresented: Binding(
- get: { viewModel.errorMessage != nil },
- set: { if !$0 { viewModel.clearError() } }
- )
- ) {
- Button("OK", role: .cancel) { viewModel.clearError() }
- } message: {
- Text(viewModel.errorMessage ?? "不明なエラーです.")
- }
- .alert(
- "書き出しが完了しました",
- isPresented: Binding(
- get: { viewModel.resultMessage != nil },
- set: { if !$0 { viewModel.clearResultMessage() } }
- )
- ) {
- Button("OK", role: .cancel) { viewModel.clearResultMessage() }
- } message: {
- Text(viewModel.resultMessage ?? "")
- }
}
// MARK: - プレビュー
@@ -265,7 +290,10 @@ struct MusicVideoView: View {
if let url = viewModel.musicURL {
MusicPreviewButton(preview: viewModel.preview, url: url) { viewModel.togglePreview(url) }
}
- Button("フォルダから…") { isShowingMusicPicker = true }
+ Button("フォルダから…") {
+ returnAnchor = Self.musicAnchor
+ isShowingMusicPicker = true
+ }
.buttonStyle(.quiet)
.help("曲を置いてあるフォルダから探して選びます")
.accessibilityIdentifier("musicvideo.musicFolder")
@@ -365,7 +393,10 @@ struct MusicVideoView: View {
.buttonStyle(.quiet)
.help("アルバムと動画の選択をすべて外します")
}
- Button("選ぶ…") { isShowingSourcePicker = true }
+ Button("選ぶ…") {
+ returnAnchor = Self.sourceAnchor
+ isShowingSourcePicker = true
+ }
.buttonStyle(.quiet)
.accessibilityIdentifier("musicvideo.chooseSource")
}
diff --git a/ArkServerTests/MusicVideoMusicBrowserTests.swift b/ArkServerTests/MusicVideoMusicBrowserTests.swift
new file mode 100644
index 0000000..3d9f692
--- /dev/null
+++ b/ArkServerTests/MusicVideoMusicBrowserTests.swift
@@ -0,0 +1,190 @@
+// ArkServerTests/MusicVideoMusicBrowserTests.swift
+
+import Foundation
+import Testing
+@testable import ArkServer
+
+/// 曲を選ぶ画面の、フォルダの走査・絞り込み・並べ替え・フォルダの階層。
+@Suite
+struct MusicVideoMusicBrowserTests {
+ private func file(
+ _ name: String,
+ folder: String = "",
+ daysAgo: Double = 0,
+ size: Int64 = 1_000
+ ) -> MusicVideoMusicFile {
+ let path = (folder.isEmpty ? "" : folder + "/") + name
+ return MusicVideoMusicFile(
+ url: URL(fileURLWithPath: "/music/" + path),
+ size: size,
+ modified: Date(timeIntervalSince1970: 1_700_000_000 - daysAgo * 86_400),
+ folder: folder
+ )
+ }
+
+ private func write(_ relativePath: String, in root: URL) throws {
+ let url = root.appendingPathComponent(relativePath)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("x".utf8).write(to: url)
+ }
+
+ // MARK: 走査
+
+ @Test
+ func scanFindsAudioFilesInSubfoldersAndSkipsOtherFiles() throws {
+ let root = try temporaryDirectory("music-scan")
+ defer { try? FileManager.default.removeItem(at: root) }
+ try write("top.mp3", in: root)
+ try write("notes.txt", in: root) // 音声ではない
+ try write("cover.jpg", in: root) // 音声ではない
+ try write(".hidden.mp3", in: root) // 隠しファイル
+ try write("Artist A/one.m4a", in: root)
+ try write("Artist A/Album 1/two.wav", in: root)
+ try write("Artist A/Album 1/three.mp3", in: root)
+ try write("Artist B/four.mp3", in: root)
+ try write("Player.app/Contents/Resources/inside.mp3", in: root) // パッケージの中は見ない
+
+ let result = MusicVideoMusicBrowser.scan(folder: root)
+ #expect(!result.hitLimit)
+
+ let titles = Set(result.files.map(\.title))
+ #expect(titles == ["top", "one", "two", "three", "four"])
+
+ // 選んだフォルダからの相対の場所が付く。
+ func folderOf(_ title: String) -> String? { result.files.first { $0.title == title }?.folder }
+ #expect(folderOf("top") == "")
+ #expect(folderOf("one") == "Artist A")
+ #expect(folderOf("two") == "Artist A/Album 1")
+ #expect(folderOf("four") == "Artist B")
+ // 大きさも読める。
+ #expect(result.files.allSatisfy { $0.size == 1 })
+ }
+
+ @Test
+ func scanStopsAtTheLimitAndSaysSo() throws {
+ let root = try temporaryDirectory("music-limit")
+ defer { try? FileManager.default.removeItem(at: root) }
+ for index in 0..<6 { try write("song\(index).mp3", in: root) }
+
+ let limited = MusicVideoMusicBrowser.scan(folder: root, limit: 4)
+ #expect(limited.files.count == 4)
+ #expect(limited.hitLimit)
+
+ let all = MusicVideoMusicBrowser.scan(folder: root, limit: 6)
+ #expect(all.files.count == 6)
+ #expect(all.hitLimit) // ちょうど上限に達したときも、これ以上あるかもしれないので、上限として扱う
+
+ let more = MusicVideoMusicBrowser.scan(folder: root, limit: 7)
+ #expect(more.files.count == 6)
+ #expect(!more.hitLimit)
+ }
+
+ @Test
+ func scanOfAMissingFolderIsEmpty() {
+ let result = MusicVideoMusicBrowser.scan(folder: URL(fileURLWithPath: "/no/such/folder-\(UUID().uuidString)"))
+ #expect(result.files.isEmpty)
+ #expect(!result.hitLimit)
+ }
+
+ @Test
+ func relativeFolderIsComputedFromTheChosenFolder() {
+ let root = ["/", "Users", "me", "Music"]
+ func relative(_ path: String) -> String {
+ MusicVideoMusicBrowser.relativeFolder(of: URL(fileURLWithPath: path), root: root)
+ }
+ #expect(relative("/Users/me/Music/a.mp3") == "")
+ #expect(relative("/Users/me/Music/Artist/a.mp3") == "Artist")
+ #expect(relative("/Users/me/Music/Artist/Album/a.mp3") == "Artist/Album")
+ // 選んだフォルダの外にあるように見えるときは、空にする(落ちない)。
+ #expect(relative("/Volumes/Other/a.mp3") == "")
+ #expect(relative("/Users/me/MusicOther/a.mp3") == "")
+ }
+
+ // MARK: フォルダの階層
+
+ @Test
+ func foldersCountSongsIncludingSubfoldersAndOrderParentsBeforeChildren() {
+ let files = [
+ file("root"), // 直下の曲は、どのフォルダにも入らない
+ file("a", folder: "Artist A"),
+ file("b", folder: "Artist A/Album 2"),
+ file("c", folder: "Artist A/Album 10"),
+ file("d", folder: "Artist A/Album 10"),
+ file("e", folder: "Artist B")
+ ]
+ let folders = MusicVideoMusicBrowser.folders(in: files)
+
+ #expect(folders.map(\.path) == [
+ "Artist A", "Artist A/Album 2", "Artist A/Album 10", // 親の次に子。数字は数として並ぶ(2 の次が 10)
+ "Artist B"
+ ])
+ // 数は、その下の曲も合わせた数。
+ #expect(folders.map(\.count) == [4, 1, 2, 1])
+ #expect(folders.map(\.depth) == [0, 1, 1, 0])
+ #expect(folders[1].name == "Album 2")
+ }
+
+ @Test
+ func aFolderScopeIncludesItsSubfoldersButNotSimilarlyNamedSiblings() {
+ let inside = file("inside", folder: "A")
+ let nested = file("nested", folder: "A/B")
+ let sibling = file("sibling", folder: "AB") // 名前が "A" で始まるだけの別のフォルダ
+ let root = file("root")
+ let files = [inside, nested, sibling, root]
+
+ func titles(_ folder: String?) -> Set {
+ Set(MusicVideoMusicBrowser.visible(files, folder: folder, order: .name, query: "").map(\.title))
+ }
+ #expect(titles("A") == ["inside", "nested"])
+ #expect(titles("A/B") == ["nested"])
+ #expect(titles("AB") == ["sibling"])
+ #expect(titles(nil) == ["inside", "nested", "sibling", "root"])
+ #expect(titles("") == ["inside", "nested", "sibling", "root"])
+ }
+
+ // MARK: 絞り込みと並べ替え
+
+ @Test
+ func songsAreSortedByNaturalNameOrByRecency() {
+ let files = [
+ file("Track 10", daysAgo: 1),
+ file("Track 2", daysAgo: 5),
+ file("Another", daysAgo: 0)
+ ]
+ func titles(_ order: MusicVideoMusicOrder) -> [String] {
+ MusicVideoMusicBrowser.visible(files, folder: nil, order: order, query: "").map(\.title)
+ }
+ #expect(titles(.name) == ["Another", "Track 2", "Track 10"])
+ #expect(titles(.recent) == ["Another", "Track 10", "Track 2"])
+ }
+
+ @Test
+ func searchIgnoresCaseAndSurroundingSpaces() {
+ let files = [file("Summer Night"), file("Winter"), file("夏の終わり")]
+ func titles(_ query: String) -> [String] {
+ MusicVideoMusicBrowser.visible(files, folder: nil, order: .name, query: query).map(\.title)
+ }
+ #expect(titles(" summer ") == ["Summer Night"])
+ #expect(titles("夏") == ["夏の終わり"])
+ #expect(titles("nothing").isEmpty)
+ #expect(titles(" ").count == 3) // 空白だけなら絞らない
+ }
+
+ @Test
+ func searchAndFolderScopeCombine() {
+ let files = [
+ file("love song", folder: "Pop"),
+ file("love ballad", folder: "Rock"),
+ file("other", folder: "Pop")
+ ]
+ let result = MusicVideoMusicBrowser.visible(files, folder: "Pop", order: .name, query: "love")
+ #expect(result.map(\.title) == ["love song"])
+ }
+
+ @Test
+ func savedSortOrderKeepsItsStoredValue() {
+ // 以前の版が `AppStorage` に保存した文字列を、そのまま読める。
+ #expect(MusicVideoMusicOrder(rawValue: "名前") == .name)
+ #expect(MusicVideoMusicOrder(rawValue: "新しい順") == .recent)
+ }
+}
diff --git a/ArkServerTests/MusicVideoSourceBrowserTests.swift b/ArkServerTests/MusicVideoSourceBrowserTests.swift
new file mode 100644
index 0000000..f79fd66
--- /dev/null
+++ b/ArkServerTests/MusicVideoSourceBrowserTests.swift
@@ -0,0 +1,175 @@
+// ArkServerTests/MusicVideoSourceBrowserTests.swift
+
+import Foundation
+import Testing
+@testable import ArkServer
+
+/// 素材を選ぶ画面の、一覧の絞り込み・並べ替え・表紙・「アルバムで選択済み」の判定。
+@Suite
+@MainActor
+struct MusicVideoSourceBrowserTests {
+ private func video(
+ _ name: String,
+ duration: Double = 30,
+ daysAgo: Double = 0,
+ favorite: Bool = false,
+ trashed: Bool = false,
+ type: MediaType = .video,
+ id: UUID = UUID()
+ ) -> VideoItem {
+ VideoItem(
+ id: id, originalFilename: name, internalFilename: "", duration: duration,
+ importDate: Date(timeIntervalSince1970: 1_700_000_000 - daysAgo * 86_400),
+ creationDate: nil, fileHash: "", mediaType: type, isFavorite: favorite, isInTrash: trashed
+ )
+ }
+
+ private func entry(_ name: String, count: Int, daysAgo: Double = 0, cover: UUID? = nil) -> MusicVideoAlbumEntry {
+ let components = name.components(separatedBy: "/")
+ return MusicVideoAlbumEntry(
+ id: UUID(), name: name, title: components.last ?? name,
+ parent: components.count > 1 ? components.dropLast().joined(separator: " / ") : "",
+ count: count, totalDuration: Double(count) * 30,
+ latestImport: Date(timeIntervalSince1970: 1_700_000_000 - daysAgo * 86_400),
+ coverVideoID: cover
+ )
+ }
+
+ // MARK: アルバム
+
+ @Test
+ func albumsAreSortedByNameCountOrRecency() {
+ let rows = [entry("b", count: 5, daysAgo: 1), entry("a", count: 9, daysAgo: 5), entry("c", count: 2, daysAgo: 0)]
+
+ func names(_ order: MusicVideoAlbumOrder) -> [String] {
+ MusicVideoSourceBrowser.albums(rows, order: order, hidesEmpty: false, onlyIDs: nil, query: "").map(\.name)
+ }
+ #expect(names(.name) == ["a", "b", "c"])
+ #expect(names(.count) == ["a", "b", "c"]) // 9, 5, 2
+ #expect(names(.recent) == ["c", "b", "a"]) // 新しい順
+ }
+
+ @Test
+ func albumNamesSortNaturallyAndByHierarchy() {
+ let rows = [entry("x/10", count: 1), entry("x/2", count: 1), entry("a/z", count: 1)]
+ let names = MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: false, onlyIDs: nil, query: "").map(\.name)
+ // 階層の名前から順に、数字は桁の大きさではなく数として並ぶ(2 の次が 10)。
+ #expect(names == ["a/z", "x/2", "x/10"])
+ }
+
+ @Test
+ func albumsCanHideEmptyOnesAndFilterBySelectionAndQuery() {
+ let empty = entry("empty", count: 0)
+ let kept = entry("Summer trip", count: 3)
+ let other = entry("Winter", count: 4)
+ let rows = [empty, kept, other]
+
+ #expect(MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: true, onlyIDs: nil, query: "").map(\.name) == ["Summer trip", "Winter"])
+ #expect(MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: false, onlyIDs: nil, query: "").count == 3)
+ // 選択中のみ
+ #expect(MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: true, onlyIDs: [other.id], query: "").map(\.name) == ["Winter"])
+ // 検索は、大文字小文字を区別せず、前後の空白を無視する。
+ #expect(MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: true, onlyIDs: nil, query: " summer ").map(\.name) == ["Summer trip"])
+ #expect(MusicVideoSourceBrowser.albums(rows, order: .name, hidesEmpty: true, onlyIDs: nil, query: "nothing").isEmpty)
+ }
+
+ @Test
+ func savedSortOrdersKeepTheirStoredValues() {
+ // 以前の版が `AppStorage` に保存した文字列を、そのまま読める(並べ替えの設定が初期化されない)。
+ #expect(MusicVideoAlbumOrder(rawValue: "名前") == .name)
+ #expect(MusicVideoAlbumOrder(rawValue: "件数の多い順") == .count)
+ #expect(MusicVideoAlbumOrder(rawValue: "最近追加した順") == .recent)
+ #expect(MusicVideoVideoOrder(rawValue: "追加が新しい順") == .recent)
+ #expect(MusicVideoVideoOrder(rawValue: "長い順") == .longest)
+ #expect(MusicVideoVideoOrder(rawValue: "名前") == .name)
+ }
+
+ // MARK: 動画
+
+ @Test
+ func videosFilterByLengthFavoritesSelectionAndQuery() {
+ let short = video("short", duration: 3)
+ let normal = video("Beach day", duration: 20)
+ let favorite = video("Party", duration: 40, favorite: true)
+ let all = [short, normal, favorite]
+
+ func ids(minimum: Double = 1, favoritesOnly: Bool = false, only: Set? = nil, query: String = "") -> [UUID] {
+ MusicVideoSourceBrowser.videos(all, order: .name, minimumLength: minimum, favoritesOnly: favoritesOnly, onlyIDs: only, query: query).map(\.id)
+ }
+ #expect(ids().count == 3)
+ #expect(Set(ids(minimum: 5)) == [normal.id, favorite.id]) // 5秒以上
+ #expect(Set(ids(minimum: 30)) == [favorite.id]) // 30秒以上
+ #expect(ids(favoritesOnly: true) == [favorite.id])
+ #expect(ids(only: [short.id, normal.id]).count == 2) // 選択中のみ
+ #expect(ids(query: "beach") == [normal.id]) // 検索
+ #expect(ids(minimum: 5, favoritesOnly: true, query: "par") == [favorite.id]) // 組み合わせ
+ }
+
+ @Test
+ func videosAreSortedByRecencyLengthOrName() {
+ let old = video("b-old", duration: 10, daysAgo: 30)
+ let recent = video("c-recent", duration: 20, daysAgo: 1)
+ let long = video("a-long", duration: 90, daysAgo: 10)
+ let all = [old, recent, long]
+
+ func names(_ order: MusicVideoVideoOrder) -> [String] {
+ MusicVideoSourceBrowser.videos(all, order: order, minimumLength: 1, favoritesOnly: false, onlyIDs: nil, query: "").map(\.originalFilename)
+ }
+ #expect(names(.recent) == ["c-recent", "a-long", "b-old"])
+ #expect(names(.longest) == ["a-long", "c-recent", "b-old"])
+ #expect(names(.name) == ["a-long", "b-old", "c-recent"])
+ }
+
+ @Test
+ func onlyVideosOutsideTheTrashCanBeUsed() {
+ let ok = video("ok")
+ let trashed = video("trashed", trashed: true)
+ let photo = video("photo", type: .photo)
+ let usable = MusicVideoSourceBrowser.usableVideos([ok, trashed, photo])
+ #expect(usable.map(\.id) == [ok.id])
+ }
+
+ // MARK: アルバムの中身・表紙・選択済みの判定
+
+ @Test
+ func albumContentsKeepTheAlbumOrderAndSkipUnusableItems() {
+ let first = video("first"), second = video("second"), trashed = video("trashed", trashed: true)
+ let photo = video("photo", type: .photo)
+ let byID = Dictionary(uniqueKeysWithValues: [first, second, trashed, photo].map { ($0.id, $0) })
+ // アルバムの並びは second → first。存在しない ID や、ゴミ箱・写真は飛ばす。
+ let album = Album(id: UUID(), name: "mix", videoIDs: [second.id, trashed.id, UUID(), photo.id, first.id], type: .mixed)
+
+ let inside = MusicVideoSourceBrowser.videos(in: album, from: byID)
+ #expect(inside.map(\.originalFilename) == ["second", "first"])
+ }
+
+ @Test
+ func albumEntryUsesTheFirstUsableVideoAsTheCover() {
+ let trashed = video("trashed", trashed: true)
+ let photo = video("photo", type: .photo)
+ let cover = video("cover")
+ let later = video("later")
+ let videos = [trashed, photo, cover, later]
+ let withCover = Album(id: UUID(), name: "with cover", videoIDs: [trashed.id, photo.id, cover.id, later.id], type: .mixed)
+ let onlyTrash = Album(id: UUID(), name: "only trash", videoIDs: [trashed.id], type: .video)
+
+ let entries = MusicVideoAlbumEntry.entries(albums: [withCover, onlyTrash], videos: videos)
+ #expect(entries.first { $0.name == "with cover" }?.coverVideoID == cover.id)
+ #expect(entries.first { $0.name == "with cover" }?.count == 2)
+ #expect(entries.first { $0.name == "only trash" }?.coverVideoID == nil) // 使える動画が無ければ表紙なし
+ }
+
+ @Test
+ func videosInSelectedAlbumsAreReportedForTheAlbumBadge() {
+ let a = video("a"), b = video("b"), c = video("c"), trashed = video("trashed", trashed: true)
+ let byID = Dictionary(uniqueKeysWithValues: [a, b, c, trashed].map { ($0.id, $0) })
+ let albumOne = Album(id: UUID(), name: "one", videoIDs: [a.id, trashed.id], type: .video)
+ let albumTwo = Album(id: UUID(), name: "two", videoIDs: [b.id], type: .video)
+ let unselected = Album(id: UUID(), name: "three", videoIDs: [c.id], type: .video)
+ let albums = [albumOne, albumTwo, unselected]
+
+ let ids = MusicVideoSourceBrowser.videoIDs(inAlbums: albums, selected: [albumOne.id, albumTwo.id], from: byID)
+ #expect(ids == [a.id, b.id]) // 選んでいないアルバムの c と、ゴミ箱の動画は入らない
+ #expect(MusicVideoSourceBrowser.videoIDs(inAlbums: albums, selected: [], from: byID).isEmpty)
+ }
+}