Repository Public
1// ORIX DJ2// File: App/Sources/Features/Library/LibrarySmartCrateEditor.swift3// Description: Smart-crate editor shown in the main library area: name, all/any, rules (field, comparison, values)4// and a live preview of the matching tracks computed by the library store off the main thread.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011extension SmartRule.Field {12 enum ValueKind { case number, text, tag, flag }1314 var valueKind: ValueKind {15 switch self {16 case .bpm, .rating, .year, .duration, .playCount, .dateAdded: .number17 case .title, .artist, .album, .genre, .key, .camelot, .format: .text18 case .tag: .tag19 case .favorite, .analysed: .flag20 }21 }2223 var title: LocalizedStringKey {24 switch self {25 case .bpm: "Tempo (BPM)"26 case .key: "Key name (Am, F♯)"27 case .camelot: "Key code (8A)"28 case .genre: "Genre"29 case .artist: "Artist"30 case .title: "Title"31 case .album: "Album"32 case .rating: "Rating (0–5)"33 case .favorite: "Favourite"34 case .tag: "Tag"35 case .year: "Year"36 case .duration: "Length (seconds)"37 case .dateAdded: "Added (days ago)"38 case .playCount: "Play count"39 case .analysed: "Analysed"40 case .format: "File format"41 }42 }4344 var comparisons: [SmartRule.Comparison] {45 switch valueKind {46 case .number: [.equals, .notEquals, .greaterThan, .lessThan, .between]47 case .text: [.contains, .equals, .notEquals, .greaterThan, .lessThan, .between]48 case .tag: [.equals, .notEquals, .contains]49 case .flag: [.equals]50 }51 }5253 var defaultValue: String {54 switch self {55 case .bpm: "124"56 case .rating: "3"57 case .year: "2020"58 case .duration: "240"59 case .playCount: "0"60 case .dateAdded: "30"61 case .favorite, .analysed: "true"62 case .camelot: "8A"63 case .format: "wav"64 default: ""65 }66 }67}6869extension SmartRule.Comparison {70 func title(for kind: SmartRule.Field.ValueKind) -> LocalizedStringKey {71 switch self {72 case .equals: "is"73 case .notEquals: "is not"74 case .contains: "contains"75 case .greaterThan: kind == .text ? "comes after" : "is more than"76 case .lessThan: kind == .text ? "comes before" : "is less than"77 case .between: "is between"78 }79 }80}8182struct LibrarySmartCrateEditor: View {83 @Environment(AppModel.self) private var model84 var controller: LibraryController8586 var body: some View {87 if let draft = controller.smartDraft {88 VStack(spacing: 0) {89 ScrollView { form(draft).padding(ORIX.Space.md) }90 .frame(maxHeight: 330)91 .background(ORIX.Palette.canvas)92 Divider().overlay(ORIX.Palette.hairline)93 preview94 }95 .task(id: draft) {96 try? await Task.sleep(nanoseconds: 200_000_000)97 guard !Task.isCancelled else { return }98 await controller.refreshSmartPreview(library: model.library)99 }100 .task(id: model.libraryRevision) { await controller.refreshSmartPreview(library: model.library) }101 .accessibilityIdentifier("library-smart-editor")102 }103 }104105 private func binding<T>(_ keyPath: WritableKeyPath<SmartCrateDraft, T>, fallback: T) -> Binding<T> {106 Binding(get: { controller.smartDraft?[keyPath: keyPath] ?? fallback }, set: { controller.smartDraft?[keyPath: keyPath] = $0 })107 }108109 private func form(_ draft: SmartCrateDraft) -> some View {110 Panel(padding: ORIX.Space.md) {111 VStack(alignment: .leading, spacing: ORIX.Space.sm) {112 HStack(spacing: ORIX.Space.xs) {113 Image(systemName: "gearshape.2").foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)114 Text(draft.crateID == nil ? "New Smart Crate" : "Edit Smart Crate").font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary)115 Spacer()116 Button("Cancel", role: .cancel) { controller.smartDraft = nil }.keyboardShortcut(.cancelAction)117 .accessibilityIdentifier("library-smart-cancel")118 Button(draft.crateID == nil ? "Create" : "Save") { controller.saveSmartDraft(model: model) }119 .keyboardShortcut(.defaultAction).disabled(controller.smartPreview.error != nil)120 .accessibilityIdentifier("library-smart-save")121 }122 HStack(spacing: ORIX.Space.xs) {123 Text("Name").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)124 TextField("Name", text: binding(\.name, fallback: "")).textFieldStyle(.roundedBorder).frame(maxWidth: 280)125 .accessibilityLabel("Smart crate name").accessibilityIdentifier("library-smart-name")126 Spacer().frame(width: ORIX.Space.md)127 Text("Tracks must match").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)128 Picker("Match", selection: binding(\.match, fallback: .all)) {129 Text("all rules").tag(SmartCrate.Match.all)130 Text("any rule").tag(SmartCrate.Match.any)131 }132 .pickerStyle(.segmented).labelsHidden().fixedSize()133 .accessibilityLabel("Tracks must match").accessibilityIdentifier("library-smart-match")134 }135 Divider().overlay(ORIX.Palette.hairline)136 if draft.rules.isEmpty {137 Text("No rule: the crate holds every track of the library.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)138 }139 ForEach(Array(draft.rules.enumerated()), id: \.element.id) { index, rule in140 LibrarySmartRuleRow(index: index, draft: rule, controller: controller)141 }142 HStack {143 Button { controller.smartDraft?.rules.append(SmartRuleDraft(rule: SmartRule(field: .genre, comparison: .contains, value: ""))) } label: { Label("Add Rule", systemImage: "plus") }144 .controlSize(.small).accessibilityIdentifier("library-smart-add-rule")145 Spacer()146 }147 }148 }149 }150151 private var preview: some View {152 let p = controller.smartPreview153 return VStack(spacing: 0) {154 HStack(spacing: ORIX.Space.xs) {155 SectionLabel("Live preview")156 if let error = p.error {157 Label { Text(verbatim: error) } icon: { Image(systemName: "exclamationmark.triangle.fill") }158 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).lineLimit(2)159 .accessibilityIdentifier("library-smart-error")160 } else {161 Text(p.count == 1 ? "1 track matches" : "\(p.count) tracks match").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)162 .accessibilityIdentifier("library-smart-count")163 if p.count > p.sample.count { Text("first \(p.sample.count) shown").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary) }164 }165 Spacer()166 }167 .padding(.horizontal, ORIX.Space.sm).frame(height: 30).background(ORIX.Palette.surface)168 Divider().overlay(ORIX.Palette.hairline)169 if p.error == nil, !p.sample.isEmpty {170 Table(p.sample) {171 TableColumn("Title") { t in Text(verbatim: t.title).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1) }172 TableColumn("Artist") { t in Text(verbatim: t.artist).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1) }173 TableColumn("BPM") { t in Text(verbatim: LibraryFormat.bpm(t.bpm)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary) }.width(52)174 TableColumn("Key") { t in Text(verbatim: t.camelot ?? "–").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textSecondary) }.width(44)175 TableColumn("Genre") { t in Text(verbatim: t.genre).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1) }176 TableColumn("Rating") { t in Text(verbatim: t.rating > 0 ? String(repeating: "★", count: t.rating) : "–").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary) }.width(70)177 }178 .scrollContentBackground(.hidden).background(ORIX.Palette.canvas)179 .accessibilityIdentifier("library-smart-preview")180 } else {181 Text(p.error == nil ? "No track matches these rules." : "Fix the rule above to see the matching tracks.")182 .font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).frame(maxWidth: .infinity, maxHeight: .infinity)183 }184 }185 }186}187188private struct LibrarySmartRuleRow: View {189 var index: Int190 var draft: SmartRuleDraft191 var controller: LibraryController192193 private func update(_ change: (inout SmartRule) -> Void) {194 guard let i = controller.smartDraft?.rules.firstIndex(where: { $0.id == draft.id }) else { return }195 change(&controller.smartDraft!.rules[i].rule)196 }197198 var body: some View {199 let rule = draft.rule200 let kind = rule.field.valueKind201 HStack(spacing: ORIX.Space.xs) {202 Picker("Field", selection: Binding(get: { rule.field }, set: { field in203 update { r in204 let old = r.field.valueKind205 r.field = field206 if !field.comparisons.contains(r.comparison) { r.comparison = field.comparisons[0] }207 if old != field.valueKind { r.value = field.defaultValue; r.upperValue = nil }208 if r.comparison == .between, r.upperValue == nil { r.upperValue = r.value }209 }210 })) {211 ForEach(SmartRule.Field.allCases, id: \.self) { f in Text(f.title).tag(f) }212 }213 .labelsHidden().frame(width: 170)214 .accessibilityLabel(Text("Rule \(index + 1) field")).accessibilityIdentifier("library-smart-rule-\(index)-field")215216 if kind == .flag {217 Picker("Value", selection: Binding(get: { ["true", "yes", "1", "on"].contains(rule.value.lowercased()) }, set: { v in update { $0.comparison = .equals; $0.value = v ? "true" : "false" } })) {218 Text("is yes").tag(true)219 Text("is no").tag(false)220 }221 .pickerStyle(.segmented).labelsHidden().fixedSize()222 .accessibilityLabel(Text("Rule \(index + 1) value")).accessibilityIdentifier("library-smart-rule-\(index)-flag")223 } else {224 Picker("Comparison", selection: Binding(get: { rule.comparison }, set: { c in225 update { r in r.comparison = c; r.upperValue = c == .between ? (r.upperValue ?? r.value) : nil }226 })) {227 ForEach(rule.field.comparisons, id: \.self) { c in Text(c.title(for: kind)).tag(c) }228 }229 .labelsHidden().frame(width: 130)230 .accessibilityLabel(Text("Rule \(index + 1) comparison")).accessibilityIdentifier("library-smart-rule-\(index)-comparison")231232 TextField(kind == .number ? "number" : "text", text: Binding(get: { rule.value }, set: { v in update { $0.value = v } }))233 .textFieldStyle(.roundedBorder).frame(width: kind == .number ? 80 : 180)234 .accessibilityLabel(Text("Rule \(index + 1) value")).accessibilityIdentifier("library-smart-rule-\(index)-value")235 if rule.comparison == .between {236 Text("and").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)237 TextField(kind == .number ? "number" : "text", text: Binding(get: { rule.upperValue ?? "" }, set: { v in update { $0.upperValue = v } }))238 .textFieldStyle(.roundedBorder).frame(width: kind == .number ? 80 : 180)239 .accessibilityLabel(Text("Rule \(index + 1) upper value")).accessibilityIdentifier("library-smart-rule-\(index)-upper")240 }241 }242 Spacer()243 Button { controller.smartDraft?.rules.removeAll { $0.id == draft.id } } label: { Image(systemName: "minus.circle") }244 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textSecondary)245 .accessibilityLabel(Text("Remove rule \(index + 1)")).accessibilityIdentifier("library-smart-rule-\(index)-remove")246 }247 .controlSize(.small)248 }249}250