Repository Public
1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/ScriptExplorer.swift3// Description: Left pane of the Automation Studio: saved scripts (search, sort, favourites, tags, version history,4// import / export / backup) and the bundled presets by category.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI11import UniformTypeIdentifiers1213/// File operations on scripts shared by the explorer and the toolbar.14@MainActor15enum ScriptFiles {16 static var contentType: UTType { UTType(filenameExtension: LibraryStore.scriptFileExtension) ?? .plainText }1718 static func export(record: ScriptRecord, model: AppModel) {19 let panel = NSSavePanel()20 panel.allowedContentTypes = [contentType]21 panel.nameFieldStringValue = record.name + "." + LibraryStore.scriptFileExtension22 guard panel.runModal() == .OK, let url = panel.url else { return }23 let text = LibraryStore.scriptFileContents(record)24 Task {25 let failure: String? = await Task.detached {26 do { try Data(text.utf8).write(to: url, options: .atomic); return nil } catch { return error.localizedDescription }27 }.value28 model.show(notice: failure ?? "Exported \"\(record.name)\"")29 }30 }3132 /// Exports the active editor tab as it is on screen (saved or not).33 static func exportActive(model: AppModel) {34 guard let doc = model.activeDocument else { return }35 var record = ScriptRecord(id: doc.recordID ?? 0, name: doc.name, source: doc.source, origin: doc.origin)36 if let id = doc.recordID, let stored = try? model.library.script(id: id) { record = stored; record.source = doc.source }37 export(record: record, model: model)38 }3940 static func importScripts(model: AppModel) {41 let panel = NSOpenPanel()42 panel.allowedContentTypes = [contentType, .plainText]43 panel.allowsMultipleSelection = true44 panel.canChooseDirectories = false45 panel.message = String(localized: "Choose ORIX Script files (.orixdj). Each one is imported as a new script; nothing is overwritten.")46 guard panel.runModal() == .OK else { return }47 let urls = panel.urls48 let library = model.library49 Task {50 let outcome: ([ScriptRecord], [String]) = await Task.detached {51 var imported: [ScriptRecord] = [], failures: [String] = []52 for url in urls { do { imported.append(try library.importScript(from: url)) } catch { failures.append(error.localizedDescription) } }53 return (imported, failures)54 }.value55 model.libraryRevision += 156 for record in outcome.0 { model.open(record: record) }57 if let failure = outcome.1.first { model.show(notice: failure) }58 else { model.show(notice: "Imported \(outcome.0.count) script\(outcome.0.count == 1 ? "" : "s")") }59 }60 }6162 static func backupAll(model: AppModel) {63 let panel = NSOpenPanel()64 panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true65 panel.prompt = String(localized: "Back Up Here")66 panel.message = String(localized: "Choose a folder. Every saved script is written there as a .orixdj file; files with the same names are replaced.")67 guard panel.runModal() == .OK, let directory = panel.url else { return }68 let library = model.library69 Task {70 let outcome: Result<Int, LibraryError> = await Task.detached {71 do { return .success(try library.backupScripts(to: directory).count) }72 catch let e as LibraryError { return .failure(e) }73 catch { return .failure(.io(error.localizedDescription)) }74 }.value75 switch outcome {76 case let .success(n): model.show(notice: "Backed up \(n) script\(n == 1 ? "" : "s") to \(directory.lastPathComponent)")77 case let .failure(e): model.show(notice: e.localizedDescription)78 }79 }80 }81}8283struct ScriptExplorerView: View {84 enum Sort: String, CaseIterable, Identifiable { case name, date; var id: String { rawValue } }8586 @Environment(AppModel.self) private var model87 let studio: AutomationStudioState8889 @State private var records: [ScriptRecord] = []90 @State private var search = ""91 @State private var sort: Sort = .name92 @State private var favouritesOnly = false93 @State private var loadError: String?94 @State private var renaming: ScriptRecord?95 @State private var tagging: ScriptRecord?96 @State private var deleting: ScriptRecord?97 @State private var history: ScriptRecord?98 @State private var fieldText = ""99 @State private var expanded: Set<PresetCategory> = [.transitions]100101 private func reload() {102 do {103 var list = try model.library.scripts(search: search, favoritesOnly: favouritesOnly)104 if sort == .date { list.sort { $0.updatedAt > $1.updatedAt } }105 records = list; loadError = nil106 } catch { records = []; loadError = error.localizedDescription }107 }108109 /// Keeps open tabs in step with a record changed in the library (name, timestamp).110 private func refreshOpenDocument(_ record: ScriptRecord, replaceSource: Bool = false) {111 guard let i = model.documents.firstIndex(where: { $0.recordID == record.id }) else { return }112 model.documents[i].name = record.name113 model.documents[i].recordUpdatedAt = record.updatedAt114 if replaceSource { model.documents[i].source = record.source; model.documents[i].savedSource = record.source }115 }116117 private func attempt(_ work: () throws -> Void) {118 do { try work(); model.libraryRevision += 1; reload() } catch { model.show(notice: error.localizedDescription) }119 }120121 var body: some View {122 VStack(spacing: 0) {123 PaneHeader(title: "Scripts") {124 StudioIconButton(title: "New Script", symbol: "plus") { model.newDocument(); studio.mode = .editor }125 .accessibilityIdentifier("automation-explorer-new")126 StudioIconButton(title: "Import…", symbol: "square.and.arrow.down") { ScriptFiles.importScripts(model: model); studio.mode = .editor }127 .accessibilityIdentifier("automation-explorer-import")128 StudioIconButton(title: "Back Up All…", symbol: "externaldrive") { ScriptFiles.backupAll(model: model) }129 .accessibilityIdentifier("automation-explorer-backup")130 }131 VStack(spacing: 6) {132 HStack(spacing: 4) {133 Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)134 TextField("Search name, tags, source", text: $search).textFieldStyle(.plain).font(.system(size: 12))135 .accessibilityIdentifier("automation-explorer-search")136 if !search.isEmpty {137 Button { search = "" } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary).accessibilityLabel("Clear search")138 }139 }140 .padding(.horizontal, 8).frame(height: 26)141 .background(ORIX.Palette.well, in: RoundedRectangle(cornerRadius: ORIX.Radius.chip))142 HStack(spacing: 6) {143 Picker("Sort", selection: $sort) { Text("Name").tag(Sort.name); Text("Date").tag(Sort.date) }144 .pickerStyle(.segmented).labelsHidden().controlSize(.small)145 .accessibilityIdentifier("automation-explorer-sort")146 ToggleChip(title: "Favourites", symbol: favouritesOnly ? "star.fill" : "star", isOn: favouritesOnly, tint: ORIX.Palette.warning) { favouritesOnly.toggle() }147 .accessibilityIdentifier("automation-explorer-favourites")148 }149 }150 .padding(.horizontal, ORIX.Space.xs).padding(.bottom, 6)151 Divider().overlay(ORIX.Palette.hairline)152 ScrollView {153 LazyVStack(alignment: .leading, spacing: 0) {154 if let loadError { Text(verbatim: loadError).font(.system(size: 11)).foregroundStyle(ORIX.Palette.danger).padding(ORIX.Space.xs) }155 if records.isEmpty, loadError == nil {156 Text(search.isEmpty && !favouritesOnly ? "No saved script yet. Save the editor's script with ⌘S, or open a preset below." : "No script matches.")157 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).padding(ORIX.Space.sm)158 }159 ForEach(records) { record in scriptRow(record) }160 presets161 }162 }163 .accessibilityIdentifier("automation-explorer-list")164 }165 .background(ORIX.Palette.surface)166 .task(id: "\(model.libraryRevision)|\(search)|\(sort.rawValue)|\(favouritesOnly)") { reload() }167 .alert("Rename Script", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), presenting: renaming) { record in168 TextField("Name", text: $fieldText)169 Button("Rename") {170 attempt { let renamed = try model.library.renameScript(id: record.id, to: fieldText); refreshOpenDocument(renamed) }171 }172 Button("Cancel", role: .cancel) {}173 } message: { _ in Text("A name already in use gets a number added.") }174 .alert("Edit Tags", isPresented: Binding(get: { tagging != nil }, set: { if !$0 { tagging = nil } }), presenting: tagging) { record in175 TextField("Tags, separated by commas", text: $fieldText)176 Button("Save") {177 let tags = fieldText.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }178 attempt { refreshOpenDocument(try model.library.updateScript(id: record.id, tags: tags)) }179 }180 Button("Cancel", role: .cancel) {}181 }182 .confirmationDialog("Delete this script?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), presenting: deleting) { record in183 Button("Delete \"\(record.name)\"", role: .destructive) {184 attempt {185 try model.library.deleteScript(id: record.id)186 if let doc = model.documents.first(where: { $0.recordID == record.id }) { model.close(document: doc.id) }187 }188 }189 Button("Cancel", role: .cancel) {}190 } message: { _ in Text("The script and its version history are removed from the library. This cannot be undone.") }191 .sheet(item: $history) { record in192 ScriptHistorySheet(record: record) { restored in refreshOpenDocument(restored, replaceSource: true); model.libraryRevision += 1; reload() }193 }194 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-explorer")195 }196197 private func scriptRow(_ record: ScriptRecord) -> some View {198 let isOpen = model.documents.contains { $0.recordID == record.id && $0.id == model.activeDocumentID } && studio.mode == .editor199 return Button { model.open(record: record); studio.mode = .editor } label: {200 HStack(alignment: .top, spacing: 6) {201 Image(systemName: record.favorite ? "star.fill" : "doc.text").font(.system(size: 10)).frame(width: 14)202 .foregroundStyle(record.favorite ? ORIX.Palette.warning : ORIX.Palette.textTertiary).padding(.top, 2)203 .accessibilityLabel(record.favorite ? "Favourite" : "Script")204 VStack(alignment: .leading, spacing: 2) {205 Text(verbatim: record.name).font(.system(size: 12, weight: isOpen ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)206 HStack(spacing: 4) {207 Text(record.updatedAt, format: .dateTime.year().month(.abbreviated).day().hour().minute()).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary)208 if record.origin != .user { Text(verbatim: record.origin.rawValue).font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.accentSecondary) }209 }210 if !record.tags.isEmpty {211 Text(verbatim: record.tags.map { "#" + $0 }.joined(separator: " ")).font(.system(size: 10)).foregroundStyle(ORIX.Palette.accent).lineLimit(1)212 }213 }214 Spacer(minLength: 0)215 }216 .padding(.horizontal, ORIX.Space.xs).padding(.vertical, 5)217 .background(isOpen ? ORIX.Palette.surfaceRaised : .clear)218 .contentShape(Rectangle())219 }220 .buttonStyle(.plain)221 .accessibilityIdentifier("automation-script-\(record.id)")222 .contextMenu {223 Button("Open") { model.open(record: record); studio.mode = .editor }224 Button("Rename…") { fieldText = record.name; renaming = record }225 Button("Duplicate") { attempt { model.open(record: try model.library.duplicateScript(id: record.id)) } }226 Button(record.favorite ? "Remove from Favourites" : "Add to Favourites") { attempt { refreshOpenDocument(try model.library.updateScript(id: record.id, favorite: !record.favorite)) } }227 Button("Edit Tags…") { fieldText = record.tags.joined(separator: ", "); tagging = record }228 Button("Version History…") { history = record }229 Divider()230 Button("Export…") { ScriptFiles.export(record: record, model: model) }231 Divider()232 Button("Delete…", role: .destructive) { deleting = record }233 }234 }235236 private var presets: some View {237 VStack(alignment: .leading, spacing: 0) {238 HStack { SectionLabel("Bundled presets"); Spacer() }.padding(.horizontal, ORIX.Space.sm).frame(height: 28)239 .background(ORIX.Palette.surfaceRaised)240 ForEach(PresetCategory.allCases, id: \.self) { category in241 let items = PresetLibrary.all.filter { $0.category == category }242 if !items.isEmpty {243 Button { if expanded.contains(category) { expanded.remove(category) } else { expanded.insert(category) } } label: {244 HStack(spacing: 4) {245 Image(systemName: expanded.contains(category) ? "chevron.down" : "chevron.right").font(.system(size: 8, weight: .bold)).frame(width: 12)246 Text(verbatim: category.rawValue).font(.system(size: 11, weight: .semibold))247 Spacer()248 Text(verbatim: "\(items.count)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)249 }250 .foregroundStyle(ORIX.Palette.textSecondary)251 .padding(.horizontal, ORIX.Space.xs).frame(height: 24).contentShape(Rectangle())252 }253 .buttonStyle(.plain)254 .accessibilityValue(expanded.contains(category) ? Text("expanded") : Text("collapsed"))255 if expanded.contains(category) {256 ForEach(items) { preset in257 Button { model.newDocument(name: preset.name, source: preset.source, origin: .preset); studio.mode = .editor } label: {258 HStack(spacing: 6) {259 Image(systemName: "doc.badge.plus").font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 14)260 Text(verbatim: preset.name).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)261 Spacer(minLength: 0)262 }263 .padding(.leading, 20).padding(.trailing, ORIX.Space.xs).frame(height: 22).contentShape(Rectangle())264 }265 .buttonStyle(.plain)266 .help(Text(verbatim: preset.summary + " Opens an editable copy."))267 }268 }269 }270 }271 }272 .padding(.top, 6)273 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-explorer-presets")274 }275}276277/// Version history of a saved script: versions with dates, preview and Restore.278struct ScriptHistorySheet: View {279 @Environment(AppModel.self) private var model280 @Environment(\.dismiss) private var dismiss281 let record: ScriptRecord282 var onRestore: (ScriptRecord) -> Void283284 @State private var versions: [ScriptVersion] = []285 @State private var selected: Int64?286287 var body: some View {288 let version = versions.first { $0.id == selected }289 VStack(spacing: 0) {290 HStack {291 Text(verbatim: "Version history — \(record.name)").font(ORIX.Typeface.title).foregroundStyle(ORIX.Palette.textPrimary)292 Spacer()293 Button("Done") { dismiss() }.keyboardShortcut(.cancelAction)294 }295 .padding(ORIX.Space.sm)296 Divider().overlay(ORIX.Palette.hairline)297 HStack(spacing: 0) {298 List(versions, selection: $selected) { v in299 VStack(alignment: .leading, spacing: 1) {300 Text(verbatim: "Version \(v.version)" + (v.id == versions.first?.id ? " (current)" : "")).font(.system(size: 12, weight: .medium))301 Text(v.createdAt, format: .dateTime.year().month().day().hour().minute().second()).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textSecondary)302 }303 .tag(v.id)304 }305 .frame(width: 220)306 .accessibilityIdentifier("automation-history-list")307 Divider().overlay(ORIX.Palette.hairline)308 VStack(spacing: 0) {309 ScrollView {310 if let version { HighlightedSource(text: version.source).padding(ORIX.Space.sm) }311 else { Text("Select a version to preview it.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textTertiary).padding(ORIX.Space.lg) }312 }313 .background(ORIX.Palette.surface)314 Divider().overlay(ORIX.Palette.hairline)315 HStack {316 Text("Restoring appends the old text as a new version; history is never rewritten. An open tab of this script takes the restored text.")317 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)318 Spacer()319 Button("Restore This Version") {320 guard let version else { return }321 do {322 let restored = try model.library.restoreScriptVersion(scriptID: record.id, versionID: version.id)323 onRestore(restored)324 model.show(notice: "Restored version \(version.version) of \"\(record.name)\"")325 dismiss()326 } catch { model.show(notice: error.localizedDescription) }327 }328 .disabled(version == nil || version?.id == versions.first?.id)329 .accessibilityIdentifier("automation-history-restore")330 }331 .padding(ORIX.Space.xs)332 }333 }334 }335 .frame(width: 780, height: 500)336 .background(ORIX.Palette.canvas)337 .task {338 versions = (try? model.library.scriptVersions(scriptID: record.id)) ?? []339 selected = versions.first?.id340 }341 }342}343