SPB Git

Repository Public

LibraryTrackTable.swift 13.5 KB 251 lines swift

1// ORIX DJ2// File: App/Sources/Features/Library/LibraryTrackTable.swift3// Description: The track table (full and compact column sets): sortable headers that drive the store query, status4//              marks, clickable rating, harmonic / tempo match against the playing deck, drag source, context menu.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct LibraryTrackTable: View {12    @Environment(AppModel.self) private var model13    var controller: LibraryController14    var compact: Bool1516    var body: some View {17        Group { if compact { compactTable } else { fullTable } }18            .contextMenu(forSelectionType: Int64.self) { ids in19                // The menu is built by AppKit outside the view hierarchy, so it needs the model handed to it.20                LibraryTrackMenu(model: model, controller: controller, rowIDs: ids)21            } primaryAction: { ids in22                if let id = controller.trackIDs(forRows: ids).first { controller.loadOnFreeDeck(id, model: model) }23            }24            .scrollContentBackground(.hidden)25            .background(ORIX.Palette.canvas)26            .onKeyPress(.return) {27                guard let id = controller.selectedTrackIDs.first else { return .ignored }28                controller.loadOnFreeDeck(id, model: model); return .handled29            }30            .accessibilityIdentifier(compact ? "library-compact-table" : "library-table")31    }3233    private var fullTable: some View {34        @Bindable var controller = controller35        let scope = model.libraryScope36        return Table(of: LibraryRow.self, selection: $controller.selection, sortOrder: $controller.sortOrder) {37            TableColumn("Title", value: \.title) { (row: LibraryRow) in LibraryTitleCell(track: row.track, showStatus: true) }.width(min: 120, ideal: 150)38            TableColumn("Artist", value: \.artist) { (row: LibraryRow) in LibraryCellText(row.track.artist) }.width(min: 60, ideal: 84)39            TableColumn("BPM", value: \.bpm) { (row: LibraryRow) in LibraryNumber(LibraryFormat.bpm(row.track.bpm)) }.width(46)40            TableColumn("Key", value: \.key) { (row: LibraryRow) in LibraryKeyCell(track: row.track) }.width(38)41            TableColumn("Time", value: \.duration) { (row: LibraryRow) in LibraryNumber(formatTime(row.track.duration, tenths: false)) }.width(40)42            TableColumn("Match") { (row: LibraryRow) in LibraryMatchCell(track: row.track, reference: controller.reference) }.width(min: 96, ideal: 106)43            TableColumn("Rating", value: \.rating) { (row: LibraryRow) in44                RatingStars(rating: row.track.rating) { controller.setRating([row.track.id], $0, model: model) }45            }.width(74)46            TableColumn("Genre", value: \.genre) { (row: LibraryRow) in LibraryCellText(row.track.genre) }.width(min: 50, ideal: 64)47            TableColumn("Added", value: \.dateAdded) { (row: LibraryRow) in LibraryNumber(row.track.dateAdded.formatted(LibraryFormat.shortDay)) }.width(72)48            TableColumn("Plays", value: \.playCount) { (row: LibraryRow) in LibraryNumber(row.track.playCount > 0 ? "\(row.track.playCount)" : "–") }.width(36)49        } rows: {50            ForEach(controller.rows) { row in51                TableRow(row).draggable(LibraryDrag.payload(row.track.id))52            }53            .dropDestination(for: String.self) { index, items in54                controller.handleTableDrop(items, at: index, scope: scope, model: model)55            }56        }57    }5859    private var compactTable: some View {60        @Bindable var controller = controller61        let decks = model.deckCountShown62        return Table(of: LibraryRow.self, selection: $controller.selection, sortOrder: $controller.sortOrder) {63            TableColumn("Load") { (row: LibraryRow) in LibraryLoadButtons(model: model, trackID: row.track.id, decks: decks, controller: controller) }.width(decks == 4 ? 104 : 54)64            TableColumn("Title", value: \.title) { (row: LibraryRow) in LibraryTitleCell(track: row.track, showStatus: true) }.width(min: 150, ideal: 270)65            TableColumn("Artist", value: \.artist) { (row: LibraryRow) in LibraryCellText(row.track.artist) }.width(min: 80, ideal: 150)66            TableColumn("BPM", value: \.bpm) { (row: LibraryRow) in LibraryNumber(LibraryFormat.bpm(row.track.bpm)) }.width(52)67            TableColumn("Key", value: \.key) { (row: LibraryRow) in LibraryKeyCell(track: row.track) }.width(44)68            TableColumn("Time", value: \.duration) { (row: LibraryRow) in LibraryNumber(formatTime(row.track.duration, tenths: false)) }.width(48)69            TableColumn("Match") { (row: LibraryRow) in LibraryMatchCell(track: row.track, reference: controller.reference) }.width(min: 96, ideal: 124)70        } rows: {71            ForEach(controller.rows) { row in72                TableRow(row).draggable(LibraryDrag.payload(row.track.id))73            }74        }75    }76}7778// MARK: - Cells7980private struct LibraryCellText: View {81    var text: String82    init(_ text: String) { self.text = text }83    var body: some View { Text(verbatim: text).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1) }84}8586private struct LibraryNumber: View {87    var text: String88    init(_ text: String) { self.text = text }89    var body: some View { Text(verbatim: text).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1) }90}9192private struct LibraryTitleCell: View {93    var track: Track94    var showStatus: Bool95    var body: some View {96        HStack(spacing: 5) {97            if showStatus, track.missing || !track.isAnalysed { LibraryStatusMark(track: track) }98            Text(verbatim: track.title.isEmpty ? track.url.lastPathComponent : track.title).font(.system(size: 12, weight: .medium))99                .foregroundStyle(track.missing ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary).lineLimit(1)100            if track.favorite {101                Image(systemName: "heart.fill").font(.system(size: 8)).foregroundStyle(ORIX.Palette.accent).accessibilityLabel("Favourite")102            }103        }104    }105}106107/// Missing file or analysis pending, as a symbol with a spoken label and a tooltip.108private struct LibraryStatusMark: View {109    var track: Track110    var body: some View {111        if track.missing {112            Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 10)).foregroundStyle(ORIX.Palette.warning)113                .help("The audio file is missing: \(track.path)").accessibilityLabel("Missing file")114        } else if !track.isAnalysed {115            Image(systemName: "waveform.badge.magnifyingglass").font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary)116                .help("Not analysed yet. Tempo, key and loudness appear after the background analysis, or when the track is loaded on a deck.")117                .accessibilityLabel("Not analysed")118        } else {119            Color.clear.frame(width: 1, height: 1).accessibilityHidden(true)120        }121    }122}123124private struct LibraryKeyCell: View {125    var track: Track126    var body: some View {127        if let camelot = track.camelot {128            let name = LibraryKeyNames.musicalName(camelot: camelot) ?? track.key ?? camelot129            Text(verbatim: camelot).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)130                .help(Text(verbatim: name))131                .accessibilityLabel(Text(verbatim: name))132        } else {133            Text(verbatim: track.key ?? "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textTertiary)134        }135    }136}137138/// Key relation and tempo change against the playing deck: a symbol, words and a number.139private struct LibraryMatchCell: View {140    var track: Track141    var reference: HarmonicReference?142143    var body: some View {144        if let reference {145            let c = TrackCompatibility(referenceCamelot: reference.camelot, referenceBPM: reference.bpm, camelot: track.camelot, bpm: track.bpm)146            HStack(spacing: 4) {147                Image(systemName: c.symbol).font(.system(size: 10, weight: .semibold)).foregroundStyle(c.tint)148                Text(verbatim: c.summary).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)149            }150            .help("Against deck \(deckLetters[reference.deck]): key \(c.keyWords), tempo change \(c.tempoWords)")151            .accessibilityElement(children: .ignore)152            .accessibilityLabel(Text("Match with deck \(deckLetters[reference.deck])"))153            .accessibilityValue(Text(verbatim: c.summary))154        } else {155            Text(verbatim: "–").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)156                .help("Shown while a deck is playing.")157        }158    }159}160161private struct LibraryLoadButtons: View {162    /// Passed in: table cells live in their own hosting views, which do not always carry the environment.163    var model: AppModel164    var trackID: Int64165    var decks: Int166    var controller: LibraryController167168    var body: some View {169        HStack(spacing: 3) {170            ForEach(0 ..< decks, id: \.self) { d in171                let playing = controller.playingDecks[d]172                Button { controller.load(trackID, deck: d, model: model) } label: {173                    Text(verbatim: deckLetters[d]).font(.system(size: 10, weight: .heavy, design: .rounded))174                        .frame(width: 20, height: 17)175                        .foregroundStyle(playing ? ORIX.Palette.textTertiary : ORIX.deck(d))176                        .overlay(RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(playing ? ORIX.Palette.hairline : ORIX.deck(d), lineWidth: 1))177                        .contentShape(Rectangle())178                }179                .buttonStyle(.plain).disabled(playing)180                .help(playing ? "Deck \(deckLetters[d]) is playing. Pause it before loading another track." : "Load on deck \(deckLetters[d])")181                .accessibilityLabel(Text("Load on deck \(deckLetters[d])"))182                .accessibilityValue(playing ? Text("unavailable, the deck is playing") : Text(verbatim: ""))183            }184        }185    }186}187188// MARK: - Context menu189190struct LibraryTrackMenu: View {191    var model: AppModel192    var controller: LibraryController193    var rowIDs: Set<Int64>194195    var body: some View {196        let ids = controller.trackIDs(forRows: rowIDs)197        let tracks = controller.rows.filter { rowIDs.contains($0.id) }.map(\.track)198        if let first = ids.first {199            ForEach(0 ..< deckCount, id: \.self) { d in200                if controller.playingDecks[d] {201                    Button("Load to Deck \(deckLetters[d]) (deck is playing)") {}.disabled(true)202                } else {203                    Button("Load to Deck \(deckLetters[d])") { controller.load(first, deck: d, model: model) }204                }205            }206            Divider()207            Menu("Add to Crate") {208                ForEach(controller.crates) { c in Button { controller.addToCrate(ids, crate: c.id, model: model) } label: { Text(verbatim: c.name) } }209                if !controller.crates.isEmpty { Divider() }210                Button("New Crate…") { controller.nameRequest = LibraryNameRequest(purpose: .newCrate, text: String(localized: "New Crate")) }211            }212            Menu("Add to Playlist") {213                ForEach(controller.playlists) { p in Button { controller.addToPlaylist(ids, playlist: p.id, model: model) } label: { Text(verbatim: p.name) } }214                if !controller.playlists.isEmpty { Divider() }215                Button("New Playlist…") { controller.nameRequest = LibraryNameRequest(purpose: .newPlaylist, text: String(localized: "New Playlist")) }216            }217            scopeItems(ids: ids)218            Divider()219            let allFavourite = tracks.allSatisfy(\.favorite)220            Button(allFavourite ? "Remove from Favourites" : "Add to Favourites") { controller.setFavorite(ids, !allFavourite, model: model) }221            Menu("Rating") {222                ForEach((0 ... 5).reversed(), id: \.self) { n in223                    Button { controller.setRating(ids, n, model: model) } label: {224                        if n == 0 { Text("No rating") } else { Text(verbatim: String(repeating: "★", count: n) + "  \(n)") }225                    }226                }227            }228            Button("Edit Tags…") { controller.requestTags(ids) }229            Divider()230            Button("Show in Finder") { controller.showInFinder(ids) }231            Button("Analyse Again") { controller.analyseAgain(ids, model: model) }232            Divider()233            Button("Remove from Library…", role: .destructive) { controller.removalRequest = ids }234        }235    }236237    @ViewBuilder private func scopeItems(ids: [Int64]) -> some View {238        switch model.libraryScope {239        case let .crate(id):240            Button("Remove from This Crate") { controller.removeFromCrate(ids, crate: id, model: model) }241        case let .playlist(id):242            Button("Remove from This Playlist") { controller.removeFromPlaylist(rows: rowIDs, playlist: id, model: model) }243            if controller.sortKey == nil, model.librarySearch.isEmpty, let first = controller.rows.first(where: { rowIDs.contains($0.id) }), let last = controller.rows.last(where: { rowIDs.contains($0.id) }) {244                Button("Move Up") { controller.movePlaylistRows(rowIDs, playlist: id, to: first.position - 1, model: model) }.disabled(first.position == 0)245                Button("Move Down") { controller.movePlaylistRows(rowIDs, playlist: id, to: last.position + 2, model: model) }.disabled(last.position >= controller.rows.count - 1)246            }247        default: EmptyView()248        }249    }250}251
Files main
Menu

Theme