SPB Git

Repository Public License

WorkflowRunView.swift 8.9 KB 197 lines swift

1// ORIX Scan2// File: App/Sources/Actions/WorkflowRunView.swift3// Description: Runs a workflow on one or several documents with live per-step status, progress, cancellation and results.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import SwiftUI1011struct WorkflowRunView: View {12    enum Phase { case running, finished, cancelled }1314    @Environment(AppModel.self) private var model15    @Environment(\.orixAccent) private var accent16    @Environment(\.dismiss) private var dismiss17    let run: WorkflowRun1819    @State private var phase: Phase = .running20    @State private var documentIndex = 021    @State private var progress: WorkflowProgress?22    @State private var outcomes: [UUID: [StepOutcome]] = [:]23    @State private var artifacts: [URL] = []24    @State private var failures = 025    @State private var task: Task<Void, Never>?26    @State private var share: SharePayload?2728    private var overall: Double {29        let per = 1 / Double(max(run.documentIDs.count, 1))30        return min(1, (Double(documentIndex) + (progress?.overall ?? 0)) * per)31    }3233    private var currentOutcomes: [StepOutcome] {34        guard run.documentIDs.indices.contains(documentIndex) else { return outcomes[run.documentIDs.last ?? UUID()] ?? [] }35        return outcomes[run.documentIDs[documentIndex]] ?? []36    }3738    var body: some View {39        NavigationStack {40            ScrollView {41                VStack(alignment: .leading, spacing: ORIX.Space.lg) {42                    header43                    VStack(spacing: 0) {44                        ForEach(Array(run.workflow.steps.enumerated()), id: \.element.id) { index, step in45                            stepRow(step, index: index)46                            if index < run.workflow.steps.count - 1 { Divider().padding(.leading, 52) }47                        }48                    }49                    .orixCard(padding: ORIX.Space.xs)50                    if phase != .running { results }51                }52                .padding(ORIX.Space.md)53            }54            .background(ORIX.Palette.canvas)55            .navigationTitle(run.workflow.displayName)56            .navigationBarTitleDisplayMode(.inline)57            .toolbar {58                ToolbarItem(placement: .cancellationAction) {59                    if phase == .running {60                        Button("Cancel") { task?.cancel() }.accessibilityIdentifier("run.cancel")61                    } else {62                        Button("Close") { dismiss() }.accessibilityIdentifier("run.close")63                    }64                }65            }66            .interactiveDismissDisabled(phase == .running)67            .task { if task == nil { start() } }68            .sheet(item: $share) { ShareSheet(items: $0.urls) }69        }70    }7172    private var header: some View {73        VStack(alignment: .leading, spacing: ORIX.Space.sm) {74            HStack(spacing: ORIX.Space.sm) {75                ORIXGlyph(run.workflow.symbol, size: 44)76                VStack(alignment: .leading, spacing: 2) {77                    switch phase {78                    case .running:79                        Text(run.documentIDs.count > 1 ? "Document \(min(documentIndex + 1, run.documentIDs.count)) of \(run.documentIDs.count)" : "Running…")80                            .font(.orixHeadline)81                    case .finished:82                        Text(failures == 0 ? "Finished" : "Finished with problems").font(.orixHeadline)83                            .foregroundStyle(failures == 0 ? ORIX.Palette.success : ORIX.Palette.warning)84                            .accessibilityIdentifier("run.finished")85                    case .cancelled:86                        Text("Cancelled").font(.orixHeadline).foregroundStyle(ORIX.Palette.textSecondary)87                    }88                    Text("Everything runs on this device.").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)89                }90            }91            ORIXProgressBar(value: phase == .running ? overall : 1)92        }93        .orixCard()94    }9596    private func stepRow(_ step: ActionStep, index: Int) -> some View {97        let outcome = currentOutcomes.first { $0.id == step.id }98        let active = phase == .running && outcome == nil && progress?.stepIndex == index99        return HStack(spacing: ORIX.Space.sm) {100            ZStack {101                if active {102                    ProgressView()103                } else if let outcome {104                    switch outcome.status {105                    case .done: Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success)106                    case .nothingToDo: Image(systemName: "minus.circle.fill").foregroundStyle(ORIX.Palette.textTertiary)107                    case .failed: Image(systemName: "xmark.octagon.fill").foregroundStyle(ORIX.Palette.danger)108                    case .skipped: Image(systemName: "forward.end.circle").foregroundStyle(ORIX.Palette.textTertiary)109                    }110                } else {111                    Image(systemName: "circle").foregroundStyle(ORIX.Palette.textTertiary)112                }113            }114            .font(.title3)115            .frame(width: 36)116            VStack(alignment: .leading, spacing: 2) {117                Label { Text(step.kind.title) } icon: { Image(systemName: step.kind.symbol) }.font(.orixBody.weight(.medium))118                if let outcome { Text(describe(outcome)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary) }119                else if active, let fraction = progress?.stepFraction, fraction > 0 {120                    Text(fraction, format: .percent.precision(.fractionLength(0))).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary).monospacedDigit()121                }122            }123            Spacer(minLength: 0)124        }125        .padding(.horizontal, ORIX.Space.xs)126        .frame(minHeight: 52)127        .accessibilityElement(children: .combine)128    }129130    private func describe(_ outcome: StepOutcome) -> String {131        switch outcome.status {132        case let .nothingToDo(note): return String(localized: note.title)133        case .failed: return String(localized: "This step failed. Later steps were skipped; the document is unchanged by them.")134        case .skipped: return String(localized: "Skipped")135        case .done:136            switch outcome.detail {137            case let .pages(n): return String(localized: "\(n) pages")138            case let .lines(n): return String(localized: "\(n) lines of text")139            case let .file(name, bytes): return "\(name) · \(bytes.byteCountString)"140            case let .files(n): return String(localized: "\(n) files")141            case let .title(title): return title142            case let .folder(name): return name143            case .none: return String(localized: "Done")144            }145        }146    }147148    @ViewBuilder private var results: some View {149        VStack(spacing: ORIX.Space.sm) {150            if !artifacts.isEmpty {151                Button { share = SharePayload(urls: artifacts) } label: {152                    Label(artifacts.count == 1 ? "Share Result" : "Share \(artifacts.count) Files", systemImage: "square.and.arrow.up")153                }154                .buttonStyle(.orixPrimary)155                .accessibilityIdentifier("run.share")156            }157            if let first = run.documentIDs.first, run.documentIDs.count == 1 {158                Button {159                    dismiss()160                    model.router.open(first)161                } label: { Label("Open Document", systemImage: "doc") }162                .buttonStyle(.orixSecondary)163                .accessibilityIdentifier("run.open")164            }165        }166    }167168    private func start() {169        let engine = WorkflowEngine(processor: model.processor, languages: model.settings.languages)170        task = Task {171            let background = BackgroundWork.begin(named: "ORIX action")172            defer { background.end() }173            for (n, id) in run.documentIDs.enumerated() {174                documentIndex = n175                progress = nil176                await model.waitForRecognition(id)177                do {178                    let result = try await engine.run(run.workflow, on: id) { update in Task { @MainActor in progress = update } }179                    outcomes[id] = result.outcomes180                    artifacts.append(contentsOf: result.artifacts)181                    if !result.succeeded { failures += 1 }182                    // Library changes requested by the steps.183                    if let name = result.folderName, let folder = model.index.folder(named: name) { model.index.move([id], to: folder) }184                    if result.markFavorite { model.index.setFavorite([id], true) }185                    await model.didChange(id)186                } catch {187                    await model.didChange(id)188                    phase = .cancelled189                    return190                }191            }192            phase = .finished193            if failures == 0 { ORIXHaptics.success() } else { ORIXHaptics.warning() }194        }195    }196}197
Files main
Menu

Theme