SPB Git

Repository Public License

FlowView.swift 24.5 KB 464 lines swift

1// ORIX Convert — App/Sources/Features/Flow/FlowView.swift2// Description: Conversion Flow: the workflow library, the canvas of connected step cards (branches show their two3//              lanes; steps are added from the palette or the connectors, dragged to reorder, selected with the4//              keyboard) and the side panel (step editor, run, history).5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import SwiftUI8import UniformTypeIdentifiers910struct FlowView: View {11    @Environment(AppModel.self) private var model1213    var body: some View {14        let flow = model.flow15        VStack(spacing: 0) {16            HeaderBar(title: L("Flow"), subtitle: flow.document.map { $0.name } ?? L("Reusable conversion workflows")) {17                if let validation = flow.validation, flow.document != nil {18                    let errors = validation.errors.count19                    Pill(text: errors == 0 ? L("Valid") : (errors == 1 ? L("1 problem") : L("%lld problems", errors)),20                         symbol: errors == 0 ? "checkmark.seal" : "xmark.octagon.fill", color: errors == 0 ? ORIX.Palette.success : ORIX.Palette.danger)21                }22                LibraryMenu(flow: flow)23                Button { flow.tab = .run; flow.run() } label: { Label(L("Run"), systemImage: "play.fill") }24                    .buttonStyle(PrimaryButtonStyle()).disabled(!flow.canRun)25                    .help(flow.isValid ? L("Runs the workflow over the files of the Run panel") : L("Fix the problems before running"))26            }27            if flow.document != nil {28                GeometryReader { geo in29                    let showLibrary = geo.size.width >= 100030                    let panelWidth: CGFloat = geo.size.width < 900 ? 290 : 32031                    HStack(spacing: 0) {32                        if showLibrary {33                            LibraryList(flow: flow).frame(width: 200)34                            ORIX.Palette.hairline.frame(width: 1)35                        }36                        FlowCanvas(flow: flow)37                        ORIX.Palette.hairline.frame(width: 1)38                        FlowPanel(flow: flow).frame(width: panelWidth)39                    }40                }41            } else {42                EmptyState(symbol: "point.3.connected.trianglepath.dotted", title: L("No workflow yet"),43                           message: L("A workflow chains filters, conversions, renames and exports, and applies them to each file you give it."),44                           actionTitle: L("New Workflow")) { flow.newWorkflow() }45            }46        }47        .task { await flow.start() }48    }49}5051// MARK: - Library5253private struct LibraryMenu: View {54    let flow: FlowModel55    var body: some View {56        Menu {57            Button(L("New Workflow")) { flow.newWorkflow() }58            Button(L("Import…")) { flow.importJSON() }59            if let workflow = flow.document?.workflow {60                Divider()61                Button(L("Duplicate “%@”", workflow.name)) { flow.duplicate(workflow) }62                Button(L("Export “%@”…", workflow.name)) { flow.exportJSON(workflow) }63                if !flow.isBuiltIn { Button(L("Delete “%@”", workflow.name), role: .destructive) { flow.delete(workflow) } }64            }65            if !flow.saved.isEmpty {66                Divider()67                Section(L("My workflows")) { ForEach(flow.saved) { workflow in Button(workflow.name) { flow.open(workflow) } } }68            }69            if !flow.builtIns.isEmpty {70                Section(L("Examples")) { ForEach(flow.builtIns) { item in Button(item.workflow.name) { flow.open(item.workflow) } } }71            }72        } label: { Label(L("Workflows"), systemImage: "square.stack.3d.up") }73        .menuStyle(.button).buttonStyle(SecondaryButtonStyle()).fixedSize()74    }75}7677private struct LibraryList: View {78    let flow: FlowModel79    @State private var renaming: UUID?80    @State private var name = ""81    @FocusState private var nameFocused: Bool8283    var body: some View {84        ScrollView {85            VStack(alignment: .leading, spacing: 2) {86                HStack {87                    SectionLabel(L("My workflows"))88                    Spacer()89                    IconButton(symbol: "plus", label: L("New Workflow")) { flow.newWorkflow() }90                }91                .padding(.leading, ORIX.Space.s)92                if flow.saved.isEmpty {93                    Text(L("None yet. Create one, or duplicate an example to edit it.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)94                        .padding(.horizontal, ORIX.Space.s).padding(.bottom, ORIX.Space.s).fixedSize(horizontal: false, vertical: true)95                }96                ForEach(flow.saved) { workflow in row(workflow, builtIn: false) }97                if !flow.builtIns.isEmpty {98                    SectionLabel(L("Examples")).padding(.leading, ORIX.Space.s).padding(.top, ORIX.Space.l).padding(.bottom, 4)99                    ForEach(flow.builtIns) { row($0.workflow, builtIn: true) }100                }101                if let error = flow.loadError { Banner(kind: .caution, text: L("The saved workflows could not be read."), detail: error).padding(.top, ORIX.Space.m) }102            }103            .padding(ORIX.Space.s)104        }105        .background(ORIX.Palette.canvas)106        .accessibilityElement(children: .contain)107        .accessibilityLabel(L("Workflow library"))108    }109110    @ViewBuilder private func row(_ workflow: Workflow, builtIn: Bool) -> some View {111        let selected = flow.document?.id == workflow.id112        if renaming == workflow.id {113            TextField(L("Workflow name"), text: $name).textFieldStyle(.roundedBorder).font(.callout).focused($nameFocused)114                .onSubmit { flow.rename(workflow, to: name); renaming = nil }115                .onExitCommand { renaming = nil }116                .padding(.vertical, 2)117        } else {118            Button { flow.open(workflow) } label: {119                HStack(spacing: 8) {120                    Image(systemName: builtIn ? "sparkles.rectangle.stack" : "point.3.connected.trianglepath.dotted").font(.system(size: 12))121                        .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary).frame(width: 18)122                    Text(workflow.name).font(.callout.weight(selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(2).multilineTextAlignment(.leading)123                    Spacer(minLength: 0)124                }125                .padding(.horizontal, 8).padding(.vertical, 6)126                .background(selected ? ORIX.Palette.accentSoft : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))127                .contentShape(Rectangle())128            }129            .buttonStyle(.plain)130            .contextMenu {131                if !builtIn { Button(L("Rename…")) { name = workflow.name; renaming = workflow.id; nameFocused = true } }132                Button(L("Duplicate")) { flow.duplicate(workflow) }133                Button(L("Export…")) { flow.exportJSON(workflow) }134                if !builtIn { Divider(); Button(L("Delete"), role: .destructive) { flow.delete(workflow) } }135            }136            .accessibilityLabel(workflow.name)137            .accessibilityValue(builtIn ? L("Example") : "")138            .accessibilityAddTraits(selected ? [.isSelected] : [])139        }140    }141}142143// MARK: - Canvas144145extension FlowNode.Category {146    var color: Color {147        switch self {148        case .convert: ORIX.Palette.accent149        case .rename: ORIX.Palette.info150        case .filter: ORIX.Palette.caution151        case .branch: FormatCategory.vector.color152        case .export: ORIX.Palette.success153        }154    }155}156157private struct FlowCanvas: View {158    @Environment(AppModel.self) private var model159    let flow: FlowModel160    @FocusState private var focused: Bool161162    var body: some View {163        VStack(spacing: 0) {164            palette165            if flow.isBuiltIn, let workflow = flow.document?.workflow {166                HStack(spacing: ORIX.Space.s) {167                    Image(systemName: "sparkles").foregroundStyle(ORIX.Palette.info).accessibilityHidden(true)168                    Text(L("This is a built-in example: it runs as it is. Duplicate it to change it.")).font(.callout).foregroundStyle(ORIX.Palette.textPrimary)169                        .fixedSize(horizontal: false, vertical: true)170                    Spacer(minLength: 4)171                    Button(L("Duplicate to Edit")) { flow.duplicate(workflow) }.buttonStyle(SecondaryButtonStyle(prominent: true))172                }173                .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.s)174                .background(ORIX.Palette.info.opacity(0.08))175            }176            if let notice = flow.notice {177                Banner(kind: .info, text: notice).padding(.horizontal, ORIX.Space.l).padding(.top, ORIX.Space.s).onTapGesture { flow.dismissNotice() }178            }179            GeometryReader { geo in180                // Cards shrink with the canvas so a branch (two lanes side by side) fits without scrolling sideways.181                let available = geo.size.width - 2 * ORIX.Space.l182                let cardWidth = min(300, max(200, available))183                let laneWidth = min(240, max(168, (available - 44) / 2))184                ScrollView([.vertical, .horizontal]) {185                    VStack(spacing: 0) {186                        EndCap(symbol: "tray.and.arrow.down", title: L("Files in"), detail: L("Each file goes through the steps on its own"))187                        if let document = flow.document {188                            FlowLane(flow: flow, nodes: document.nodes, parent: nil, lane: .main, prefix: "", width: cardWidth, laneWidth: laneWidth)189                        }190                        EndCap(symbol: "tray.and.arrow.up", title: L("Results"), detail: resultsDetail)191                        ForEach(Array(flow.workflowIssues.enumerated()), id: \.offset) { _, issue in192                            Banner(kind: issue.severity == .error ? .danger : .info, text: FlowMessages.text(issue)).frame(width: min(460, available)).padding(.top, ORIX.Space.m)193                        }194                    }195                    .padding(ORIX.Space.l)196                    .frame(minWidth: geo.size.width, minHeight: geo.size.height, alignment: .top)197                }198            }199            .defaultScrollAnchor(.top)200            .frame(maxWidth: .infinity, maxHeight: .infinity)201            .background(ORIX.Palette.surfaceSunken)202            .contentShape(Rectangle())203            .onTapGesture { flow.selection = nil; focused = true }204            .focusable()205            .focusEffectDisabled()206            .focused($focused)207            .onKeyPress(.upArrow) { flow.selectNeighbour(-1); return .handled }208            .onKeyPress(.downArrow) { flow.selectNeighbour(1); return .handled }209            .onKeyPress(.leftArrow) { flow.selectNeighbour(-1); return .handled }210            .onKeyPress(.rightArrow) { flow.selectNeighbour(1); return .handled }211            .onKeyPress(.escape) { flow.selection = nil; return .handled }212            .onDeleteCommand { flow.deleteSelection() }213            .onChange(of: flow.selection) { _, new in if new != nil { focused = true } }214            .accessibilityElement(children: .contain)215            .accessibilityLabel(L("Workflow steps"))216            .accessibilityHint(L("Arrow keys move the selection. Delete removes the selected step. Command-D duplicates it."))217        }218    }219220    private var resultsDetail: String {221        if flow.document != nil, !flow.workflowIssues.contains(where: { $0.message.hasPrefix("Some paths have no export step") }), flow.isValid {222            return L("Every path ends in an export step")223        }224        if let folder = flow.exportFolder { return L("Paths without an export step write to %@", folder.lastPathComponent) }225        return L("Paths without an export step write next to each source")226    }227228    private var palette: some View {229        HStack(spacing: 6) {230            ViewThatFits(in: .horizontal) {231                paletteChips(labels: true)232                paletteChips(labels: false)233            }234            Spacer(minLength: 0)235            IconButton(symbol: "arrow.uturn.backward", label: L("Undo")) { flow.undo() }.disabled(!flow.canUndo).opacity(flow.canUndo ? 1 : 0.4)236            IconButton(symbol: "arrow.uturn.forward", label: L("Redo")) { flow.redo() }.disabled(!flow.canRedo).opacity(flow.canRedo ? 1 : 0.4)237        }238        .padding(.horizontal, ORIX.Space.l).frame(height: 44)239        .background(ORIX.Palette.canvas)240        .overlay(alignment: .bottom) { ORIX.Palette.hairline.frame(height: 1) }241        .disabled(!flow.canEdit)242        .opacity(flow.canEdit ? 1 : 0.55)243    }244245    private func paletteChips(labels: Bool) -> some View {246        HStack(spacing: 6) {247            Text(L("Add")).font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize()248            ForEach(FlowNode.Category.allCases) { category in249                Button { flow.add(category) } label: {250                    HStack(spacing: 5) {251                        Image(systemName: category.symbol).font(.system(size: 11, weight: .semibold)).foregroundStyle(category.color)252                        if labels { Text(category.title).font(.callout).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1) }253                    }254                    .padding(.horizontal, labels ? 10 : 9).padding(.vertical, labels ? 5 : 7)255                    .background(ORIX.Palette.surface, in: Capsule())256                    .overlay(Capsule().strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))257                    .contentShape(Capsule())258                    .fixedSize()259                }260                .buttonStyle(.plain)261                .draggable("kind:" + category.rawValue)262                .help(category.title + " — " + category.help)263                .accessibilityLabel(L("Add a %@ step", category.title))264                .accessibilityHint(category.help)265            }266        }267    }268}269270private struct EndCap: View {271    let symbol: String272    let title: String273    let detail: String274    var body: some View {275        HStack(spacing: 8) {276            Image(systemName: symbol).font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textSecondary)277            VStack(alignment: .leading, spacing: 0) {278                Text(title).font(.callout.weight(.semibold)).foregroundStyle(ORIX.Palette.textPrimary)279                Text(detail).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)280            }281        }282        .padding(.horizontal, 14).padding(.vertical, 7)283        .background(ORIX.Palette.surface, in: Capsule())284        .overlay(Capsule().strokeBorder(ORIX.Palette.hairlineStrong, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))285        .accessibilityElement(children: .combine)286    }287}288289/// One lane: connector, card, connector… A branch card is followed by its two lanes side by side.290private struct FlowLane: View {291    let flow: FlowModel292    let nodes: [FlowNode]293    let parent: UUID?294    let lane: FlowSlot.Lane295    let prefix: String296    let width: CGFloat297    /// Width of the cards inside a branch of this lane.298    let laneWidth: CGFloat299300    var body: some View {301        VStack(spacing: 0) {302            Connector(flow: flow, slot: FlowSlot(parent: parent, lane: lane, index: 0), emptyLane: nodes.isEmpty && parent != nil)303            ForEach(Array(nodes.enumerated()), id: \.element.id) { index, node in304                let path = prefix + String(index + 1)305                NodeCard(flow: flow, node: node, path: path, width: width)306                if case .branch(_, let then, let otherwise) = node.kind {307                    BranchFork()308                        .frame(width: 2 * laneWidth + 24, height: 16)309                    HStack(alignment: .top, spacing: 14) {310                        VStack(spacing: 0) {311                            LaneLabel(text: L("If true"), color: ORIX.Palette.success)312                            AnyView(FlowLane(flow: flow, nodes: then, parent: node.id, lane: .then, prefix: path + ".then.", width: laneWidth, laneWidth: max(150, laneWidth - 40)))313                        }314                        VStack(spacing: 0) {315                            LaneLabel(text: L("Otherwise"), color: ORIX.Palette.textSecondary)316                            AnyView(FlowLane(flow: flow, nodes: otherwise, parent: node.id, lane: .otherwise, prefix: path + ".otherwise.", width: laneWidth, laneWidth: max(150, laneWidth - 40)))317                        }318                    }319                    .padding(.horizontal, 5).padding(.bottom, 8)320                    .background(FormatCategory.vector.color.opacity(0.05), in: RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous))321                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous).strokeBorder(FormatCategory.vector.color.opacity(0.25), style: StrokeStyle(lineWidth: 1, dash: [5, 4])))322                }323                Connector(flow: flow, slot: FlowSlot(parent: parent, lane: lane, index: index + 1), emptyLane: false)324            }325        }326    }327}328329private struct LaneLabel: View {330    let text: String331    let color: Color332    var body: some View {333        Text(text.uppercased(with: .current)).font(.system(size: 9, weight: .bold)).kerning(0.5).foregroundStyle(color)334            .padding(.horizontal, 7).padding(.vertical, 2).background(color.opacity(0.12), in: Capsule()).padding(.top, 8)335    }336}337338/// The line from a branch card down to its two lanes.339private nonisolated struct BranchForkShape: Shape {340    func path(in rect: CGRect) -> Path {341        var path = Path()342        path.move(to: CGPoint(x: rect.midX, y: rect.minY))343        path.addLine(to: CGPoint(x: rect.midX, y: rect.midY))344        path.move(to: CGPoint(x: rect.width * 0.25, y: rect.maxY))345        path.addLine(to: CGPoint(x: rect.width * 0.25, y: rect.midY))346        path.addLine(to: CGPoint(x: rect.width * 0.75, y: rect.midY))347        path.addLine(to: CGPoint(x: rect.width * 0.75, y: rect.maxY))348        return path349    }350}351352private struct BranchFork: View {353    var body: some View {354        BranchForkShape().stroke(ORIX.Palette.hairlineStrong, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round)).accessibilityHidden(true)355    }356}357358/// The line between two cards: an insertion point (menu) and a drop target (palette chip or dragged card).359private struct Connector: View {360    let flow: FlowModel361    let slot: FlowSlot362    let emptyLane: Bool363    @State private var hovering = false364    @State private var targeted = false365366    var body: some View {367        ZStack {368            Rectangle().fill(targeted ? AnyShapeStyle(ORIX.Palette.accent) : AnyShapeStyle(ORIX.Palette.hairlineStrong)).frame(width: 2)369            if flow.canEdit {370                Menu {371                    ForEach(FlowNode.Category.allCases) { category in372                        Button { flow.insert(category, at: slot) } label: { Label(category.title, systemImage: category.symbol) }373                    }374                } label: {375                    Image(systemName: "plus").font(.system(size: 9, weight: .bold)).foregroundStyle(hovering || targeted || emptyLane ? ORIX.Palette.accent : ORIX.Palette.textTertiary)376                        .frame(width: 18, height: 18)377                        .background(ORIX.Palette.surface, in: Circle())378                        .overlay(Circle().strokeBorder(hovering || targeted || emptyLane ? ORIX.Palette.accent : ORIX.Palette.hairlineStrong, lineWidth: 1))379                }380                .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()381                .accessibilityLabel(L("Insert a step here"))382            }383        }384        .frame(width: 120, height: emptyLane ? 44 : 30)385        .contentShape(Rectangle())386        .onHover { hovering = $0 }387        .dropDestination(for: String.self) { items, _ in388            guard flow.canEdit, let item = items.first else { return false }389            if item.hasPrefix("kind:"), let category = FlowNode.Category(rawValue: String(item.dropFirst(5))) { flow.insert(category, at: slot); return true }390            if item.hasPrefix("node:"), let id = UUID(uuidString: String(item.dropFirst(5))) { flow.move(id, to: slot); return true }391            return false392        } isTargeted: { targeted = $0 }393    }394}395396private struct NodeCard: View {397    @Environment(AppModel.self) private var model398    let flow: FlowModel399    let node: FlowNode400    let path: String401    let width: CGFloat402403    var body: some View {404        let selected = flow.selection == node.id405        let issues = flow.issues(for: path)406        let errors = issues.filter { $0.severity == .error }407        let category = node.category408        let shape = RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous)409        VStack(alignment: .leading, spacing: 6) {410            HStack(spacing: ORIX.Space.m) {411                icon(category)412                VStack(alignment: .leading, spacing: 2) {413                    Text(node.title(registry: model.registry)).font(.callout.weight(.semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)414                    Text(node.detail).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).multilineTextAlignment(.leading)415                }416                Spacer(minLength: 0)417                if !errors.isEmpty {418                    Image(systemName: "xmark.octagon.fill").font(.callout).foregroundStyle(ORIX.Palette.danger).help(errors.map { FlowMessages.text($0) }.joined(separator: "\n"))419                } else if !issues.isEmpty {420                    Image(systemName: "info.circle.fill").font(.callout).foregroundStyle(ORIX.Palette.info).help(issues.map { FlowMessages.text($0) }.joined(separator: "\n"))421                }422            }423            if let first = errors.first {424                Text(FlowMessages.text(first)).font(.caption).foregroundStyle(ORIX.Palette.danger).fixedSize(horizontal: false, vertical: true)425            }426        }427        .padding(ORIX.Space.m)428        .frame(width: width, alignment: .leading)429        .background(ORIX.Palette.surface, in: shape)430        .overlay(shape.strokeBorder(selected ? AnyShapeStyle(ORIX.Palette.transformationDiagonal) : AnyShapeStyle(errors.isEmpty ? ORIX.Palette.hairlineStrong : ORIX.Palette.danger.opacity(0.6)), lineWidth: selected ? 2 : 1))431        .shadow(color: .black.opacity(selected ? 0.12 : 0.04), radius: selected ? 8 : 2, y: 1)432        .contentShape(shape)433        .onTapGesture { flow.selection = node.id; flow.tab = .step }434        .draggable("node:" + node.id.uuidString)435        .contextMenu {436            Button(L("Duplicate")) { flow.selection = node.id; flow.duplicateSelection() }.disabled(!flow.canEdit)437            Button(L("Move Up")) { flow.selection = node.id; flow.moveSelection(by: -1) }.disabled(!flow.canEdit)438            Button(L("Move Down")) { flow.selection = node.id; flow.moveSelection(by: 1) }.disabled(!flow.canEdit)439            Divider()440            Button(L("Delete"), role: .destructive) { flow.selection = node.id; flow.deleteSelection() }.disabled(!flow.canEdit)441        }442        .accessibilityElement(children: .ignore)443        .accessibilityLabel(L("Step %@: %@", path.replacingOccurrences(of: ".then.", with: ", " + L("If true") + " ").replacingOccurrences(of: ".otherwise.", with: ", " + L("Otherwise") + " "), node.title(registry: model.registry)))444        .accessibilityValue(([node.detail] + issues.map { FlowMessages.text($0) }).joined(separator: ". "))445        .accessibilityAddTraits(selected ? [.isSelected, .isButton] : [.isButton])446        .accessibilityAction { flow.selection = node.id; flow.tab = .step }447        .accessibilityAction(named: L("Duplicate")) { flow.selection = node.id; flow.duplicateSelection() }448        .accessibilityAction(named: L("Delete")) { flow.selection = node.id; flow.deleteSelection() }449        .accessibilityAction(named: L("Move Up")) { flow.selection = node.id; flow.moveSelection(by: -1) }450        .accessibilityAction(named: L("Move Down")) { flow.selection = node.id; flow.moveSelection(by: 1) }451    }452453    @ViewBuilder private func icon(_ category: FlowNode.Category) -> some View {454        if case .convert(let destination, _, _) = node.kind {455            FormatBadge(format: destination, size: .regular)456        } else {457            Image(systemName: category.symbol).font(.system(size: 16, weight: .semibold)).foregroundStyle(category.color)458                .frame(width: 40, height: 40)459                .background(category.color.opacity(0.13), in: RoundedRectangle(cornerRadius: 10, style: .continuous))460                .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(category.color.opacity(0.35), lineWidth: 1))461        }462    }463}464
Files main
Menu

Theme