SPB Git

Repository Public

AutomationSheet.swift 25.0 KB 468 lines swift

1// ORIX Docs2// File: App/Sources/Automation/AutomationSheet.swift3// Description: The Workflows sheet: choose a workflow, read its steps in plain language, choose the input and the output folder,4//              run with per-file and per-step progress, cancel, review results and warnings, and browse the execution history.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocAutomation1011struct AutomationSheet: View {12    let session: DocumentSession13    @State private var model: AutomationModel14    @State private var tab = Tab.run15    @State private var importProblem: String?1617    enum Tab: Hashable { case run, history }1819    init(session: DocumentSession) {20        self.session = session21        _model = State(initialValue: AutomationModel(session: session))22    }2324    var body: some View {25        VStack(spacing: 0) {26            header27            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)28            switch tab {29            case .run: runTab30            case .history: AutomationHistoryView(model: model)31            }32            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)33            footer34        }35        .frame(width: 820, height: 600)36        .background(ORIX.Palette.chrome)37        .accessibilityIdentifier("sheet.automation")38        .task {39            #if DEBUG40            // Documentation screenshots: run the selected workflow on the open document into a scratch folder.41            if UserDefaults.standard.string(forKey: "ORIXAutomationDemo") == "run" {42                model.outputFolder = FileManager.default.temporaryDirectory.appendingPathComponent("orix-automation-demo", isDirectory: true)43                model.replaceExisting = true44                model.run()45            }46            #endif47        }48    }4950    private var header: some View {51        HStack(spacing: ORIX.Space.m) {52            Image(systemName: "gearshape.2").font(.system(size: 18)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)53            VStack(alignment: .leading, spacing: 1) {54                Text("Workflows").font(ORIX.Font.title).foregroundStyle(ORIX.Palette.text).accessibilityAddTraits(.isHeader)55                Text("Repeatable document operations, run on this Mac.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)56            }57            Spacer()58            Picker("", selection: $tab) {59                Text("Run").tag(Tab.run)60                Text("History").tag(Tab.history)61            }62            .pickerStyle(.segmented).labelsHidden().frame(width: 180)63            .accessibilityLabel(Text("Run or history"))64            .accessibilityIdentifier("automation.tabs")65        }66        .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)67    }6869    private var footer: some View {70        HStack(spacing: ORIX.Space.m) {71            if model.isRunning {72                ProgressView(value: model.overallFraction).frame(width: 180)73                    .accessibilityLabel(Text("Overall progress"))74                Text("\(model.progress.filter { $0.run != nil }.count) of \(model.progress.count) done")75                    .font(ORIX.Font.label.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)76            } else if let d = model.lastDuration {77                let failed = model.progress.filter { $0.state == .failed }.count78                Label {79                    Text(failed == 0 ? "Finished in \(d.formatted(.number.precision(.fractionLength(2)))) s" : "Finished in \(d.formatted(.number.precision(.fractionLength(2)))) s — \(failed) failed")80                } icon: { Image(systemName: failed == 0 ? "checkmark.circle.fill" : "exclamationmark.triangle.fill") }81                .font(ORIX.Font.label).foregroundStyle(failed == 0 ? ORIX.Palette.positive : ORIX.Palette.warning)82            }83            Spacer()84            if model.isRunning {85                Button(String(localized: "Cancel")) { model.cancel() }86                    .buttonStyle(ORIXButtonStyle(prominent: false))87                    .keyboardShortcut(".", modifiers: .command)88                    .help("Stop after the current step; files not started are skipped (⌘.)")89                    .accessibilityIdentifier("automation.cancel")90            } else {91                Button(String(localized: "Close")) { session.activeSheet = nil }92                    .buttonStyle(ORIXButtonStyle(prominent: false))93                    .keyboardShortcut(.cancelAction)94                    .accessibilityIdentifier("automation.close")95                if tab == .run {96                    Button(String(localized: "Run")) { model.run() }97                        .buttonStyle(ORIXButtonStyle())98                        .disabled(!model.canRun).opacity(model.canRun ? 1 : 0.45)99                        .keyboardShortcut(.defaultAction)100                        .help("Run the workflow (↩)")101                        .accessibilityIdentifier("automation.run")102                }103            }104        }105        .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)106    }107108    // MARK: Run tab109110    private var runTab: some View {111        HStack(spacing: 0) {112            workflowList.frame(width: 232)113            Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)114            ScrollViewReader { proxy in115            ScrollView {116                VStack(alignment: .leading, spacing: ORIX.Space.l) {117                    if let workflow = model.selected {118                        steps(workflow)119                        inputSection120                        outputSection121                        if !model.progress.isEmpty { AutomationResultsView(model: model).id("results") }122                    } else {123                        EmptyState(symbol: "gearshape.2", title: "No workflow selected", message: "Choose a workflow on the left.")124                    }125                }126                .padding(ORIX.Space.xl)127                .frame(maxWidth: .infinity, alignment: .leading)128            }129            .background(ORIX.Palette.surface)130            // Progress and results appear below the settings: bring them into view when a run starts and when it ends.131            .onChange(of: model.isRunning) { _, _ in132                DispatchQueue.main.async { withAnimation(ORIX.Motion.quick) { proxy.scrollTo("results", anchor: .bottom) } }133            }134            }135        }136    }137138    private var workflowList: some View {139        VStack(alignment: .leading, spacing: 0) {140            ScrollView {141                VStack(alignment: .leading, spacing: 2) {142                    listTitle("Built-in")143                    ForEach(model.items.filter(\.isBuiltin)) { WorkflowRow(item: $0, selected: model.selectedID == $0.id) { id in model.selectedID = id } }144                    let saved = model.items.filter { !$0.isBuiltin }145                    if !saved.isEmpty || !model.rejected.isEmpty {146                        listTitle("Saved").padding(.top, ORIX.Space.m)147                        ForEach(saved) { WorkflowRow(item: $0, selected: model.selectedID == $0.id) { id in model.selectedID = id } }148                        ForEach(model.rejected, id: \.name) { r in149                            Label { Text(r.name).lineLimit(1) } icon: { Image(systemName: "exclamationmark.triangle") }150                                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.warning)151                                .padding(.horizontal, ORIX.Space.s).padding(.vertical, 4)152                                .help(Text(verbatim: r.problem))153                                .accessibilityLabel(Text("\(r.name) cannot be used: \(r.problem)"))154                        }155                    }156                }157                .padding(ORIX.Space.s)158            }159            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)160            VStack(alignment: .leading, spacing: ORIX.Space.xs) {161                Button(String(localized: "Add Workflow File…")) { importProblem = model.importWorkflow() }162                    .buttonStyle(.link).font(ORIX.Font.label)163                    .help("Add a workflow written as JSON. Files with unknown steps are refused.")164                    .accessibilityIdentifier("automation.import")165                if let importProblem {166                    Text(importProblem).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.critical).fixedSize(horizontal: false, vertical: true)167                }168            }169            .padding(ORIX.Space.m)170        }171        .background(ORIX.Palette.chrome)172    }173174    private func listTitle(_ title: LocalizedStringKey) -> some View {175        Text(title).font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)176            .padding(.horizontal, ORIX.Space.s).padding(.vertical, ORIX.Space.xs)177            .accessibilityAddTraits(.isHeader)178    }179180    private func sectionTitle(_ title: LocalizedStringKey) -> some View {181        Text(title).font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)182            .accessibilityAddTraits(.isHeader)183    }184185    private func steps(_ workflow: Workflow) -> some View {186        VStack(alignment: .leading, spacing: ORIX.Space.s) {187            Text(workflow.name).font(ORIX.Font.title).foregroundStyle(ORIX.Palette.text)188            if !workflow.summary.isEmpty {189                Text(workflow.summary).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)190            }191            sectionTitle("Steps").padding(.top, ORIX.Space.xs)192            VStack(alignment: .leading, spacing: 5) {193                ForEach(Array(workflow.steps.enumerated()), id: \.offset) { i, step in194                    HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {195                        Text("\(i + 1)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 16, alignment: .trailing)196                        Image(systemName: step.symbol).font(.system(size: 11)).foregroundStyle(ORIX.Palette.accent).frame(width: 16)197                        Text(step.localizedSummary).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text)198                    }199                    .accessibilityElement(children: .combine)200                    .accessibilityLabel(Text("Step \(i + 1): \(step.localizedSummary)"))201                }202            }203        }204        .accessibilityIdentifier("automation.steps")205    }206207    private var inputSection: some View {208        VStack(alignment: .leading, spacing: ORIX.Space.s) {209            sectionTitle("Input")210            Picker("", selection: $model.inputMode) {211                Text("This document (“\(model.documentName)”)").tag(AutomationModel.InputMode.currentDocument)212                Text(model.chosenFiles.isEmpty ? String(localized: "Files…") : String(localized: "\(model.chosenFiles.count) file(s)")).tag(AutomationModel.InputMode.files)213            }214            .pickerStyle(.radioGroup).labelsHidden()215            .accessibilityLabel(Text("Input"))216            .accessibilityIdentifier("automation.input")217            .disabled(model.isRunning)218            if model.inputMode == .files {219                HStack(spacing: ORIX.Space.s) {220                    Button(String(localized: "Choose Files…")) { model.chooseFiles() }221                        .buttonStyle(ORIXButtonStyle(prominent: false)).disabled(model.isRunning)222                        .accessibilityIdentifier("automation.chooseFiles")223                    if model.chosenFiles.isEmpty {224                        Text("No file chosen. Several files are processed as a batch.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)225                    } else {226                        Text(model.chosenFiles.prefix(3).map(\.lastPathComponent).joined(separator: ", ") + (model.chosenFiles.count > 3 ? "…" : ""))227                            .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).truncationMode(.middle)228                    }229                }230            } else {231                Text("The document is processed as it is now, unsaved changes included. It is not modified.")232                    .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)233            }234        }235    }236237    private var outputSection: some View {238        VStack(alignment: .leading, spacing: ORIX.Space.s) {239            sectionTitle("Output Folder")240            HStack(spacing: ORIX.Space.s) {241                Image(systemName: "folder").foregroundStyle(ORIX.Palette.textSecondary).accessibilityHidden(true)242                Text((model.outputFolder.path as NSString).abbreviatingWithTildeInPath).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text)243                    .lineLimit(1).truncationMode(.middle)244                    .accessibilityLabel(Text("Output folder: \(model.outputFolder.path)"))245                Spacer(minLength: ORIX.Space.s)246                Button(String(localized: "Change…")) { model.chooseOutputFolder() }247                    .buttonStyle(ORIXButtonStyle(prominent: false)).disabled(model.isRunning)248                    .accessibilityIdentifier("automation.chooseOutput")249            }250            Toggle(isOn: $model.replaceExisting) { Text("Replace files that already exist").font(ORIX.Font.label) }251                .toggleStyle(.checkbox).disabled(model.isRunning)252                .help("When off, a file that already exists is kept and the new one gets a number")253                .accessibilityIdentifier("automation.replace")254            Text("Workflows write only inside this folder.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)255        }256    }257}258259private struct WorkflowRow: View {260    let item: AutomationModel.Item261    let selected: Bool262    let select: (String) -> Void263    @State private var hover = false264265    var body: some View {266        Button { select(item.id) } label: {267            VStack(alignment: .leading, spacing: 1) {268                Text(item.workflow.name).font(.system(size: 12.5, weight: selected ? .semibold : .regular)).foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.text)269                Text("\(item.workflow.steps.count) steps").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)270            }271            .frame(maxWidth: .infinity, alignment: .leading)272            .padding(.horizontal, ORIX.Space.s).padding(.vertical, 6)273            .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(selected ? ORIX.Palette.accent.opacity(0.13) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))274            .contentShape(Rectangle())275        }276        .buttonStyle(.plain)277        .onHover { hover = $0 }278        .help(Text(verbatim: item.workflow.summary))279        .accessibilityLabel(Text(item.workflow.name))280        .accessibilityHint(Text(verbatim: item.workflow.summary))281        .accessibilityAddTraits(selected ? .isSelected : [])282        .accessibilityIdentifier("automation.workflow.\(item.workflow.id)")283    }284}285286/// Per-file progress while a run is in flight, then its outcome, warnings and outputs.287struct AutomationResultsView: View {288    let model: AutomationModel289290    var body: some View {291        VStack(alignment: .leading, spacing: ORIX.Space.s) {292            HStack {293                Text(model.isRunning ? "Progress" : "Results").font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)294                    .accessibilityAddTraits(.isHeader)295                Spacer()296                if !model.isRunning, !model.outputs.isEmpty {297                    Button(String(localized: "Show in Finder")) { model.showInFinder(model.outputs) }298                        .buttonStyle(.link).font(ORIX.Font.label)299                        .accessibilityIdentifier("automation.showInFinder")300                }301            }302            ForEach(model.progress) { file in FileResultRow(file: file) { model.showInFinder($0) } }303        }304        .accessibilityIdentifier("automation.results")305    }306}307308private struct FileResultRow: View {309    let file: AutomationModel.FileProgress310    let reveal: ([URL]) -> Void311312    private var icon: (String, Color) {313        switch file.state {314        case .waiting: return ("circle.dotted", ORIX.Palette.textTertiary)315        case .running: return ("arrow.triangle.2.circlepath", ORIX.Palette.accent)316        case .succeeded: return ("checkmark.circle.fill", ORIX.Palette.positive)317        case .failed: return ("xmark.octagon.fill", ORIX.Palette.critical)318        case .cancelled: return ("slash.circle", ORIX.Palette.textTertiary)319        }320    }321    private var stateText: String {322        switch file.state {323        case .waiting: return String(localized: "Waiting")324        case .running: return file.stepName.isEmpty ? String(localized: "Starting…") : file.stepName325        case .succeeded: return String(localized: "Done")326        case .failed: return String(localized: "Failed")327        case .cancelled: return String(localized: "Cancelled")328        }329    }330331    var body: some View {332        VStack(alignment: .leading, spacing: ORIX.Space.xs) {333            HStack(spacing: ORIX.Space.s) {334                Image(systemName: icon.0).foregroundStyle(icon.1).frame(width: 16).accessibilityHidden(true)335                Text(file.name).font(.system(size: 12.5, weight: .medium)).foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.middle)336                Spacer(minLength: ORIX.Space.s)337                Text(stateText).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)338                if let run = file.run { Text("\(run.duration.formatted(.number.precision(.fractionLength(2)))) s").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary) }339            }340            if file.state == .running {341                ProgressView(value: file.fraction).controlSize(.small)342                    .accessibilityLabel(Text("Progress of \(file.name)"))343            }344            if let run = file.run { RunDetail(run: run, reveal: reveal) }345        }346        .padding(ORIX.Space.s)347        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.chrome))348        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))349        .accessibilityElement(children: .contain)350        .accessibilityLabel(Text("\(file.name): \(stateText)"))351    }352}353354/// What one run did: its error, audit summary, warnings and the files written.355struct RunDetail: View {356    let run: WorkflowRun357    let reveal: ([URL]) -> Void358359    var body: some View {360        VStack(alignment: .leading, spacing: 3) {361            if let error = run.error {362                Label {363                    Text(verbatim: (error.stepIndex.map { String(localized: "Step \($0 + 1): ") } ?? "") + error.message).fixedSize(horizontal: false, vertical: true)364                } icon: { Image(systemName: "exclamationmark.circle") }365                .font(ORIX.Font.label).foregroundStyle(run.status == .cancelled ? ORIX.Palette.textSecondary : ORIX.Palette.critical)366            }367            if let audit = run.audit {368                Label { Text("Audit: \(audit.errors) error(s), \(audit.warnings) warning(s), \(audit.infos) note(s)") } icon: { Image(systemName: "checklist") }369                    .font(ORIX.Font.label).foregroundStyle(audit.errors > 0 ? ORIX.Palette.critical : ORIX.Palette.textSecondary)370            }371            ForEach(run.warnings.filter { $0.severity != .info }.prefix(6)) { w in372                Label { Text(verbatim: "\(w.feature): \(w.detail)").fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "exclamationmark.triangle") }373                    .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.warning)374            }375            let notes = run.warnings.filter { $0.severity == .info }.count, more = max(0, run.warnings.filter { $0.severity != .info }.count - 6)376            if notes + more > 0 {377                Text("\(notes + more) more note(s) from the converters").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)378            }379            ForEach(run.outputs, id: \.self) { path in380                Button { reveal([URL(fileURLWithPath: path)]) } label: {381                    Label { Text(verbatim: (path as NSString).lastPathComponent).lineLimit(1).truncationMode(.middle) } icon: { Image(systemName: "doc") }382                        .font(ORIX.Font.label)383                }384                .buttonStyle(.link)385                .help("Show in Finder")386                .accessibilityLabel(Text("Show \((path as NSString).lastPathComponent) in Finder"))387            }388        }389        .padding(.leading, 24)390    }391}392393/// The execution history, newest first.394struct AutomationHistoryView: View {395    let model: AutomationModel396    @State private var expanded: String?397398    var body: some View {399        VStack(spacing: 0) {400            if model.history.isEmpty {401                EmptyState(symbol: "clock.arrow.circlepath", title: "No runs yet", message: "Every workflow run is recorded here, with its steps, warnings and outputs.")402            } else {403                ScrollView {404                    LazyVStack(alignment: .leading, spacing: ORIX.Space.s) {405                        ForEach(model.history) { run in row(run) }406                    }407                    .padding(ORIX.Space.xl)408                }409                Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)410                HStack {411                    Text("\(model.history.count) run(s) kept on this Mac").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)412                    Spacer()413                    Button(String(localized: "Clear History")) { model.clearHistory() }.buttonStyle(.link).font(ORIX.Font.label)414                        .accessibilityIdentifier("automation.clearHistory")415                }416                .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.s)417            }418        }419        .frame(maxWidth: .infinity, maxHeight: .infinity)420        .background(ORIX.Palette.surface)421        .accessibilityIdentifier("automation.history")422    }423424    private func row(_ run: WorkflowRun) -> some View {425        let open = expanded == run.id426        let symbol = run.status == .succeeded ? "checkmark.circle.fill" : (run.status == .failed ? "xmark.octagon.fill" : "slash.circle")427        let color = run.status == .succeeded ? ORIX.Palette.positive : (run.status == .failed ? ORIX.Palette.critical : ORIX.Palette.textTertiary)428        return VStack(alignment: .leading, spacing: ORIX.Space.xs) {429            Button { expanded = open ? nil : run.id } label: {430                HStack(spacing: ORIX.Space.s) {431                    Image(systemName: symbol).foregroundStyle(color).frame(width: 16)432                    VStack(alignment: .leading, spacing: 1) {433                        Text(verbatim: "\(run.workflowName) — \(run.inputName)").font(.system(size: 12.5, weight: .medium)).foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.middle)434                        Text("\(run.started.formatted(date: .abbreviated, time: .shortened)) · \(run.duration.formatted(.number.precision(.fractionLength(2)))) s · \(run.outputs.count) file(s)")435                            .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)436                    }437                    Spacer(minLength: 0)438                    Image(systemName: open ? "chevron.down" : "chevron.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)439                }440                .contentShape(Rectangle())441            }442            .buttonStyle(.plain)443            .accessibilityLabel(Text("\(run.workflowName), \(run.inputName), \(run.status.rawValue)"))444            .accessibilityHint(Text("Shows the steps of this run"))445            if open {446                VStack(alignment: .leading, spacing: 2) {447                    ForEach(run.steps, id: \.index) { step in448                        HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {449                            Text(verbatim: "\(step.index + 1)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 16, alignment: .trailing)450                            Text(verbatim: step.name + (step.detail.isEmpty ? "" : " — \(step.detail)")).font(ORIX.Font.label)451                                .foregroundStyle(step.outcome == .failed ? ORIX.Palette.critical : (step.outcome == .succeeded ? ORIX.Palette.text : ORIX.Palette.textTertiary))452                                .fixedSize(horizontal: false, vertical: true)453                            Spacer(minLength: ORIX.Space.s)454                            Text(verbatim: step.outcome == .succeeded ? "\(Int((step.duration * 1000).rounded())) ms" : step.outcome.rawValue)455                                .font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)456                        }457                    }458                }459                .padding(.leading, 24)460                RunDetail(run: run) { model.showInFinder($0) }461            }462        }463        .padding(ORIX.Space.s)464        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.chrome))465        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))466    }467}468
Files main
Menu

Theme