SPB Git

Repository Public License

ActionsView.swift 14.6 KB 267 lines swift

1// ORIX Secure2// File: App/Sources/Features/Actions/ActionsView.swift3// Description: ORIX Secure Actions: built-in and user workflows that chain real diagnostics, with live progress, cancellation,4//              confirmation before anything destructive, and a saved run report.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDesign9import ORIXSecureModel10import ORIXWorkflow11import SwiftUI1213struct ActionsView: View {14    @Environment(AppModel.self) private var model15    @State private var controller: ActionsController?16    @State private var running: WorkflowDefinition?17    @State private var showEditor = false1819    var body: some View {20        ScreenScroll {21            Text("A workflow runs the same checks as the individual screens, one after the other. Nothing is deleted without your confirmation.")22                .font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)23            if let controller {24                ForEach(controller.library) { definition in25                    Button { running = definition } label: { card(definition) }26                        .buttonStyle(.plain)27                        .contextMenu {28                            if !definition.isBuiltIn { Button("Delete Workflow", systemImage: "trash", role: .destructive) { controller.deleteCustom(definition) } }29                        }30                        .accessibilityIdentifier("workflow." + (definition.isBuiltIn ? definition.name : "custom"))31                }32                Button { showEditor = true } label: { Label("New Workflow", systemImage: "plus") }.buttonStyle(.orixSecondary)33                    .accessibilityIdentifier("workflow.new")34            }35        }36        .navigationTitle("Actions")37        .onAppear { if controller == nil { controller = ActionsController(model: model) } }38        .sheet(item: $running) { definition in39            if let controller { NavigationStack { WorkflowRunView(definition: definition, controller: controller) } }40        }41        .sheet(isPresented: $showEditor) {42            if let controller { WorkflowEditorView(controller: controller) }43        }44        .accessibilityIdentifier("actions")45    }4647    private func card(_ definition: WorkflowDefinition) -> some View {48        VStack(alignment: .leading, spacing: ORIX.Space.sm) {49            HStack(spacing: ORIX.Space.sm) {50                ORIXGlyph(definition.systemImage)51                VStack(alignment: .leading, spacing: 2) {52                    Text(verbatim: definition.name).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)53                    Text(verbatim: definition.summary).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.leading)54                }55                Spacer(minLength: 0)56                Image(systemName: "play.circle.fill").font(.title2).foregroundStyle(ORIXAccent.secure.primary).accessibilityHidden(true)57            }58            FlowChips {59                ForEach(Array(definition.steps.enumerated()), id: \.element.id) { index, step in60                    ORIXChip(Text(verbatim: "\(index + 1). \(step.title)"), systemName: step.isDestructive ? "trash" : nil,61                             tint: step.isDestructive ? ORIX.Palette.danger : ORIX.Palette.textSecondary)62                }63            }64        }65        .frame(maxWidth: .infinity, alignment: .leading)66        .orixCard()67        .accessibilityElement(children: .combine)68        .accessibilityAddTraits(.isButton)69    }70}7172struct WorkflowRunView: View {73    let definition: WorkflowDefinition74    @Bindable var controller: ActionsController75    @Environment(AppModel.self) private var model76    @Environment(\.dismiss) private var dismiss77    @State private var link = ""7879    private var needsLink: Bool { definition.steps.contains { $0.kind == .urlInspect } }80    private var showsThisRun: Bool { controller.definition?.id == definition.id }8182    var body: some View {83        ScreenScroll {84            Text(verbatim: definition.summary).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)85            if needsLink, !controller.isRunning, controller.run == nil || !showsThisRun {86                TextField("Link to inspect", text: $link)87                    .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL).font(.orixMono)88                    .padding(ORIX.Space.sm)89                    .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))90                    .accessibilityIdentifier("run.link")91            }92            VStack(alignment: .leading, spacing: 0) {93                let states = showsThisRun ? controller.steps : definition.steps.map { ActionsController.StepState(id: $0.id, step: $0) }94                ForEach(Array(states.enumerated()), id: \.element.id) { index, state in95                    stepRow(index: index, state: state)96                    if index < states.count - 1 { Divider().padding(.leading, 40) }97                }98            }99            .orixCard(padding: ORIX.Space.sm)100            .accessibilityElement(children: .contain)101            .accessibilityIdentifier("run.steps")102            if showsThisRun, let run = controller.run {103                ORIXBanner(run.status == .succeeded ? .success : (run.status == .failed ? .error : .info), title: Text(verbatim: run.status.title),104                           message: Text("Finished in \(run.duration.formatted(.number.precision(.fractionLength(1)))) s. The run was saved to Reports."))105                    .accessibilityIdentifier("run.finished")106                if !run.findings.filter({ $0.state == .attention }).isEmpty {107                    ORIXSectionHeader("Findings that need attention")108                    FindingList(findings: run.findings.filter { $0.state == .attention }.prioritized())109                }110            }111            if controller.isRunning {112                Button("Cancel Workflow", role: .destructive) { controller.cancel() }.buttonStyle(.orixSecondary).accessibilityIdentifier("run.cancel")113            } else {114                Button { controller.start(definition, link: needsLink ? link : nil) } label: {115                    Label(showsThisRun && controller.run != nil ? "Run Again" : "Run Workflow", systemImage: "play.fill")116                }117                .buttonStyle(.orixPrimary)118                .accessibilityIdentifier("run.start")119            }120        }121        .navigationTitle(Text(verbatim: definition.name))122        .navigationBarTitleDisplayMode(.inline)123        .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { if controller.isRunning { controller.cancel() }; dismiss() }.accessibilityIdentifier("run.close") } }124        .interactiveDismissDisabled(controller.isRunning)125        .confirmationDialog(Text(verbatim: controller.pendingConfirmation?.title ?? ""), isPresented: Binding(get: { controller.pendingConfirmation != nil }, set: { if !$0, controller.pendingConfirmation != nil { controller.answerConfirmation(.declined) } }), titleVisibility: .visible) {126            Button("Continue", role: controller.pendingConfirmation?.isDestructive == true ? .destructive : nil) { controller.answerConfirmation(.confirmed) }127            Button("Skip This Step", role: .cancel) { controller.answerConfirmation(.declined) }128        } message: {129            Text(controller.pendingConfirmation?.isDestructive == true130                 ? "\(model.photos.selection.count) selected item(s) will be moved to Recently Deleted. iOS will ask you again."131                 : "This step needs your go-ahead.")132        }133        .sheet(isPresented: $controller.isReviewingPhotos, onDismiss: { controller.finishReview(proceed: false) }) {134            NavigationStack { WorkflowPhotoReview(controller: controller) }135        }136        .accessibilityIdentifier("run")137    }138139    private func stepRow(index: Int, state: ActionsController.StepState) -> some View {140        HStack(alignment: .top, spacing: ORIX.Space.sm) {141            Group {142                switch state.status {143                case .pending: Image(systemName: "\(index + 1).circle").foregroundStyle(ORIX.Palette.textTertiary)144                case .running: ProgressView()145                case .awaitingConfirmation: Image(systemName: "hand.raised.circle.fill").foregroundStyle(ORIX.Palette.info)146                case .succeeded: Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success)147                case .failed: Image(systemName: "xmark.octagon.fill").foregroundStyle(ORIX.Palette.danger)148                case .skipped: Image(systemName: "arrow.uturn.right.circle").foregroundStyle(ORIX.Palette.textTertiary)149                }150            }151            .font(.title3).frame(width: 28)152            .accessibilityHidden(true)153            VStack(alignment: .leading, spacing: 3) {154                HStack(spacing: 6) {155                    Text(verbatim: state.step.title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)156                    if state.step.isDestructive { ORIXChip(Text("Asks first"), systemName: "trash", tint: ORIX.Palette.danger) }157                }158                Text(verbatim: statusText(state)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)159                if let message = state.message { Text(verbatim: message).font(.orixCaption).foregroundStyle(ORIX.Palette.textPrimary) }160                if let progress = state.progress, state.status == .running { ORIXProgressBar(value: progress) }161            }162            Spacer(minLength: 0)163        }164        .padding(.vertical, 8)165        .accessibilityElement(children: .combine)166        .accessibilityIdentifier("run.step.\(index)")167    }168169    private func statusText(_ state: ActionsController.StepState) -> String {170        switch state.status {171        case .pending: String(localized: "Waiting")172        case .running: String(localized: "Running")173        case .awaitingConfirmation: String(localized: "Waiting for your confirmation")174        case .succeeded: String(localized: "Done")175        case .failed: String(localized: "Failed")176        case .skipped: String(localized: "Skipped")177        }178    }179}180181/// The review step of a cleanup workflow: the same category screens as Photo Cleanup.182struct WorkflowPhotoReview: View {183    @Bindable var controller: ActionsController184    @Environment(AppModel.self) private var model185    @State private var open: CleanupCategoryBox?186187    var body: some View {188        let photos = model.photos189        ScreenScroll {190            Text("Choose what to delete. Only extra copies of exact duplicates are selected for you.").font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)191            ForEach((photos.analysis?.categories ?? []).filter { !$0.groups.isEmpty }) { category in192                Button { open = CleanupCategoryBox(kind: category.kind) } label: {193                    HStack {194                        ORIXGlyph(category.kind.systemImage)195                        Text(verbatim: category.kind.title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)196                        Spacer()197                        Text(verbatim: "\(category.groups.count)").font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)198                        Image(systemName: "chevron.right").font(.footnote).foregroundStyle(ORIX.Palette.textTertiary)199                    }200                    .orixCard(padding: ORIX.Space.sm)201                }202                .buttonStyle(.plain)203            }204            Button { controller.finishReview(proceed: true) } label: { Text("Continue with \(photos.selection.count) Selected") }.buttonStyle(.orixPrimary)205                .accessibilityIdentifier("workflowReview.continue")206        }207        .navigationTitle("Review Candidates")208        .navigationBarTitleDisplayMode(.inline)209        .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Stop") { controller.finishReview(proceed: false) } } }210        .sheet(item: $open) { box in NavigationStack { CleanupCategoryView(kind: box.kind, controller: photos) } }211    }212}213214import ORIXMediaCleanup215216struct CleanupCategoryBox: Identifiable {217    let kind: CleanupCategoryKind218    var id: String { kind.rawValue }219}220221struct WorkflowEditorView: View {222    let controller: ActionsController223    @Environment(\.dismiss) private var dismiss224    @State private var name = ""225    @State private var kinds: [WorkflowStepKind] = []226    @State private var error: String?227228    var body: some View {229        NavigationStack {230            Form {231                Section("Name") { TextField("Workflow name", text: $name).accessibilityIdentifier("editor.name") }232                Section("Steps, in order") {233                    if kinds.isEmpty { Text("Add steps below.").foregroundStyle(ORIX.Palette.textSecondary) }234                    ForEach(Array(kinds.enumerated()), id: \.offset) { index, kind in235                        Text(verbatim: "\(index + 1). " + (ActionsController.stepCatalog.first { $0.kind == kind }?.title ?? kind.rawValue))236                    }237                    .onDelete { kinds.remove(atOffsets: $0) }238                    .onMove { kinds.move(fromOffsets: $0, toOffset: $1) }239                }240                Section("Add a step") {241                    ForEach(ActionsController.stepCatalog, id: \.kind) { entry in242                        Button { kinds.append(entry.kind); error = nil } label: {243                            Label { Text(verbatim: entry.title) } icon: { Image(systemName: entry.destructive ? "trash" : "plus.circle") }244                        }245                        .accessibilityIdentifier("editor.add." + entry.kind.rawValue)246                    }247                }248                if let error { Section { Label { Text(verbatim: error) } icon: { Image(systemName: "exclamationmark.triangle") }.foregroundStyle(ORIX.Palette.warning) }.accessibilityIdentifier("editor.error") }249                Section { Text("A deletion step always asks for confirmation and must come after a review step. The workflow cannot be saved otherwise.").font(.orixCaption) }250            }251            .navigationTitle("New Workflow")252            .navigationBarTitleDisplayMode(.inline)253            .toolbar {254                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }255                ToolbarItem(placement: .confirmationAction) {256                    Button("Save") {257                        do { try controller.saveCustom(name: name, kinds: kinds); dismiss() } catch { self.error = error.localizedDescription }258                    }259                    .disabled(kinds.isEmpty)260                    .accessibilityIdentifier("editor.save")261                }262                ToolbarItem(placement: .bottomBar) { EditButton() }263            }264        }265    }266}267
Files main
Menu

Theme