Repository Public
1// ORIX DJ2// File: App/Sources/Features/Library/LibrarySupport.swift3// Description: Small value types and helpers shared by the library screens: sources, table rows, the drag payload,4// key names and the harmonic / tempo compatibility wording.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI1112/// A source in the library sidebar. Hashable twin of `TrackQuery.Scope`.13enum LibrarySource: Hashable, Sendable {14 case all, favorites, unanalysed, missing15 case history(Int64?)16 case crate(Int64)17 case playlist(Int64)18 case smartCrate(Int64)1920 init(scope: TrackQuery.Scope) {21 switch scope {22 case .all: self = .all23 case .favorites: self = .favorites24 case .unanalysed: self = .unanalysed25 case .missing: self = .missing26 case let .history(id): self = .history(id)27 case let .crate(id): self = .crate(id)28 case let .playlist(id): self = .playlist(id)29 case let .smartCrate(id): self = .smartCrate(id)30 }31 }3233 var scope: TrackQuery.Scope {34 switch self {35 case .all: .all36 case .favorites: .favorites37 case .unanalysed: .unanalysed38 case .missing: .missing39 case let .history(id): .history(sessionID: id)40 case let .crate(id): .crate(id)41 case let .playlist(id): .playlist(id)42 case let .smartCrate(id): .smartCrate(id)43 }44 }4546 var symbol: String {47 switch self {48 case .all: "music.note.list"49 case .favorites: "heart"50 case .unanalysed: "waveform.badge.magnifyingglass"51 case .missing: "questionmark.folder"52 case .history: "clock.arrow.circlepath"53 case .crate: "shippingbox"54 case .playlist: "list.number"55 case .smartCrate: "gearshape.2"56 }57 }58}5960/// One line of the track table. A playlist or the history can show the same track more than once, so the row61/// identity is separate from the track identity.62struct LibraryRow: Identifiable, Equatable, Sendable {63 let id: Int6464 /// Index in the result (the playlist position when the playlist is shown in its own order).65 let position: Int66 let track: Track6768 // Sort keys for the table headers. The actual sorting is done by the library store.69 var title: String { track.title }70 var artist: String { track.artist }71 var genre: String { track.genre }72 var bpm: Double { track.bpm ?? 0 }73 var key: String { track.camelot ?? "" }74 var duration: Double { track.duration }75 var rating: Int { track.rating }76 var dateAdded: Date { track.dateAdded }77 var playCount: Int { track.playCount }7879 static func rows(from tracks: [Track]) -> [LibraryRow] {80 var seen = Set<Int64>()81 seen.reserveCapacity(tracks.count)82 var out: [LibraryRow] = []83 out.reserveCapacity(tracks.count)84 for (i, t) in tracks.enumerated() {85 let id = seen.insert(t.id).inserted ? t.id : -Int64(i + 1)86 out.append(LibraryRow(id: id, position: i, track: t))87 }88 return out89 }90}9192extension TrackQuery.SortKey {93 /// The store sort key for a table header comparator.94 static func from(_ comparator: KeyPathComparator<LibraryRow>?) -> TrackQuery.SortKey? {95 guard let path = comparator?.keyPath else { return nil }96 if path == \LibraryRow.title { return .title }97 if path == \LibraryRow.artist { return .artist }98 if path == \LibraryRow.genre { return .genre }99 if path == \LibraryRow.bpm { return .bpm }100 if path == \LibraryRow.key { return .key }101 if path == \LibraryRow.duration { return .duration }102 if path == \LibraryRow.rating { return .rating }103 if path == \LibraryRow.dateAdded { return .dateAdded }104 if path == \LibraryRow.playCount { return .playCount }105 return nil106 }107}108109/// Drag payload of a track row: the plain text `orix-track:<id>`, so any deck can accept the drop.110enum LibraryDrag {111 static let prefix = "orix-track:"112113 static func payload(_ trackID: Int64) -> String { prefix + String(trackID) }114115 static func trackIDs(from items: [String]) -> [Int64] {116 var out: [Int64] = []117 for item in items {118 for line in item.split(whereSeparator: \.isNewline) where line.hasPrefix(prefix) {119 if let id = Int64(line.dropFirst(prefix.count)), !out.contains(id) { out.append(id) }120 }121 }122 return out123 }124}125126enum LibraryKeyNames {127 /// "A minor" for "8A". Nil when the code is not a wheel position.128 static func musicalName(camelot: String?) -> String? {129 guard let camelot else { return nil }130 for tonic in 0 ..< 12 {131 for mode in [KeyMode.minor, .major] {132 let k = KeyEstimate(tonic: tonic, mode: mode)133 if k.camelot == camelot { return k.name }134 }135 }136 return nil137 }138}139140/// What the table compares every row against: the master (or only playing) deck.141struct HarmonicReference: Equatable, Sendable {142 var deck: Int143 var camelot: String?144 /// Tempo of the deck as it plays now, rounded to 0.1 BPM.145 var bpm: Double146}147148/// Key and tempo relation of a track to a reference, in words and symbols (never colour alone).149struct TrackCompatibility: Equatable {150 enum Level { case good, fair, poor, unknown }151152 var keyDistance: Int?153 var tempoPercent: Double?154155 init(referenceCamelot: String?, referenceBPM: Double?, camelot: String?, bpm: Double?) {156 keyDistance = AutoDJPlanner.keyDistance(referenceCamelot, camelot)157 tempoPercent = AutoDJPlanner.tempoChange(from: referenceBPM, to: bpm)158 }159160 var keyWords: String {161 switch keyDistance {162 case .none: String(localized: "key unknown")163 case 0: String(localized: "same key")164 case 1: String(localized: "neighbour")165 default: String(localized: "clash")166 }167 }168169 var tempoWords: String {170 guard let t = tempoPercent else { return String(localized: "tempo unknown") }171 return String(format: "%.1f %%", t)172 }173174 var level: Level {175 guard let k = keyDistance, let t = tempoPercent else { return .unknown }176 if k <= 1, t <= 4 { return .good }177 if k <= 1, t <= 8 { return .fair }178 return .poor179 }180181 var symbol: String {182 switch level {183 case .good: "checkmark.circle.fill"184 case .fair: "circle.lefthalf.filled"185 case .poor: "xmark.circle"186 case .unknown: "questionmark.circle"187 }188 }189190 var tint: Color {191 switch level {192 case .good: ORIX.Palette.success193 case .fair: ORIX.Palette.warning194 case .poor: ORIX.Palette.danger195 case .unknown: ORIX.Palette.textTertiary196 }197 }198199 var summary: String { "\(keyWords) · \(tempoWords)" }200}201202enum LibraryFormat {203 static func fileSize(_ bytes: Int64) -> String { ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) }204205 static func bpm(_ value: Double?) -> String { value.map { $0 > 0 ? String(format: "%.1f", $0) : "–" } ?? "–" }206207 static func percent(_ value: Double?) -> String { value.map { String(format: "%.0f %%", $0 * 100) } ?? "–" }208209 static func decibels(_ value: Double?, unit: String = "dB") -> String { value.map { String(format: "%+.1f %@", $0, unit) } ?? "–" }210211 static let day: Date.FormatStyle = .dateTime.year().month(.abbreviated).day()212 static let shortDay: Date.FormatStyle = .dateTime.year(.twoDigits).month(.twoDigits).day(.twoDigits)213 static let dayTime: Date.FormatStyle = .dateTime.month(.abbreviated).day().hour().minute()214}215216/// Five clickable stars. Clicking the current rating clears it.217struct RatingStars: View {218 var rating: Int219 var size: CGFloat = 10220 var onChange: (Int) -> Void221222 var body: some View {223 HStack(spacing: 1) {224 ForEach(1 ... 5, id: \.self) { n in225 Button { onChange(n == rating ? 0 : n) } label: {226 Image(systemName: n <= rating ? "star.fill" : "star")227 .font(.system(size: size))228 .foregroundStyle(n <= rating ? ORIX.Palette.warning : ORIX.Palette.textTertiary.opacity(0.6))229 .frame(width: size + 3, height: size + 6)230 .contentShape(Rectangle())231 }232 .buttonStyle(.plain)233 .accessibilityLabel(Text("\(n) stars"))234 }235 }236 .accessibilityElement(children: .contain)237 .accessibilityLabel("Rating")238 .accessibilityValue(Text("\(rating) of 5"))239 }240}241