Repository Public License
1// ORIX Scan2// File: App/Sources/Actions/ActionsView.swift3// Description: ORIX Actions: built-in presets and user workflows, with launch, duplicate, rename and delete.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import SwiftData10import SwiftUI1112/// Starts a workflow: asks for its input (scanner, photos, files or library documents), then runs it.13enum WorkflowLauncher {14 static func start(_ workflow: Workflow, model: AppModel) {15 switch workflow.input {16 case .scan: model.request(ScannerView.isAvailable ? .scan : .photos, for: .workflow(workflow))17 case .photos: model.request(.photos, for: .workflow(workflow))18 case .files: model.request(.files, for: .workflow(workflow))19 case .library: model.pendingLibraryWorkflow = workflow20 }21 }22}2324struct ActionsView: View {25 @Environment(AppModel.self) private var model26 @Environment(\.orixAccent) private var accent27 @Query(sort: \WorkflowRecord.createdAt, order: .reverse) private var stored: [WorkflowRecord]28 @State private var renaming: WorkflowRecord?29 @State private var newName = ""3031 private var custom: [Workflow] { stored.compactMap(\.workflow) }3233 var body: some View {34 ScrollView {35 VStack(alignment: .leading, spacing: ORIX.Space.xl) {36 VStack(alignment: .leading, spacing: ORIX.Space.xs) {37 Text("Chain scanning, cleanup, text recognition and export into one tap. Every step runs on this device.")38 .font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)39 }40 section("My Actions", workflows: custom, emptyText: "Create your own action, or duplicate a preset and change it.")41 section("Presets", workflows: Workflow.presets, emptyText: "")42 }43 .padding(ORIX.Space.md)44 .frame(maxWidth: 980)45 .frame(maxWidth: .infinity)46 }47 .background(ORIX.Palette.canvas)48 .navigationTitle("ORIX Actions")49 .toolbar {50 ToolbarItem(placement: .topBarTrailing) {51 Button { create() } label: { Label("New Action", systemImage: "plus") }52 .accessibilityIdentifier("actions.new")53 }54 }55 .alert("Rename Action", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {56 TextField("Name", text: $newName)57 Button("Cancel", role: .cancel) {}58 Button("Rename") {59 let name = newName.trimmingCharacters(in: .whitespacesAndNewlines)60 if !name.isEmpty, var workflow = renaming?.workflow {61 workflow.name = name62 renaming?.workflow = workflow63 try? model.index.context.save()64 }65 }66 }67 }6869 private func section(_ title: LocalizedStringKey, workflows: [Workflow], emptyText: LocalizedStringKey) -> some View {70 VStack(alignment: .leading, spacing: ORIX.Space.sm) {71 ORIXSectionHeader(title)72 if workflows.isEmpty {73 Text(emptyText).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)74 .frame(maxWidth: .infinity, alignment: .leading).orixCard()75 } else {76 LazyVGrid(columns: [GridItem(.adaptive(minimum: 300), spacing: ORIX.Space.sm)], spacing: ORIX.Space.sm) {77 ForEach(workflows) { workflow in card(workflow) }78 }79 }80 }81 }8283 private func card(_ workflow: Workflow) -> some View {84 VStack(alignment: .leading, spacing: ORIX.Space.sm) {85 HStack(spacing: ORIX.Space.sm) {86 ORIXGlyph(workflow.symbol, tint: workflow.isPreset ? accent.secondary : accent.primary, size: 42)87 VStack(alignment: .leading, spacing: 2) {88 Text(workflow.displayName).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)89 Label { Text(workflow.input.title) } icon: { Image(systemName: workflow.input.symbol) }90 .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)91 }92 Spacer(minLength: 0)93 Menu {94 if workflow.isPreset {95 Button { duplicate(workflow) } label: { Label("Duplicate to Edit", systemImage: "plus.square.on.square") }96 } else {97 Button { model.router.push(.workflow(workflow.id)) } label: { Label("Edit", systemImage: "slider.horizontal.3") }98 Button { newName = workflow.name; renaming = stored.first { $0.id == workflow.id } } label: { Label("Rename", systemImage: "pencil") }99 Button { duplicate(workflow) } label: { Label("Duplicate", systemImage: "plus.square.on.square") }100 Divider()101 Button(role: .destructive) { delete(workflow) } label: { Label("Delete", systemImage: "trash") }102 }103 } label: {104 Image(systemName: "ellipsis").frame(width: ORIX.minimumTarget, height: ORIX.minimumTarget).contentShape(Rectangle())105 }106 .accessibilityLabel("Options for \(workflow.displayName)")107 .accessibilityIdentifier("actions.menu")108 }109 StepFlow(steps: workflow.steps)110 Button { WorkflowLauncher.start(workflow, model: model) } label: { Label("Run", systemImage: "play.fill") }111 .buttonStyle(.orixSecondary)112 .disabled(!workflow.validationIssues.isEmpty)113 .accessibilityLabel("Run \(workflow.displayName)")114 .accessibilityIdentifier("actions.run")115 }116 .orixCard()117 .contextMenu {118 Button { duplicate(workflow) } label: { Label("Duplicate", systemImage: "plus.square.on.square") }119 if !workflow.isPreset {120 Button { model.router.push(.workflow(workflow.id)) } label: { Label("Edit", systemImage: "slider.horizontal.3") }121 }122 }123 }124125 private func create() {126 let workflow = Workflow(name: uniqueName(String(localized: "New Action")), input: .scan,127 steps: [ActionStep(.enhance), ActionStep(.recognizeText), ActionStep(.exportPDF)])128 guard let record = try? WorkflowRecord(workflow) else { return }129 model.index.context.insert(record)130 try? model.index.context.save()131 model.router.push(.workflow(workflow.id))132 }133134 private func duplicate(_ workflow: Workflow) {135 var copy = workflow136 copy.id = UUID()137 copy.presetKey = nil138 copy.name = uniqueName(String(localized: "\(workflow.displayName) copy"))139 copy.steps = copy.steps.map { var s = $0; s.id = UUID(); return s }140 guard let record = try? WorkflowRecord(copy) else { return }141 model.index.context.insert(record)142 try? model.index.context.save()143 ORIXHaptics.tick()144 model.router.push(.workflow(copy.id))145 }146147 private func delete(_ workflow: Workflow) {148 if let record = stored.first(where: { $0.id == workflow.id }) {149 model.index.context.delete(record)150 try? model.index.context.save()151 }152 }153154 private func uniqueName(_ base: String) -> String {155 Library.uniqueTitle(base, existing: custom.map(\.name) + Workflow.presets.map(\.displayName))156 }157}158159/// The steps of a workflow as a compact chain of glyphs.160struct StepFlow: View {161 @Environment(\.orixAccent) private var accent162 let steps: [ActionStep]163164 var body: some View {165 ScrollView(.horizontal, showsIndicators: false) {166 HStack(spacing: 4) {167 ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in168 if index > 0 { Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(ORIX.Palette.textTertiary) }169 HStack(spacing: 4) {170 Image(systemName: step.kind.symbol)171 Text(step.kind.title)172 }173 .font(.orixCaption)174 .foregroundStyle(ORIX.Palette.textPrimary)175 .padding(.horizontal, 8)176 .padding(.vertical, 5)177 .background(ORIX.Palette.surfaceRaised, in: Capsule())178 }179 }180 }181 .accessibilityElement(children: .ignore)182 .accessibilityLabel(Text("Steps: \(steps.map { String(localized: $0.kind.title) }.joined(separator: ", "))"))183 }184}185186/// Picks library documents as the input of a workflow (batch execution).187struct DocumentChooser: View {188 @Environment(AppModel.self) private var model189 @Environment(\.dismiss) private var dismiss190 @Query private var records: [DocumentRecord]191 let workflow: Workflow192 @State private var selection: Set<UUID> = []193194 var body: some View {195 let documents = Library.query(records)196 NavigationStack {197 Group {198 if documents.isEmpty {199 ORIXEmptyState(systemName: "books.vertical", title: "No Documents", message: "Scan or import a document first.")200 } else {201 List(documents, selection: $selection) { record in202 DocumentRow(record: record).tag(record.id)203 }204 .environment(\.editMode, .constant(.active))205 }206 }207 .navigationTitle("Choose Documents")208 .navigationBarTitleDisplayMode(.inline)209 .toolbar {210 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }211 ToolbarItem(placement: .confirmationAction) {212 Button("Run") {213 let ids = documents.map(\.id).filter(selection.contains)214 dismiss()215 model.workflowRun = WorkflowRun(workflow: workflow, documentIDs: ids)216 }217 .disabled(selection.isEmpty)218 }219 }220 }221 }222}223