SPB Git

Repository Public

LibraryView.swift 24.0 KB 451 lines swift

1// ORIX DJ2// File: App/Sources/Features/Library/LibraryView.swift3// Description: The music library: the full section (sidebar, track table, inspector) and the compact browser embedded4//              under the decks. Local files only; queries run off the main thread through the library store.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI10import UniformTypeIdentifiers1112struct LibraryView: View {13    var compact: Bool1415    @Environment(AppModel.self) private var model16    @State private var controller = LibraryController()17    @State private var appliedLaunchOptions = false1819    private struct ReloadKey: Equatable {20        var revision: Int21        var source: LibrarySource22        var search: String23        var sort: String24    }2526    private var reloadKey: ReloadKey {27        let c = controller.sortOrder.first28        return ReloadKey(revision: model.libraryRevision, source: LibrarySource(scope: model.libraryScope), search: model.librarySearch,29                         sort: "\(TrackQuery.SortKey.from(c)?.rawValue ?? "")/\(c?.order == .reverse ? "d" : "a")")30    }3132    /// `-ORIXLibraryCompact YES` previews the compact browser inside the Library section (screenshots).33    private var showCompact: Bool { compact || UserDefaults.standard.bool(forKey: "ORIXLibraryCompact") }3435    var body: some View {36        @Bindable var controller = controller37        Group {38            if showCompact {39                if compact { compactBody } else {40                    VStack(spacing: 0) {41                        Spacer(minLength: 0)42                        Divider().overlay(ORIX.Palette.hairline)43                        compactBody.frame(height: 260)44                    }45                }46            } else { fullBody }47        }48        .background(LibraryDeckObserver(controller: controller))49        .task(id: reloadKey) {50            // Search keystrokes and bursts of library changes are debounced; the first load is immediate.51            if controller.loaded { try? await Task.sleep(nanoseconds: 160_000_000) }52            guard !Task.isCancelled else { return }53            await controller.reload(library: model.library, scope: model.libraryScope, search: model.librarySearch)54            applyLaunchOptions()55        }56        .onChange(of: controller.selection) { _, _ in model.selectedTrackIDs = Set(controller.selectedTrackIDs) }57        .onDrop(of: [.fileURL], isTargeted: $controller.dropTargeted) { providers in controller.handleFileDrop(providers, model: model) }58        .overlay {59            if controller.dropTargeted {60                RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous)61                    .strokeBorder(ORIX.Palette.accent, style: StrokeStyle(lineWidth: 2, dash: [6, 4]))62                    .overlay(Label("Drop audio files or folders to import", systemImage: "square.and.arrow.down").font(ORIX.Typeface.title)63                        .padding(12).background(ORIX.Palette.surfaceRaised, in: Capsule()))64                    .padding(6).allowsHitTesting(false)65            }66        }67        .alert(nameTitle, isPresented: Binding(get: { controller.nameRequest != nil }, set: { if !$0 { controller.nameRequest = nil } })) {68            TextField("Name", text: Binding(get: { controller.nameRequest?.text ?? "" }, set: { controller.nameRequest?.text = $0 }))69                .accessibilityIdentifier("library-name-field")70            Button("Cancel", role: .cancel) { controller.nameRequest = nil }71            Button("OK") { controller.commitName(model: model) }.keyboardShortcut(.defaultAction)72        }73        .confirmationDialog(removalTitle, isPresented: Binding(get: { controller.removalRequest != nil }, set: { if !$0 { controller.removalRequest = nil } })) {74            Button("Remove from Library", role: .destructive) { controller.confirmRemoval(model: model) }75            Button("Cancel", role: .cancel) { controller.removalRequest = nil }76        } message: {77            Text("The tracks leave the library, its crates, playlists and history. The audio files are not deleted and stay where they are.")78        }79        .sheet(item: $controller.tagRequest) { request in LibraryTagSheet(request: request, controller: controller) }80        .sheet(isPresented: $controller.showImportFailures) { LibraryImportFailuresSheet(controller: controller) }81    }8283    private var nameTitle: LocalizedStringKey {84        switch controller.nameRequest?.purpose {85        case .newCrate: "New Crate"86        case .newPlaylist: "New Playlist"87        case .renameCrate: "Rename Crate"88        case .renamePlaylist: "Rename Playlist"89        case .renameSmartCrate: "Rename Smart Crate"90        case nil: "Name"91        }92    }9394    private var removalTitle: LocalizedStringKey {95        let n = controller.removalRequest?.count ?? 096        return n == 1 ? "Remove this track from the library?" : "Remove \(n) tracks from the library?"97    }9899    // MARK: Full section100101    private var fullBody: some View {102        HStack(spacing: 0) {103            LibrarySidebar(controller: controller)104                .frame(width: 204)105            Divider().overlay(ORIX.Palette.hairline)106            VStack(spacing: 0) {107                LibraryToolbar(controller: controller, compact: false)108                Divider().overlay(ORIX.Palette.hairline)109                if controller.smartDraft != nil {110                    LibrarySmartCrateEditor(controller: controller)111                } else {112                    mainContent113                }114                Divider().overlay(ORIX.Palette.hairline)115                LibraryFooter(controller: controller)116            }117            .frame(maxWidth: .infinity, maxHeight: .infinity)118            if controller.showInspector, controller.smartDraft == nil {119                Divider().overlay(ORIX.Palette.hairline)120                LibraryInspector(controller: controller)121                    .frame(width: 284)122            }123        }124        .background(ORIX.Palette.canvas)125        .accessibilityElement(children: .contain).accessibilityIdentifier("library-root")126    }127128    @ViewBuilder private var mainContent: some View {129        if !controller.loaded {130            Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)131        } else if controller.libraryCount == 0 {132            VStack(spacing: ORIX.Space.sm) {133                Image(systemName: "music.note.list").font(.system(size: 34, weight: .light)).foregroundStyle(ORIX.Palette.textTertiary)134                Text("Your library is empty").font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary)135                Text("Import audio files or folders from this Mac. ORIX DJ reads them where they are and never copies, moves or deletes them. To try the decks right away, add the demo tracks: six short pieces synthesised by ORIX DJ itself, with no samples.")136                    .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 460)137                HStack(spacing: ORIX.Space.xs) {138                    Button { controller.chooseFiles(model: model) } label: { Label("Import Music…", systemImage: "square.and.arrow.down") }139                        .keyboardShortcut(.defaultAction).accessibilityIdentifier("library-empty-import")140                    Button { model.installDemoTracks() } label: { Label("Add Demo Tracks", systemImage: "waveform") }141                        .accessibilityIdentifier("library-empty-demo")142                }143                .padding(.top, 4)144            }145            .padding(ORIX.Space.lg).frame(maxWidth: .infinity, maxHeight: .infinity)146            .accessibilityIdentifier("library-empty")147        } else if controller.rows.isEmpty {148            EmptyState(symbol: model.librarySearch.isEmpty ? "tray" : "magnifyingglass",149                       title: model.librarySearch.isEmpty ? "Nothing here yet" : "No track matches",150                       message: model.librarySearch.isEmpty ? "Drag tracks onto this source in the sidebar, or use Add to Crate / Add to Playlist from a track's menu." : "The search looks at title, artist, album, genre, tags and comment, ignoring case and accents.")151        } else {152            LibraryTrackTable(controller: controller, compact: false)153        }154    }155156    // MARK: Compact browser157158    private var compactBody: some View {159        VStack(spacing: 0) {160            LibraryToolbar(controller: controller, compact: true)161            Divider().overlay(ORIX.Palette.hairline)162            if controller.loaded, controller.libraryCount == 0 {163                HStack(spacing: ORIX.Space.sm) {164                    Text("The library is empty. Import music from this Mac, or add the demo tracks synthesised by ORIX DJ.")165                        .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)166                    Button("Import Music…") { controller.chooseFiles(model: model) }.accessibilityIdentifier("library-empty-import")167                    Button("Add Demo Tracks") { model.installDemoTracks() }.accessibilityIdentifier("library-empty-demo")168                }169                .controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)170            } else if controller.loaded, controller.rows.isEmpty {171                Text(model.librarySearch.isEmpty ? "This source has no tracks." : "No track matches the search.")172                    .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).frame(maxWidth: .infinity, maxHeight: .infinity)173            } else {174                LibraryTrackTable(controller: controller, compact: true)175            }176        }177        .background(ORIX.Palette.surface)178        .accessibilityElement(children: .contain).accessibilityIdentifier("library-compact")179    }180181    // MARK: Launch options (screenshots)182183    private func applyLaunchOptions() {184        guard !appliedLaunchOptions, controller.loaded, !controller.rows.isEmpty else { return }185        appliedLaunchOptions = true186        #if DEBUG187        let defaults = UserDefaults.standard188        // -ORIXLibrarySelect <n>: select the n-th row (1-based) so the inspector shows a track.189        let n = defaults.integer(forKey: "ORIXLibrarySelect")190        if n > 0, controller.rows.indices.contains(n - 1) { controller.selection = [controller.rows[n - 1].id] }191        // -ORIXLibrarySmartEditor YES: open the smart-crate editor on a new crate.192        if defaults.bool(forKey: "ORIXLibrarySmartEditor"), !compact { controller.newSmartCrate() }193        #endif194    }195}196197/// Follows the decks without making the whole library redraw 30 times per second: the controller is touched only when198/// the master deck, its key, its tempo (to 0.1 BPM) or the set of playing decks changes.199private struct LibraryDeckObserver: View {200    @Environment(AppModel.self) private var model201    var controller: LibraryController202203    private var reference: HarmonicReference? {204        let playing = model.decks.filter(\.playing)205        guard let deck = playing.first(where: \.isMaster) ?? playing.first, deck.track != nil else { return nil }206        return HarmonicReference(deck: deck.index, camelot: deck.track?.key?.transposed(semitones: Int(deck.keyShift.rounded())).camelot, bpm: (deck.bpm * 10).rounded() / 10)207    }208209    var body: some View {210        let ref = reference211        let playing = model.decks.map(\.playing)212        Color.clear213            .onChange(of: ref, initial: true) { _, new in if controller.reference != new { controller.reference = new } }214            .onChange(of: playing, initial: true) { _, new in if controller.playingDecks != new { controller.playingDecks = new } }215            .accessibilityHidden(true)216    }217}218219// MARK: - Toolbar and footer220221struct LibraryToolbar: View {222    @Environment(AppModel.self) private var model223    var controller: LibraryController224    var compact: Bool225    @FocusState private var searchFocused: Bool226227    var body: some View {228        @Bindable var model = model229        HStack(spacing: ORIX.Space.xs) {230            if compact {231                sourceMenu232            } else {233                Image(systemName: LibrarySource(scope: model.libraryScope).symbol).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)234                Text(verbatim: sourceTitle).font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)235                if case let .smartCrate(id) = model.libraryScope, let crate = controller.smartCrates.first(where: { $0.id == id }), controller.smartDraft == nil {236                    Button { controller.editSmartCrate(crate) } label: { Label("Edit Rules", systemImage: "slider.horizontal.3") }237                        .controlSize(.small).accessibilityIdentifier("library-smart-edit")238                }239            }240            Spacer(minLength: ORIX.Space.xs)241            if !controller.sortOrder.isEmpty {242                Button { controller.sortOrder = [] } label: { Label("Natural Order", systemImage: "arrow.uturn.backward") }243                    .controlSize(.small)244                    .help("Clears the column sort: playlists return to their own order, history to newest first.")245                    .accessibilityIdentifier("library-clear-sort")246            }247            HStack(spacing: 5) {248                Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)249                TextField("Search title, artist, album, genre, tags", text: $model.librarySearch)250                    .textFieldStyle(.plain).font(.system(size: 12)).focused($searchFocused)251                    .accessibilityLabel("Search the library").accessibilityIdentifier("library-search")252                if !model.librarySearch.isEmpty {253                    Button { model.librarySearch = "" } label: { Image(systemName: "xmark.circle.fill").font(.system(size: 11)) }254                        .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary).accessibilityLabel("Clear search")255                }256            }257            .padding(.horizontal, 8).frame(width: compact ? 260 : 300, height: 26)258            .background(ORIX.Palette.well, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))259            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(searchFocused ? ORIX.Palette.accent : ORIX.Palette.hairline))260            if compact {261                Text(countText).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).accessibilityIdentifier("library-count")262            }263            Button { controller.chooseFiles(model: model) } label: { Label("Import…", systemImage: "square.and.arrow.down") }264                .controlSize(.small).disabled(controller.isImporting)265                .help("Import audio files or folders. Files stay where they are.")266                .accessibilityIdentifier("library-import")267            if !compact {268                Button { controller.showInspector.toggle() } label: { Image(systemName: "sidebar.trailing") }269                    .controlSize(.small).help("Show or hide the track inspector")270                    .accessibilityLabel("Track inspector").accessibilityValue(controller.showInspector ? Text("shown") : Text("hidden"))271                    .accessibilityIdentifier("library-inspector-toggle")272            }273        }274        .padding(.horizontal, ORIX.Space.sm)275        .frame(height: compact ? 36 : 44)276        .background(ORIX.Palette.surface)277    }278279    private var countText: String {280        let n = controller.rows.count281        return n == 1 ? String(localized: "1 track") : String(localized: "\(n) tracks")282    }283284    private var sourceTitle: String { LibrarySourceNames.title(LibrarySource(scope: model.libraryScope), controller: controller) }285286    private var sourceMenu: some View {287        Menu {288            ForEach([LibrarySource.all, .favorites, .history(nil), .unanalysed, .missing], id: \.self) { s in289                Button { model.libraryScope = s.scope } label: { Label { Text(verbatim: LibrarySourceNames.title(s, controller: controller)) } icon: { Image(systemName: s.symbol) } }290            }291            if !controller.crates.isEmpty {292                Section("Crates") { ForEach(controller.crates) { c in Button { model.libraryScope = .crate(c.id) } label: { Text(verbatim: c.name) } } }293            }294            if !controller.playlists.isEmpty {295                Section("Playlists") { ForEach(controller.playlists) { p in Button { model.libraryScope = .playlist(p.id) } label: { Text(verbatim: p.name) } } }296            }297            if !controller.smartCrates.isEmpty {298                Section("Smart Crates") { ForEach(controller.smartCrates) { c in Button { model.libraryScope = .smartCrate(c.id) } label: { Text(verbatim: c.name) } } }299            }300        } label: {301            Label { Text(verbatim: sourceTitle).lineLimit(1) } icon: { Image(systemName: LibrarySource(scope: model.libraryScope).symbol) }302                .font(.system(size: 12, weight: .semibold))303        }304        .menuStyle(.borderlessButton).fixedSize()305        .accessibilityLabel("Library source").accessibilityValue(Text(verbatim: sourceTitle))306        .accessibilityIdentifier("library-source-menu")307    }308}309310enum LibrarySourceNames {311    @MainActor static func title(_ source: LibrarySource, controller: LibraryController) -> String {312        switch source {313        case .all: String(localized: "All Tracks")314        case .favorites: String(localized: "Favourites")315        case .unanalysed: String(localized: "Not Analysed")316        case .missing: String(localized: "Missing Files")317        case .history(nil): String(localized: "History")318        case let .history(id?): controller.sessions.first { $0.id == id }.map(sessionTitle) ?? String(localized: "History")319        case let .crate(id): controller.crates.first { $0.id == id }?.name ?? String(localized: "Crate")320        case let .playlist(id): controller.playlists.first { $0.id == id }?.name ?? String(localized: "Playlist")321        case let .smartCrate(id): controller.smartCrates.first { $0.id == id }?.name ?? String(localized: "Smart Crate")322        }323    }324325    static func sessionTitle(_ s: HistorySession) -> String {326        s.name.isEmpty ? s.startedAt.formatted(LibraryFormat.dayTime) : s.name327    }328}329330struct LibraryFooter: View {331    @Environment(AppModel.self) private var model332    var controller: LibraryController333334    var body: some View {335        HStack(spacing: ORIX.Space.sm) {336            Text(countText).accessibilityIdentifier("library-count")337            if let ref = controller.reference {338                HStack(spacing: 4) {339                    Text("Match column compares with")340                    DeckBadge(index: ref.deck, size: 14)341                    Text(verbatim: "\(ref.camelot ?? "–") · \(formatBPM(ref.bpm)) BPM")342                }343                .foregroundStyle(ORIX.Palette.textTertiary)344            }345            Spacer()346            if controller.importScanning {347                ProgressView().controlSize(.small)348                Text("Looking for audio files…")349                Button("Cancel") { controller.cancelImport() }.controlSize(.small).accessibilityIdentifier("library-import-cancel")350            } else if let p = controller.importProgress {351                ProgressView(value: Double(p.completed), total: Double(max(1, p.total))).frame(width: 110)352                    .accessibilityLabel("Import progress")353                Text("Importing \(p.completed) of \(p.total)")354                Button("Cancel") { controller.cancelImport() }.controlSize(.small).accessibilityIdentifier("library-import-cancel")355            }356            if let a = model.analysis {357                ProgressView(value: Double(a.completed), total: Double(max(1, a.total))).frame(width: 110)358                    .accessibilityLabel("Analysis progress")359                Text("Analysing \(a.completed + 1) of \(a.total)")360                Text(verbatim: a.currentTitle).lineLimit(1).frame(maxWidth: 140, alignment: .leading).foregroundStyle(ORIX.Palette.textTertiary)361                if a.failures > 0 { Label("\(a.failures) failed", systemImage: "exclamationmark.triangle").foregroundStyle(ORIX.Palette.warning) }362                Button("Cancel") { model.session.cancelAnalysis() }.controlSize(.small)363                    .help("Stops the background analysis after the current track. Tracks are analysed when they are loaded on a deck.")364                    .accessibilityIdentifier("library-analysis-cancel")365            }366            if !controller.importFailures.isEmpty {367                Button { controller.showImportFailures = true } label: {368                    Label("\(controller.importFailures.count) not imported", systemImage: "exclamationmark.triangle.fill")369                }370                .controlSize(.small).foregroundStyle(ORIX.Palette.warning)371                .accessibilityIdentifier("library-import-failures")372            }373        }374        .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)375        .padding(.horizontal, ORIX.Space.sm).frame(height: 28)376        .background(ORIX.Palette.surface)377    }378379    private var countText: String {380        let n = controller.rows.count, s = controller.selection.count381        let base = n == 1 ? String(localized: "1 track") : String(localized: "\(n) tracks")382        let total = controller.rows.reduce(0.0) { $0 + $1.track.duration }383        let length = n > 0 ? " · " + LibraryFooter.length(total) : ""384        return s > 0 ? base + length + " · " + String(localized: "\(s) selected") : base + length385    }386387    static func length(_ seconds: Double) -> String {388        let total = Int(seconds), h = total / 3600, m = (total % 3600) / 60389        return h > 0 ? String(format: "%d h %02d min", h, m) : String(format: "%d min", max(m, total > 0 ? 1 : 0))390    }391}392393// MARK: - Sheets394395struct LibraryTagSheet: View {396    @Environment(AppModel.self) private var model397    @Environment(\.dismiss) private var dismiss398    var request: LibraryTagRequest399    var controller: LibraryController400    @State private var text = ""401402    var body: some View {403        VStack(alignment: .leading, spacing: ORIX.Space.sm) {404            Text(request.trackIDs.count == 1 ? "Edit Tags" : "Edit Tags of \(request.trackIDs.count) Tracks").font(ORIX.Typeface.title)405            Text("Separate tags with commas. The list replaces the tags of every selected track.")406                .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)407            TextField("warm-up, vocal, peak time", text: $text).textFieldStyle(.roundedBorder)408                .accessibilityLabel("Tags").accessibilityIdentifier("library-tags-field")409                .onSubmit(save)410            HStack {411                Spacer()412                Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)413                Button("Save", action: save).keyboardShortcut(.defaultAction).accessibilityIdentifier("library-tags-save")414            }415        }416        .padding(ORIX.Space.md).frame(width: 420)417        .onAppear { text = request.text }418    }419420    private func save() {421        controller.setTags(request.trackIDs, LibraryController.parseTags(text), model: model)422        dismiss()423    }424}425426struct LibraryImportFailuresSheet: View {427    @Environment(\.dismiss) private var dismiss428    var controller: LibraryController429430    var body: some View {431        VStack(alignment: .leading, spacing: ORIX.Space.sm) {432            Text("Files that were not imported").font(ORIX.Typeface.title)433            List(Array(controller.importFailures.enumerated()), id: \.offset) { _, failure in434                VStack(alignment: .leading, spacing: 2) {435                    Text(verbatim: failure.url.lastPathComponent).font(.system(size: 12, weight: .medium))436                    Text(verbatim: failure.error.description).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)437                }438                .padding(.vertical, 2)439            }440            .frame(minHeight: 220)441            .accessibilityIdentifier("library-import-failures-list")442            HStack {443                Button("Clear List") { controller.importFailures = []; dismiss() }444                Spacer()445                Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)446            }447        }448        .padding(ORIX.Space.md).frame(width: 560, height: 360)449    }450}451
Files main
Menu

Theme