SPB Git

Repository Public License

FlowPanel.swift 35.8 KB 615 lines swift

1// ORIX Convert — App/Sources/Features/Flow/FlowPanel.swift2// Description: Side panel of Conversion Flow: the editor of the selected step (destination and generated options,3//              name template with a live preview, condition builder, export folder), the run panel (inputs,4//              per-item progress and outcome, error policy, cancel) and the run history.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import SwiftUI89struct FlowPanel: View {10    @Environment(AppModel.self) private var model11    let flow: FlowModel1213    var body: some View {14        VStack(spacing: 0) {15            HStack {16                SegmentedPicker(selection: Binding(get: { flow.tab }, set: { flow.tab = $0 }),17                                options: [(FlowPanelTab.step, L("Step"), 0), (FlowPanelTab.run, L("Run"), flow.runItems.count), (FlowPanelTab.history, L("History"), 0)])18                Spacer(minLength: 0)19            }20            .padding(.horizontal, ORIX.Space.l).frame(height: 54)21            ORIX.Palette.hairline.frame(height: 1)22            switch flow.tab {23            case .step: StepEditor(flow: flow)24            case .run: RunPanel(flow: flow)25            case .history: HistoryPanel(flow: flow)26            }27        }28        .background(ORIX.Palette.surface)29        .accessibilityElement(children: .contain)30        .accessibilityLabel(L("Workflow panel"))31    }32}3334// MARK: - Step editor3536private struct StepEditor: View {37    @Environment(AppModel.self) private var model38    let flow: FlowModel3940    var body: some View {41        if let entry = flow.selectedEntry {42            VStack(spacing: 0) {43                ScrollView {44                    VStack(alignment: .leading, spacing: ORIX.Space.l) {45                        HStack(spacing: ORIX.Space.s) {46                            Image(systemName: entry.node.category.symbol).foregroundStyle(entry.node.category.color).accessibilityHidden(true)47                            Text(entry.node.category.title).font(.headline)48                            Spacer()49                            Text(L("Step %@", entry.path)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)50                        }51                        Text(entry.node.category.help).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)52                        ForEach(Array(flow.issues(for: entry.path).enumerated()), id: \.offset) { _, issue in53                            Banner(kind: issue.severity == .error ? .danger : .info, text: FlowMessages.text(issue))54                        }55                        editor(entry.node)56                    }57                    .padding(ORIX.Space.l)58                    .disabled(!flow.canEdit)59                }60                ORIX.Palette.hairline.frame(height: 1)61                HStack(spacing: ORIX.Space.s) {62                    IconButton(symbol: "arrow.up", label: L("Move Up")) { flow.moveSelection(by: -1) }63                    IconButton(symbol: "arrow.down", label: L("Move Down")) { flow.moveSelection(by: 1) }64                    Spacer()65                    Button(L("Duplicate")) { flow.duplicateSelection() }.buttonStyle(SecondaryButtonStyle())66                    Button(L("Delete")) { flow.deleteSelection() }.buttonStyle(SecondaryButtonStyle())67                }68                .padding(ORIX.Space.m)69                .disabled(!flow.canEdit)70            }71        } else {72            WorkflowSettings(flow: flow)73        }74    }7576    @ViewBuilder private func editor(_ node: FlowNode) -> some View {77        switch node.kind {78        case .convert(let destination, let operation, let options):79            ConvertEditor(flow: flow, id: node.id, destination: destination, operation: operation, options: options)80        case .rename(let template):81            RenameEditor(flow: flow, id: node.id, template: template)82        case .filter(let condition):83            ConditionEditor(condition: condition) { new in flow.update(node.id, actionName: L("Change Condition")) { $0.kind = .filter(new) } }84        case .branch(let condition, let then, let otherwise):85            ConditionEditor(condition: condition) { new in flow.update(node.id, actionName: L("Change Condition")) { $0.kind = .branch(new, then: then, otherwise: otherwise) } }86            Text(L("Files that match take the “If true” lane, the others the “Otherwise” lane. Both lanes join again after the branch."))87                .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)88        case .export(let folder, let policy):89            ExportEditor(flow: flow, id: node.id, folder: folder, policy: policy)90        }91    }92}9394/// Shown when no step is selected: name, description, error policy.95private struct WorkflowSettings: View {96    let flow: FlowModel97    var body: some View {98        ScrollView {99            if let document = flow.document {100                VStack(alignment: .leading, spacing: ORIX.Space.l) {101                    VStack(alignment: .leading, spacing: ORIX.Space.s) {102                        SectionLabel(L("Workflow"))103                        TextField(L("Workflow name"), text: Binding(get: { document.name }, set: { name in flow.edit(L("Rename Workflow")) { $0.name = name } }))104                            .textFieldStyle(.roundedBorder).disabled(!flow.canEdit)105                        TextField(L("Description"), text: Binding(get: { document.summary }, set: { text in flow.edit(L("Change Description")) { $0.summary = text } }), axis: .vertical)106                            .textFieldStyle(.roundedBorder).lineLimit(2...5).disabled(!flow.canEdit)107                    }108                    ErrorPolicyPicker(flow: flow)109                    VStack(alignment: .leading, spacing: ORIX.Space.s) {110                        SectionLabel(L("Steps"))111                        Text(L("Select a step on the canvas to edit it. Add steps from the palette above the canvas, or from the + on a connector."))112                            .font(.callout).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)113                    }114                }115                .padding(ORIX.Space.l)116            }117        }118    }119}120121private struct ErrorPolicyPicker: View {122    let flow: FlowModel123    var body: some View {124        if let document = flow.document {125            VStack(alignment: .leading, spacing: ORIX.Space.s) {126                SectionLabel(L("When a step fails"))127                Picker(L("When a step fails"), selection: Binding(get: { document.errorPolicy }, set: { policy in flow.edit(L("Change Error Policy")) { $0.errorPolicy = policy } })) {128                    Text(L("Stop this file")).tag(WorkflowErrorPolicy.stopItem)129                    Text(L("Skip the step and continue")).tag(WorkflowErrorPolicy.continueItem)130                }131                .pickerStyle(.menu).labelsHidden().fixedSize().disabled(!flow.canEdit)132                Text(document.errorPolicy == .stopItem ? L("The file ends at the failing step. Other files are never affected.") : L("The failing step is skipped; the next steps receive the unchanged file."))133                    .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)134            }135        }136    }137}138139private struct ConvertEditor: View {140    @Environment(AppModel.self) private var model141    let flow: FlowModel142    let id: UUID143    let destination: FormatID144    let operation: String?145    let options: ConversionOptions146    @State private var engineID: String?147148    var body: some View {149        let entries = TargetCatalog.everyEntry(registry: model.registry)150        let current = entries.first { $0.destination == destination && $0.operation == operation }151        let sets = TargetCatalog.optionSets(to: destination, operation: operation, registry: model.registry)152        let active = sets.first { $0.engine == engineID } ?? sets.first153        VStack(alignment: .leading, spacing: ORIX.Space.l) {154            VStack(alignment: .leading, spacing: ORIX.Space.s) {155                SectionLabel(L("Convert to"))156                TargetButton(entries: entries, current: current) { entry in157                    flow.update(id, actionName: L("Change Destination")) { $0.kind = .convert(destination: entry.destination, operation: entry.operation, options: ConversionOptions()) }158                }159                if current == nil {160                    Banner(kind: .danger, text: L("No engine of this build produces %@.", destination.displayName + (operation.map { " (\($0))" } ?? "")))161                }162            }163            let presets = model.presetList.filter { !$0.options.values.isEmpty || $0.operation != nil }164            if !presets.isEmpty {165                Menu {166                    ForEach(presets) { preset in167                        Button(preset.name + " · " + preset.destinationFormat.shortLabel) {168                            flow.update(id, actionName: L("Apply Preset")) { $0.kind = .convert(destination: preset.destinationFormat, operation: preset.operation, options: preset.options) }169                        }170                    }171                } label: { Label(L("Apply Preset"), systemImage: "bookmark") }172                .menuStyle(.button).buttonStyle(SecondaryButtonStyle()).fixedSize()173            }174            if sets.count > 1 {175                VStack(alignment: .leading, spacing: 4) {176                    SectionLabel(L("Settings for files handled by"))177                    Picker(L("Settings for files handled by"), selection: Binding(get: { active?.engine ?? "" }, set: { engineID = $0 })) {178                        ForEach(sets, id: \.engine) { Text($0.name).tag($0.engine) }179                    }180                    .pickerStyle(.menu).labelsHidden().fixedSize()181                    Text(L("Several engines produce this format, depending on the file that arrives. Each one reads the settings it knows."))182                        .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)183                }184            }185            if let active, !active.descriptors.isEmpty {186                OptionsForm(descriptors: active.descriptors, values: options.values) { key, value in187                    var next = options188                    if let descriptor = active.descriptors.first(where: { $0.id == key }), descriptor.defaultValue == value { next[key] = nil } else { next[key] = value }189                    flow.update(id, actionName: L("Change Setting")) { $0.kind = .convert(destination: destination, operation: operation, options: next) }190                }191                if !options.values.isEmpty {192                    Button(L("Reset to Defaults")) { flow.update(id, actionName: L("Reset Settings")) { $0.kind = .convert(destination: destination, operation: operation, options: ConversionOptions()) } }193                        .buttonStyle(SecondaryButtonStyle())194                }195            } else if current != nil {196                Text(L("This conversion has no settings.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)197            }198            if operation == nil {199                Label(L("A file that is already %@ is converted again when a setting here differs from its default; without any, it goes through unchanged.", destination.displayName), systemImage: "arrow.right.to.line")200                    .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)201            }202            if !options.secretKeys.isEmpty {203                Label(L("A password typed here is used by the runs you start now. It is never saved with the workflow."), systemImage: "lock")204                    .font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)205            }206        }207    }208}209210private struct RenameEditor: View {211    let flow: FlowModel212    let id: UUID213    let template: String214215    private var preview: String {216        let context = OutputNameContext(name: L("holiday photo"), ext: "heic", date: Date(), counter: 1, width: 4032, height: 3024)217        return OutputNameTemplate.render(template, context)218    }219220    var body: some View {221        VStack(alignment: .leading, spacing: ORIX.Space.m) {222            SectionLabel(L("Name template"))223            TextField("{name}", text: Binding(get: { template }, set: { text in flow.update(id, actionName: L("Change Name Template")) { $0.kind = .rename(text) } }))224                .textFieldStyle(.roundedBorder).font(.callout.monospaced())225                .accessibilityLabel(L("Name template"))226            FlowLayout(spacing: 5, lineSpacing: 5) {227                ForEach(OutputNameTemplate.tokens + ["{counter:3}"], id: \.self) { token in228                    Button(token) { flow.update(id, actionName: L("Change Name Template")) { $0.kind = .rename(template + token) } }229                        .buttonStyle(.plain).font(.caption.monospaced()).foregroundStyle(ORIX.Palette.accent)230                        .padding(.horizontal, 7).padding(.vertical, 3)231                        .background(ORIX.Palette.accentSoft, in: Capsule())232                        .accessibilityLabel(L("Insert %@", token))233                }234            }235            VStack(alignment: .leading, spacing: 3) {236                SectionLabel(L("Preview"))237                Text(preview.isEmpty ? "—" : preview + ".…").font(.callout.monospaced()).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(2).textSelection(.enabled)238                Text(L("For “%@”, first file of the run. The extension is the one of the exported file.", L("holiday photo") + ".heic"))239                    .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)240            }241            Text(L("The name applies to the exports that come after this step."))242                .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)243        }244    }245}246247/// Builder for conditions: clauses joined by "all" / "any". A condition nested deeper is shown as text.248struct ConditionEditor: View {249    @Environment(AppModel.self) private var model250    let condition: WorkflowCondition251    let onChange: (WorkflowCondition) -> Void252253    var body: some View {254        VStack(alignment: .leading, spacing: ORIX.Space.m) {255            SectionLabel(L("Condition"))256            if let draft = ConditionDraft(condition) {257                if draft.clauses.count > 1 {258                    Picker(L("Match"), selection: Binding(get: { draft.matchAll }, set: { value in var next = draft; next.matchAll = value; onChange(next.condition) })) {259                        Text(L("All of these")).tag(true)260                        Text(L("Any of these")).tag(false)261                    }262                    .pickerStyle(.segmented).labelsHidden()263                }264                ForEach(Array(draft.clauses.enumerated()), id: \.offset) { index, clause in265                    ClauseRow(clause: clause, formats: model.registry.sourceFormats, canRemove: draft.clauses.count > 1) { updated in266                        var next = draft267                        if let updated { next.clauses[index] = updated } else { next.clauses.remove(at: index) }268                        onChange(next.condition)269                    }270                }271                Button { var next = draft; next.clauses.append(ConditionClause()); onChange(next.condition) } label: { Label(L("Add a Test"), systemImage: "plus") }272                    .buttonStyle(SecondaryButtonStyle())273            } else {274                Text(condition.summary).font(.callout).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)275                Text(L("This condition is nested deeper than the builder edits. It works as it is; replace it to edit it here."))276                    .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)277                Button(L("Replace with a New Condition")) { onChange(ConditionDraft().condition) }.buttonStyle(SecondaryButtonStyle())278            }279            Text(L("Reads: %@.", condition.summary)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)280        }281    }282}283284private struct ClauseRow: View {285    let clause: ConditionClause286    let formats: [FormatID]287    let canRemove: Bool288    /// `nil` removes the clause.289    let onChange: (ConditionClause?) -> Void290291    private func set<T>(_ keyPath: WritableKeyPath<ConditionClause, T>) -> Binding<T> {292        Binding(get: { clause[keyPath: keyPath] }, set: { value in var next = clause; next[keyPath: keyPath] = value; onChange(next) })293    }294295    var body: some View {296        VStack(alignment: .leading, spacing: 6) {297            HStack(spacing: 6) {298                Picker(L("Test"), selection: set(\.kind)) { ForEach(ConditionClause.Kind.allCases) { Text($0.title).tag($0) } }299                    .labelsHidden().pickerStyle(.menu).fixedSize()300                Spacer(minLength: 0)301                Toggle(L("Not"), isOn: set(\.negated)).toggleStyle(.checkbox).controlSize(.small).help(L("Inverts this test"))302                if canRemove { IconButton(symbol: "minus.circle", label: L("Remove this test"), tint: ORIX.Palette.textTertiary) { onChange(nil) } }303            }304            switch clause.kind {305            case .format:306                Picker(L("Format"), selection: set(\.format)) { ForEach(formats.filter { $0 != .folder }, id: \.self) { Text($0.displayName).tag($0) } }307                    .labelsHidden().pickerStyle(.menu).fixedSize()308            case .category:309                Picker(L("Category"), selection: set(\.category)) { ForEach(FormatCategory.allCases.filter { $0 != .other }, id: \.self) { Text($0.title).tag($0) } }310                    .labelsHidden().pickerStyle(.menu).fixedSize()311            case .sizeAbove, .sizeBelow:312                HStack(spacing: 6) {313                    TextField(L("Size"), value: set(\.megabytes), format: .number.precision(.fractionLength(0...3))).textFieldStyle(.roundedBorder).frame(width: 90).multilineTextAlignment(.trailing)314                        .accessibilityLabel(L("Size in megabytes"))315                    Text(L("MB")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)316                }317            case .name:318                TextField("*.jpg", text: set(\.glob)).textFieldStyle(.roundedBorder).font(.callout.monospaced())319                    .accessibilityLabel(L("Name pattern"))320                    .help(L("* matches any text, ? one character. Upper and lower case are the same."))321            case .width, .height, .duration:322                HStack(spacing: 6) {323                    Picker(L("Comparison"), selection: set(\.comparison)) { ForEach(Comparison.allCases, id: \.self) { Text($0.symbol).tag($0) } }324                        .labelsHidden().pickerStyle(.menu).fixedSize()325                    TextField(L("Value"), value: set(\.number), format: .number.precision(.fractionLength(0...2))).textFieldStyle(.roundedBorder).frame(width: 90).multilineTextAlignment(.trailing)326                        .accessibilityLabel(L("Value"))327                    Text(clause.kind == .duration ? L("seconds") : L("px")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)328                }329            }330        }331        .padding(ORIX.Space.s)332        .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))333        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))334    }335}336337/// Folder row used by the export step, the run panel and the watch rules.338struct FolderField: View {339    let title: String340    let url: URL?341    var placeholder = L("No folder chosen")342    let choose: () -> Void343344    var body: some View {345        HStack(spacing: ORIX.Space.s) {346            Image(systemName: "folder").foregroundStyle(ORIX.Palette.textSecondary).accessibilityHidden(true)347            VStack(alignment: .leading, spacing: 1) {348                Text(url?.lastPathComponent ?? placeholder).font(.callout.weight(.medium)).foregroundStyle(url == nil ? ORIX.Palette.textSecondary : ORIX.Palette.textPrimary).lineLimit(1).truncationMode(.middle)349                if let url {350                    Text((url.deletingLastPathComponent().path as NSString).abbreviatingWithTildeInPath).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).truncationMode(.head)351                }352            }353            Spacer(minLength: 4)354            Button(L("Choose…"), action: choose).buttonStyle(SecondaryButtonStyle())355        }356        .padding(.leading, 10).padding(.trailing, 6).padding(.vertical, 6)357        .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))358        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))359        .accessibilityElement(children: .contain)360        .accessibilityLabel(title)361        .accessibilityValue(url.map { ($0.path as NSString).abbreviatingWithTildeInPath } ?? placeholder)362    }363}364365enum FolderPanel {366    /// The only way a folder enters a workflow or a rule: the user picks it.367    static func choose(message: String, starting: URL? = nil) -> URL? {368        let panel = NSOpenPanel()369        panel.canChooseFiles = false370        panel.canChooseDirectories = true371        panel.canCreateDirectories = true372        panel.allowsMultipleSelection = false373        panel.prompt = L("Choose")374        panel.message = message375        if let starting, FileManager.default.fileExists(atPath: starting.path) { panel.directoryURL = starting }376        return panel.runModal() == .OK ? panel.url : nil377    }378}379380private struct ExportEditor: View {381    let flow: FlowModel382    let id: UUID383    let folder: URL384    let policy: ConflictPolicy385386    var body: some View {387        VStack(alignment: .leading, spacing: ORIX.Space.l) {388            VStack(alignment: .leading, spacing: ORIX.Space.s) {389                SectionLabel(L("Folder"))390                FolderField(title: L("Export folder"), url: folder) {391                    if let url = FolderPanel.choose(message: L("Where should this step copy the files?"), starting: folder) {392                        flow.update(id, actionName: L("Change Folder")) { $0.kind = .export(url, policy) }393                    }394                }395                if !FileManager.default.fileExists(atPath: folder.path) {396                    Label(L("This folder does not exist yet; it is created when the first file is exported."), systemImage: "info.circle").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)397                        .fixedSize(horizontal: false, vertical: true)398                }399            }400            VStack(alignment: .leading, spacing: ORIX.Space.s) {401                SectionLabel(L("If the file exists"))402                Picker(L("If the file exists"), selection: Binding(get: { policy }, set: { value in flow.update(id, actionName: L("Change Conflict Policy")) { $0.kind = .export(folder, value) } })) {403                    ForEach([ConflictPolicy.rename, .skip, .replace], id: \.self) { Text($0.title).tag($0) }404                    if policy == .askUser { Text(ConflictPolicy.askUser.title).tag(ConflictPolicy.askUser) }405                }406                .pickerStyle(.menu).labelsHidden().fixedSize()407                Text(policy.explanation).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)408            }409            Text(L("The file is copied: the workflow continues with it, and your original is never moved."))410                .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)411        }412    }413}414415// MARK: - Run416417private struct RunPanel: View {418    let flow: FlowModel419420    var body: some View {421        VStack(spacing: 0) {422            ScrollView {423                VStack(alignment: .leading, spacing: ORIX.Space.l) {424                    if let error = flow.runError { Banner(kind: .danger, text: error) }425                    if !flow.isValid, flow.document != nil {426                        Banner(kind: .danger, text: L("This workflow cannot run yet"), detail: flow.issues.filter { $0.severity == .error }.map { FlowMessages.text($0) }.joined(separator: " "))427                    }428                    if let run = flow.lastRun { summary(run) }429                    VStack(alignment: .leading, spacing: ORIX.Space.s) {430                        HStack {431                            SectionLabel(L("Files"))432                            Spacer()433                            if !flow.runItems.isEmpty, !flow.isRunning { Button(L("Clear")) { flow.clearInputs() }.buttonStyle(.plain).font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.accent) }434                        }435                        if flow.runItems.isEmpty {436                            VStack(spacing: ORIX.Space.s) {437                                Image(systemName: "square.and.arrow.down.on.square").font(.system(size: 24, weight: .light)).foregroundStyle(ORIX.Palette.transformationDiagonal).accessibilityHidden(true)438                                Text(L("Drop files on the window, or choose them.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.center)439                                Button(L("Choose Files…")) { flow.chooseInputs() }.buttonStyle(SecondaryButtonStyle(prominent: true))440                            }441                            .frame(maxWidth: .infinity).padding(.vertical, ORIX.Space.xl)442                            .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))443                            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairlineStrong, style: StrokeStyle(lineWidth: 1, dash: [5, 4])))444                        } else {445                            VStack(spacing: 0) { ForEach(flow.runItems) { RunRow(flow: flow, item: $0) } }446                                .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))447                                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))448                            if !flow.isRunning { Button { flow.chooseInputs() } label: { Label(L("Add Files…"), systemImage: "plus") }.buttonStyle(SecondaryButtonStyle()) }449                        }450                    }451                    VStack(alignment: .leading, spacing: ORIX.Space.s) {452                        SectionLabel(L("Results without an export step go to"))453                        FolderField(title: L("Default folder"), url: flow.exportFolder, placeholder: L("Next to each source file")) { flow.chooseExportFolder() }454                        if flow.exportFolder != nil { Button(L("Use the Folder of Each Source")) { flow.exportFolder = nil }.buttonStyle(.plain).font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.accent) }455                    }456                    ErrorPolicyPicker(flow: flow)457                }458                .padding(ORIX.Space.l)459            }460            ORIX.Palette.hairline.frame(height: 1)461            HStack(spacing: ORIX.Space.s) {462                if flow.isRunning {463                    ORIXProgressRing(fraction: runFraction, size: 18, lineWidth: 2.5, label: L("Run progress"))464                    Text(L("%lld of %lld", flow.runItems.filter { $0.result != nil }.count, flow.runItems.count)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)465                    Spacer()466                    Button(L("Cancel Run")) { flow.cancelRun() }.buttonStyle(SecondaryButtonStyle())467                } else {468                    Text(flow.runItems.isEmpty ? L("No file yet") : (flow.runItems.count == 1 ? L("1 file") : L("%lld files", flow.runItems.count))).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)469                    Spacer()470                    Button { flow.run() } label: { Label(L("Run"), systemImage: "play.fill") }.buttonStyle(PrimaryButtonStyle()).disabled(!flow.canRun)471                }472            }473            .padding(ORIX.Space.m)474        }475    }476477    /// Finished items plus the measured fractions of the running ones; `nil` until something was measured.478    private var runFraction: Double? {479        let total = flow.runItems.count480        guard total > 0 else { return nil }481        let done = flow.runItems.filter { $0.result != nil }.count482        let partial = flow.runItems.compactMap { $0.result == nil ? $0.progress?.fraction : nil }.reduce(0, +)483        return done > 0 || partial > 0 ? min(1, (Double(done) + partial) / Double(total)) : nil484    }485486    private func summary(_ run: WorkflowRunResult) -> some View {487        let done = run.count(.succeeded) + run.count(.succeededWithErrors), failed = run.count(.failed)488        var parts: [String] = []489        if done > 0 { parts.append(L("%lld done", done)) }490        if run.count(.filtered) > 0 { parts.append(L("%lld filtered out", run.count(.filtered))) }491        if failed > 0 { parts.append(L("%lld failed", failed)) }492        if run.count(.cancelled) > 0 { parts.append(L("%lld cancelled", run.count(.cancelled))) }493        let outputs = run.items.flatMap(\.outputs)494        return HStack(alignment: .top, spacing: ORIX.Space.s) {495            Banner(kind: failed > 0 ? .caution : .success, text: parts.joined(separator: " · "),496                   detail: L("%lld files written in %@", outputs.count, Fmt.duration(run.finishedAt.timeIntervalSince(run.startedAt))))497            if !outputs.isEmpty { IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal(Array(outputs.prefix(50))) } }498        }499    }500}501502private struct RunRow: View {503    let flow: FlowModel504    let item: FlowRunItem505    @State private var showLog = false506507    var body: some View {508        HStack(spacing: ORIX.Space.s) {509            status.frame(width: 18)510            VStack(alignment: .leading, spacing: 1) {511                Text(item.url.lastPathComponent).font(.callout).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).truncationMode(.middle)512                Text(detail).font(.caption).foregroundStyle(item.result?.status == .failed ? ORIX.Palette.danger : ORIX.Palette.textSecondary).lineLimit(2)513            }514            Spacer(minLength: 4)515            if let result = item.result {516                if !result.outputs.isEmpty { IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal(result.outputs) } }517                IconButton(symbol: "doc.text.magnifyingglass", label: L("Show Log")) { showLog = true }518                    .popover(isPresented: $showLog, arrowEdge: .leading) { log(result) }519            } else if !flow.isRunning {520                IconButton(symbol: "minus.circle", label: L("Remove %@", item.url.lastPathComponent), tint: ORIX.Palette.textTertiary) { flow.removeInput(item) }521            }522        }523        .padding(.horizontal, ORIX.Space.s).padding(.vertical, 6)524        .overlay(alignment: .bottom) { ORIX.Palette.hairline.frame(height: 1).padding(.horizontal, ORIX.Space.s) }525        .accessibilityElement(children: .combine)526        .accessibilityLabel(item.url.lastPathComponent)527        .accessibilityValue(detail)528    }529530    @ViewBuilder private var status: some View {531        if let result = item.result {532            Image(systemName: result.status.symbol).foregroundStyle(color(result.status))533        } else if item.isActive {534            ORIXProgressRing(fraction: item.progress?.fraction, size: 14, lineWidth: 2, label: L("Progress"))535        } else {536            Image(systemName: "doc").foregroundStyle(ORIX.Palette.textTertiary)537        }538    }539540    private func color(_ status: WorkflowItemResult.Status) -> Color {541        switch status {542        case .succeeded: ORIX.Palette.success543        case .succeededWithErrors: ORIX.Palette.caution544        case .filtered, .cancelled: ORIX.Palette.textSecondary545        case .failed: ORIX.Palette.danger546        }547    }548549    private var detail: String {550        if let result = item.result {551            if let error = result.errors.first { return LE(error) }552            if result.status == .succeeded || result.status == .succeededWithErrors {553                return result.outputs.isEmpty ? L("Nothing written") : (result.outputs.count == 1 ? result.outputs[0].lastPathComponent : L("%lld files written", result.outputs.count))554            }555            return result.status.title556        }557        if item.isActive { return item.progress?.fraction.map { Fmt.percent($0) } ?? L("In progress") }558        return L("Waiting")559    }560561    private func log(_ result: WorkflowItemResult) -> some View {562        VStack(alignment: .leading, spacing: ORIX.Space.s) {563            Label(result.status.title, systemImage: result.status.symbol).font(.headline).foregroundStyle(color(result.status))564            ForEach(Array(result.log.enumerated()), id: \.offset) { _, line in565                Text(LE(line)).font(.caption.monospaced()).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)566            }567            ForEach(result.warnings, id: \.self) { Banner(kind: $0.severity == .dataLoss ? .danger : .info, text: LE($0.message)) }568        }569        .padding(ORIX.Space.l).frame(width: 380, alignment: .leading)570    }571}572573// MARK: - History574575private struct HistoryPanel: View {576    let flow: FlowModel577    var body: some View {578        ScrollView {579            VStack(alignment: .leading, spacing: ORIX.Space.s) {580                if flow.history.isEmpty {581                    Text(L("No run of this workflow has been recorded.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)582                    Text(L("Runs are recorded when the history is enabled in Settings › Privacy.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)583                }584                ForEach(flow.history) { record in585                    VStack(alignment: .leading, spacing: 4) {586                        HStack {587                            Text(Fmt.date(record.startedAt)).font(.callout.weight(.medium))588                            Spacer()589                            Text(Fmt.duration(record.finishedAt.timeIntervalSince(record.startedAt))).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)590                        }591                        HStack(spacing: 6) {592                            if record.succeeded > 0 { Pill(text: L("%lld done", record.succeeded), symbol: "checkmark", color: ORIX.Palette.success) }593                            if record.filtered > 0 { Pill(text: L("%lld filtered out", record.filtered), symbol: nil) }594                            if record.failed > 0 { Pill(text: L("%lld failed", record.failed), symbol: "xmark", color: ORIX.Palette.danger) }595                            if record.cancelled > 0 { Pill(text: L("%lld cancelled", record.cancelled), symbol: nil) }596                            Spacer(minLength: 0)597                            let outputs = record.items.flatMap(\.outputPaths).map { URL(fileURLWithPath: $0) }598                            if !outputs.isEmpty { IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal(Array(outputs.prefix(50))) } }599                        }600                        if let failure = record.items.first(where: { $0.error != nil }) {601                            Text("\((failure.sourcePath as NSString).lastPathComponent): \(LE(failure.error ?? ""))").font(.caption).foregroundStyle(ORIX.Palette.danger).lineLimit(2)602                        }603                    }604                    .padding(ORIX.Space.m)605                    .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))606                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))607                    .accessibilityElement(children: .combine)608                }609            }610            .padding(ORIX.Space.l)611        }612        .task(id: flow.document?.id) { await flow.reloadHistory() }613    }614}615
Files main
Menu

Theme