SPB Git

Repository Public

VisualBuilderView.swift 39.3 KB 721 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/VisualBuilderView.swift3// Description: The Visual Builder: automations assembled from connected blocks. Every edit regenerates ordinary ORIX4//              Script, shown live beside the blocks and compiled by the same compiler the editor uses.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011@MainActor @Observable12final class VisualBuilderState {13    private(set) var graph = VBGraph()14    private(set) var source = VBCodegen.source(for: VBGraph())15    private(set) var result = ScriptCompiler.compile(VBCodegen.source(for: VBGraph()))16    var importFailure: String?17    var saved: [LibraryDocument] = []18    /// JSON of the graph as last saved or loaded, to show unsaved changes.19    private var storedJSON: String?2021    func edit(_ change: (inout VBGraph) -> Void) {22        var g = graph23        change(&g)24        guard g != graph else { return }25        replace(with: g)26    }2728    private func replace(with g: VBGraph) {29        graph = g30        source = VBCodegen.source(for: g)31        result = ScriptCompiler.compile(source)32    }3334    func update(_ id: UUID, _ change: (inout VBKind) -> Void) { edit { VBTree.update(id, in: &$0.blocks, change) } }3536    private static func json(_ graph: VBGraph) -> String? {37        let encoder = JSONEncoder()38        encoder.outputFormatting = [.sortedKeys]39        return (try? encoder.encode(graph)).map { String(decoding: $0, as: UTF8.self) }40    }4142    var hasUnsavedChanges: Bool { Self.json(graph) != storedJSON && graph != VBGraph() }4344    func newGraph() { replace(with: VBGraph()); storedJSON = nil; importFailure = nil }4546    func refreshSaved(model: AppModel) { saved = (try? model.library.documents(kind: DocumentKind.visualGraph)) ?? [] }4748    func save(model: AppModel) {49        guard let json = Self.json(graph) else { return }50        let name = graph.name.trimmingCharacters(in: .whitespacesAndNewlines)51        guard !name.isEmpty else { model.show(notice: "Name the automation before saving the graph."); return }52        do {53            try model.library.saveDocument(kind: DocumentKind.visualGraph, name: name, json: json)54            storedJSON = json55            refreshSaved(model: model)56            model.show(notice: "Graph \"\(name)\" saved")57        } catch { model.show(notice: error.localizedDescription) }58    }5960    func open(_ document: LibraryDocument, model: AppModel) {61        guard let g = try? JSONDecoder().decode(VBGraph.self, from: Data(document.json.utf8)) else {62            model.show(notice: "The saved graph \"\(document.name)\" could not be read."); return63        }64        replace(with: g)65        storedJSON = Self.json(g)66        importFailure = nil67    }6869    func delete(_ document: LibraryDocument, model: AppModel) {70        do { try model.library.deleteDocument(id: document.id); refreshSaved(model: model) } catch { model.show(notice: error.localizedDescription) }71    }7273    /// Replaces the graph with the script's blocks, or explains which construct prevents it. Never partial.74    func importScript(_ script: String, model: AppModel) {75        switch VBImporter.graph(from: script) {76        case let .success(g):77            replace(with: g); storedJSON = nil; importFailure = nil78            model.show(notice: "Imported \(g.blockCount) block\(g.blockCount == 1 ? "" : "s") from the script")79        case let .failure(f):80            importFailure = f.message81        }82    }83}8485/// ORIX Script text with the editor's token colours (read-only views).86struct HighlightedSource: View {87    var text: String8889    var body: some View {90        Text(Self.attributed(text)).font(ORIX.Typeface.mono).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)91    }9293    static func attributed(_ text: String) -> AttributedString {94        var out = AttributedString(text)95        out.foregroundColor = ORIX.Palette.textPrimary96        for span in Lexer.highlight(text) where span.tokenClass != .identifier {97            let lower = String.Index(utf16Offset: span.range.lowerBound, in: text), upper = String.Index(utf16Offset: span.range.upperBound, in: text)98            guard let range = Range(lower ..< upper, in: out) else { continue }99            out[range].foregroundColor = switch span.tokenClass {100            case .keyword: ORIX.Palette.accent101            case .root: ORIX.Palette.accentSecondary102            case .number: ORIX.Palette.warning103            case .string: ORIX.Palette.success104            case .comment: ORIX.Palette.textTertiary105            default: ORIX.Palette.textSecondary106            }107        }108        return out109    }110}111112struct VisualBuilderView: View {113    @Environment(AppModel.self) private var model114    let studio: AutomationStudioState115116    private var builder: VisualBuilderState { studio.builder }117118    var body: some View {119        HSplitView {120            flow.frame(minWidth: 360, idealWidth: 620, maxWidth: .infinity, maxHeight: .infinity).layoutPriority(1)121            sourcePane.frame(minWidth: 280, idealWidth: 340, maxWidth: 420, maxHeight: .infinity)122        }123        .background(ORIX.Palette.canvas)124        .onAppear { builder.refreshSaved(model: model) }125        .accessibilityIdentifier("automation-builder")126    }127128    // MARK: Blocks129130    private var flow: some View {131        VStack(spacing: 0) {132            HStack(spacing: ORIX.Space.xs) {133                TextField("Automation name", text: Binding(get: { builder.graph.name }, set: { v in builder.edit { $0.name = v } }))134                    .textFieldStyle(.roundedBorder).frame(maxWidth: 220)135                    .accessibilityIdentifier("automation-builder-name")136                Menu {137                    Button("New Graph") { builder.newGraph() }138                    Button("Save Graph") { builder.save(model: model) }139                    Divider()140                    if builder.saved.isEmpty { Text("No saved graph") }141                    ForEach(builder.saved) { doc in Button { builder.open(doc, model: model) } label: { Text(verbatim: doc.name) } }142                    if !builder.saved.isEmpty {143                        Divider()144                        Menu("Delete Saved Graph") {145                            ForEach(builder.saved) { doc in Button(role: .destructive) { builder.delete(doc, model: model) } label: { Text(verbatim: doc.name) } }146                        }147                    }148                } label: {149                    Label(builder.hasUnsavedChanges ? "Graph (edited)" : "Graph", systemImage: "square.stack.3d.up")150                }151                .menuStyle(.borderlessButton).fixedSize()152                .accessibilityIdentifier("automation-builder-graph-menu")153                Spacer(minLength: 4)154                Button { if let doc = model.activeDocument { builder.importScript(doc.source, model: model) } } label: { Label("Import from Script", systemImage: "arrow.down.doc") }155                    .help("Converts the script of the active editor tab to blocks when it only uses constructs the builder supports.")156                    .accessibilityIdentifier("automation-builder-import")157            }158            .controlSize(.small)159            .padding(.horizontal, ORIX.Space.sm).frame(height: 38)160            .background(ORIX.Palette.surface)161            Divider().overlay(ORIX.Palette.hairline)162            if let failure = builder.importFailure {163                HStack(alignment: .firstTextBaseline, spacing: 6) {164                    Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(ORIX.Palette.warning)165                    Text(verbatim: "Not imported. " + failure + " Nothing was changed.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textPrimary)166                    Spacer()167                    Button("Dismiss") { builder.importFailure = nil }.controlSize(.small)168                }169                .padding(ORIX.Space.xs)170                .background(ORIX.Palette.warning.opacity(0.12))171                .accessibilityIdentifier("automation-builder-import-failure")172            }173            ScrollView([.vertical, .horizontal]) {174                VStack(alignment: .leading, spacing: 0) {175                    startCard176                    VBBlockList(builder: builder, blocks: builder.graph.blocks, parent: nil, slot: .body, topLevel: true)177                }178                .padding(ORIX.Space.md)179            }180            .defaultScrollAnchor(.topLeading)181            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)182            .accessibilityIdentifier("automation-builder-flow")183        }184    }185186    private var startCard: some View {187        VBCard(symbol: "play.circle.fill", title: "Trigger: start", tint: ORIX.Palette.success) {188            HStack(spacing: 8) {189                Text("Starts").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)190                Picker("Start", selection: Binding(get: { builder.graph.quantize }, set: { v in builder.edit { $0.quantize = v } })) {191                    Text("now").tag(StartQuantize.none)192                    Text("on the next beat").tag(StartQuantize.beat)193                    Text("on the next bar").tag(StartQuantize.bar)194                }195                .labelsHidden().pickerStyle(.segmented).fixedSize()196                .accessibilityIdentifier("automation-builder-start")197            }198        } controls: { EmptyView() }199    }200201    // MARK: Generated source202203    private var sourcePane: some View {204        VStack(spacing: 0) {205            PaneHeader(title: "Generated ORIX Script") {206                let errors = builder.result.errors.count, warnings = builder.result.warnings.count207                Label {208                    Text(errors > 0 ? "\(errors) error\(errors == 1 ? "" : "s")" : (warnings > 0 ? "Valid, \(warnings) warning\(warnings == 1 ? "" : "s")" : "Valid"))209                } icon: {210                    Image(systemName: errors > 0 ? "xmark.octagon.fill" : (warnings > 0 ? "exclamationmark.triangle.fill" : "checkmark.circle.fill"))211                }212                .font(.system(size: 11, weight: .medium))213                .foregroundStyle(errors > 0 ? ORIX.Palette.danger : (warnings > 0 ? ORIX.Palette.warning : ORIX.Palette.success))214                .accessibilityIdentifier("automation-builder-validity")215            }216            Divider().overlay(ORIX.Palette.hairline)217            ScrollView {218                HighlightedSource(text: builder.source).padding(ORIX.Space.sm)219            }220            .background(ORIX.Palette.surface)221            .accessibilityIdentifier("automation-builder-source")222            if !builder.result.diagnostics.isEmpty {223                Divider().overlay(ORIX.Palette.hairline)224                ScrollView {225                    VStack(alignment: .leading, spacing: 4) {226                        ForEach(Array(builder.result.diagnostics.enumerated()), id: \.offset) { _, d in227                            HStack(alignment: .firstTextBaseline, spacing: 6) {228                                Image(systemName: d.severity == .error ? "xmark.octagon.fill" : "exclamationmark.triangle.fill")229                                    .foregroundStyle(d.severity == .error ? ORIX.Palette.danger : ORIX.Palette.warning)230                                Text(verbatim: "Line \(d.location.line): \(d.message) [\(d.code)]").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textPrimary)231                            }232                        }233                    }234                    .frame(maxWidth: .infinity, alignment: .leading).padding(ORIX.Space.xs)235                }236                .frame(maxHeight: 110)237            }238            Divider().overlay(ORIX.Palette.hairline)239            VStack(alignment: .leading, spacing: 6) {240              HStack(spacing: 6) {241                StudioIconButton(title: "Validate", symbol: "checkmark.seal", showsTitle: true) {242                    let r = builder.result243                    model.show(notice: r.errors.isEmpty ? "The generated script is valid" + (r.warnings.isEmpty ? "" : " (\(r.warnings.count) warning\(r.warnings.count == 1 ? "" : "s"))") : "\(r.errors.count) error\(r.errors.count == 1 ? "" : "s") in the generated script")244                }245                .accessibilityIdentifier("automation-builder-validate")246                StudioIconButton(title: "Simulate", symbol: "chart.xyaxis.line", showsTitle: true) { studio.simulate(source: builder.source, title: builder.graph.name, docID: nil) }247                    .accessibilityIdentifier("automation-builder-simulate")248                StudioIconButton(title: "Run", symbol: "play.fill", tint: ORIX.Palette.success, showsTitle: true) {249                    studio.requestRun(source: builder.source, automation: nil, title: builder.graph.name, origin: "builder", model: model)250                }251                .disabled(!builder.result.succeeded)252                .accessibilityIdentifier("automation-builder-run")253                Spacer(minLength: 0)254              }255                StudioIconButton(title: "Open as Script", symbol: "arrow.up.forward.square", showsTitle: true) {256                    model.openInEditor(name: builder.graph.name, source: builder.source)257                    studio.mode = .editor258                }259                .accessibilityIdentifier("automation-builder-open-script")260            }261            .padding(ORIX.Space.xs)262            .background(ORIX.Palette.surface)263        }264    }265}266267// MARK: - Cards268269/// One block card: icon, title, editors, and the reorder / remove controls.270struct VBCard<Content: View, Controls: View>: View {271    var symbol: String272    var title: LocalizedStringKey273    var tint: Color274    @ViewBuilder var content: Content275    @ViewBuilder var controls: Controls276277    var body: some View {278        VStack(alignment: .leading, spacing: 6) {279            HStack(spacing: 6) {280                Image(systemName: symbol).font(.system(size: 11, weight: .bold)).foregroundStyle(tint).frame(width: 16)281                Text(title).font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)282                controls.padding(.leading, 6)283                Spacer(minLength: 4)284            }285            content286        }287        .padding(8)288        .frame(minWidth: 400, alignment: .leading)289        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))290        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline))291        .overlay(alignment: .leading) { UnevenRoundedRectangle(topLeadingRadius: ORIX.Radius.control, bottomLeadingRadius: ORIX.Radius.control).fill(tint).frame(width: 3) }292    }293}294295/// The connector drawn between two cards of a flow.296private struct VBConnector: View {297    var body: some View {298        Rectangle().fill(ORIX.Palette.textTertiary).frame(width: 2, height: 10).padding(.leading, 15).accessibilityHidden(true)299    }300}301302/// A vertical flow of blocks with the "add block" control at its end.303struct VBBlockList: View {304    @Environment(AppModel.self) private var model305    let builder: VisualBuilderState306    var blocks: [VBBlock]307    var parent: UUID?308    var slot: VBSlot309    var topLevel: Bool310311    var body: some View {312        VStack(alignment: .leading, spacing: 0) {313            ForEach(blocks) { block in314                VBConnector()315                VBBlockView(builder: builder, block: block)316            }317            VBConnector()318            addMenu319        }320    }321322    private func add(_ kind: VBKind) { builder.edit { VBTree.append(VBBlock(kind), to: parent, slot: slot, in: &$0.blocks) } }323324    private var addMenu: some View {325        Menu {326            if topLevel {327                Button { add(.event(.deck(0, "trackEnd"), once: false, body: [])) } label: { Label("Trigger: Event", systemImage: "antenna.radiowaves.left.and.right") }328                Divider()329            }330            Button { add(.wait(.duration(.beats(4)))) } label: { Label("Wait", systemImage: "hourglass") }331            Button { add(.deckAction(deck: 0, action: "play", args: [])) } label: { Label("Deck Action", systemImage: "opticaldisc") }332            Button { add(.setParam(.deck(0, "volume"), .gain(0))) } label: { Label("Mixer Action (Set Parameter)", systemImage: "slider.vertical.3") }333            Button { add(.effect(rack: nil, effect: .echo, op: .enable)) } label: { Label("Effect Action", systemImage: "sparkles") }334            Button { add(.over(duration: .beats(32), curve: nil, ramps: [VBRamp(target: .deck(0, "volume"), value: .gain(-60))])) } label: { Label("Parameter Automation", systemImage: "line.diagonal.arrow") }335            Button { add(.condition(VBCondition(left: .deck(0, "playing"), op: "==", right: .bool(true)), then: [], otherwise: nil)) } label: { Label("Condition", systemImage: "arrow.triangle.branch") }336            Button { add(.loop(count: 4, body: [])) } label: { Label("Loop", systemImage: "repeat") }337            Button { add(.stop) } label: { Label("Stop", systemImage: "stop.fill") }338        } label: {339            Label("Add Block", systemImage: "plus.circle.fill").font(.system(size: 11, weight: .medium))340        }341        .menuStyle(.borderlessButton).fixedSize()342        .accessibilityIdentifier(topLevel ? "automation-builder-add" : "automation-builder-add-nested")343    }344}345346struct VBBlockView: View {347    let builder: VisualBuilderState348    var block: VBBlock349350    private func set(_ kind: VBKind) { builder.update(block.id) { $0 = kind } }351352    @ViewBuilder private var controls: some View {353        let position = VBTree.position(of: block.id, in: builder.graph.blocks)354        HStack(spacing: 2) {355            Button { builder.edit { VBTree.move(block.id, by: -1, in: &$0.blocks) } } label: { Image(systemName: "chevron.up") }356                .disabled(position?.index == 0).help("Move up").accessibilityLabel("Move block up")357            Button { builder.edit { VBTree.move(block.id, by: 1, in: &$0.blocks) } } label: { Image(systemName: "chevron.down") }358                .disabled(position.map { $0.index >= $0.count - 1 } ?? true).help("Move down").accessibilityLabel("Move block down")359            Button { builder.edit { VBTree.remove(block.id, from: &$0.blocks) } } label: { Image(systemName: "xmark") }360                .help("Remove block").accessibilityLabel("Remove block")361        }362        .buttonStyle(.borderless).controlSize(.small).font(.system(size: 10, weight: .semibold))363    }364365    var body: some View {366        switch block.kind {367        case let .event(event, once, body):368            VBCard(symbol: "antenna.radiowaves.left.and.right", title: "Trigger: event", tint: ORIX.Palette.accent) {369                HStack(spacing: 6) {370                    VBEventEditor(event: event) { set(.event($0, once: once, body: body)) }371                    Toggle("once", isOn: Binding(get: { once }, set: { set(.event(event, once: $0, body: body)) })).toggleStyle(.checkbox).font(.system(size: 11))372                }373                VBLane(title: "then") { VBBlockList(builder: builder, blocks: body, parent: block.id, slot: .body, topLevel: false) }374            } controls: { controls }375        case let .wait(wait):376            VBCard(symbol: "hourglass", title: "Wait", tint: ORIX.Palette.textSecondary) {377                HStack(spacing: 6) {378                    Picker("Wait", selection: Binding(get: { waitTag(wait) }, set: { tag in379                        set(.wait(tag == 1 ? .nextBeat : (tag == 2 ? .nextBar : .duration(.beats(4)))))380                    })) {381                        Text("for a duration").tag(0); Text("until the next beat").tag(1); Text("until the next bar").tag(2)382                    }383                    .labelsHidden().fixedSize()384                    if case let .duration(v) = wait { VBValueEditor(value: v, def: nil) { set(.wait(.duration($0))) } }385                }386            } controls: { controls }387        case let .deckAction(deck, action, args):388            VBCard(symbol: "opticaldisc", title: "Deck action", tint: ORIX.deck(deck)) {389                HStack(spacing: 6) {390                    VBDeckPicker(deck: deck) { set(.deckAction(deck: $0, action: action, args: args)) }391                    Picker("Action", selection: Binding(get: { action }, set: { name in392                        set(.deckAction(deck: deck, action: name, args: ScriptSchema.deckAction(name).map(VBSchema.defaultArguments(for:)) ?? []))393                    })) {394                        ForEach(ScriptSchema.deckActions, id: \.name) { a in Text(verbatim: a.name).tag(a.name) }395                    }396                    .labelsHidden().fixedSize()397                    if let def = ScriptSchema.deckAction(action) {398                        ForEach(Array(args.enumerated()), id: \.offset) { i, arg in399                            if i < def.params.count { Text(verbatim: def.params[i].name).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary) }400                            VBValueEditor(value: arg, def: nil) { v in var a = args; a[i] = v; set(.deckAction(deck: deck, action: action, args: a)) }401                        }402                    }403                }404                if let def = ScriptSchema.deckAction(action) { Text(verbatim: def.doc).font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(2).frame(width: 380, alignment: .leading) }405            } controls: { controls }406        case let .setParam(target, value):407            VBCard(symbol: "slider.vertical.3", title: "Mixer action: set parameter", tint: ORIX.Palette.accentSecondary) {408                HStack(spacing: 6) {409                    VBTargetPicker(target: target, mode: .writable) { new in set(.setParam(new, sameType(target, new) ? value : defaultValue(new))) }410                    Text(verbatim: "=").font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary)411                    VBValueEditor(value: value, def: ScriptSchema.definition(for: target)) { set(.setParam(target, $0)) }412                }413            } controls: { controls }414        case let .effect(rack, effect, op):415            VBCard(symbol: "sparkles", title: "Effect action", tint: ORIX.Palette.accent) {416                HStack(spacing: 6) {417                    Picker("Rack", selection: Binding(get: { rack ?? -1 }, set: { set(.effect(rack: $0 < 0 ? nil : $0, effect: effect, op: op)) })) {418                        Text("Master rack").tag(-1)419                        ForEach(0 ..< ScriptSchema.deckCount, id: \.self) { d in Text("Deck \(deckLetters[d]) rack").tag(d) }420                    }421                    .labelsHidden().fixedSize()422                    Picker("Effect", selection: Binding(get: { effect }, set: { new in423                        // A parameter of the previous effect does not carry over.424                        if case .set = op, let first = ScriptSchema.fxParams(new).first(where: \.writable) { set(.effect(rack: rack, effect: new, op: .set(key: first.key, value: VBValue.defaultValue(for: first)))) }425                        else { set(.effect(rack: rack, effect: new, op: op)) }426                    })) {427                        ForEach(EffectKind.allCases, id: \.self) { k in Text(verbatim: EffectCatalog.descriptor(k).displayName).tag(k) }428                    }429                    .labelsHidden().fixedSize()430                    Picker("Operation", selection: Binding(get: { opTag(op) }, set: { tag in431                        switch tag {432                        case 0: set(.effect(rack: rack, effect: effect, op: .enable))433                        case 1: set(.effect(rack: rack, effect: effect, op: .disable))434                        case 2: set(.effect(rack: rack, effect: effect, op: .toggle))435                        default:436                            if let first = ScriptSchema.fxParams(effect).first(where: \.writable) { set(.effect(rack: rack, effect: effect, op: .set(key: first.key, value: VBValue.defaultValue(for: first)))) }437                        }438                    })) {439                        Text("enable").tag(0); Text("disable").tag(1); Text("toggle").tag(2); Text("set parameter").tag(3)440                    }441                    .labelsHidden().fixedSize()442                }443                if case let .set(key, value) = op {444                    HStack(spacing: 6) {445                        Picker("Parameter", selection: Binding(get: { key }, set: { new in446                            if let def = ScriptSchema.fxParam(effect, new) { set(.effect(rack: rack, effect: effect, op: .set(key: new, value: VBValue.defaultValue(for: def)))) }447                        })) {448                            ForEach(ScriptSchema.fxParams(effect).filter(\.writable), id: \.key) { d in Text(verbatim: d.key).tag(d.key) }449                        }450                        .labelsHidden().fixedSize()451                        Text(verbatim: "=").font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary)452                        VBValueEditor(value: value, def: ScriptSchema.fxParam(effect, key)) { set(.effect(rack: rack, effect: effect, op: .set(key: key, value: $0))) }453                    }454                }455            } controls: { controls }456        case let .over(duration, curve, ramps):457            VBCard(symbol: "line.diagonal.arrow", title: "Parameter automation", tint: ORIX.Palette.warning) {458                HStack(spacing: 6) {459                    Text("over").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)460                    VBValueEditor(value: duration, def: nil) { set(.over(duration: $0, curve: curve, ramps: ramps)) }461                    Text("curve").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)462                    Picker("Curve", selection: Binding(get: { curve ?? "" }, set: { set(.over(duration: duration, curve: $0.isEmpty ? nil : $0, ramps: ramps)) })) {463                        Text("linear (default)").tag("")464                        ForEach(ScriptSchema.rampCurves, id: \.self) { c in Text(verbatim: c).tag(c) }465                    }466                    .labelsHidden().fixedSize()467                }468                ForEach(ramps) { ramp in469                    HStack(spacing: 6) {470                        VBTargetPicker(target: ramp.target, mode: .rampable) { new in471                            var r = ramps472                            if let i = r.firstIndex(where: { $0.id == ramp.id }) { r[i].target = new; if !sameType(ramp.target, new) { r[i].value = defaultValue(new) } }473                            set(.over(duration: duration, curve: curve, ramps: r))474                        }475                        Image(systemName: "arrow.right").font(.system(size: 10, weight: .bold)).foregroundStyle(ORIX.Palette.textSecondary).accessibilityLabel("ramps to")476                        VBValueEditor(value: ramp.value, def: ScriptSchema.definition(for: ramp.target)) { v in477                            var r = ramps478                            if let i = r.firstIndex(where: { $0.id == ramp.id }) { r[i].value = v }479                            set(.over(duration: duration, curve: curve, ramps: r))480                        }481                        Button { set(.over(duration: duration, curve: curve, ramps: ramps.filter { $0.id != ramp.id })) } label: { Image(systemName: "minus.circle") }482                            .buttonStyle(.borderless).help("Remove ramp").accessibilityLabel("Remove ramp")483                    }484                }485                Button { set(.over(duration: duration, curve: curve, ramps: ramps + [VBRamp(target: .deck(0, "volume"), value: .gain(0))])) } label: { Label("Add Ramp", systemImage: "plus") }486                    .buttonStyle(.borderless).controlSize(.small).font(.system(size: 11))487            } controls: { controls }488        case let .condition(c, thenBody, otherwise):489            VBCard(symbol: "arrow.triangle.branch", title: "Condition", tint: ORIX.Palette.accentSecondary) {490                HStack(spacing: 6) {491                    Text("if").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)492                    VBTargetPicker(target: c.left, mode: .readable) { new in493                        var n = c; n.left = new494                        if !sameType(c.left, new) { n.right = defaultValue(new); if !comparable(new) && !["==", "!="].contains(n.op) { n.op = "==" } }495                        set(.condition(n, then: thenBody, otherwise: otherwise))496                    }497                    Picker("Comparison", selection: Binding(get: { c.op }, set: { var n = c; n.op = $0; set(.condition(n, then: thenBody, otherwise: otherwise)) })) {498                        ForEach(comparable(c.left) ? VBCondition.operators : ["==", "!="], id: \.self) { op in Text(verbatim: op).tag(op) }499                    }500                    .labelsHidden().fixedSize()501                    VBValueEditor(value: c.right, def: ScriptSchema.definition(for: c.left)) { var n = c; n.right = $0; set(.condition(n, then: thenBody, otherwise: otherwise)) }502                }503                VBLane(title: "then") { VBBlockList(builder: builder, blocks: thenBody, parent: block.id, slot: .body, topLevel: false) }504                if let otherwise {505                    VBLane(title: "else") { VBBlockList(builder: builder, blocks: otherwise, parent: block.id, slot: .otherwise, topLevel: false) }506                    Button { set(.condition(c, then: thenBody, otherwise: nil)) } label: { Label("Remove Else", systemImage: "minus") }507                        .buttonStyle(.borderless).controlSize(.small).font(.system(size: 11)).disabled(!otherwise.isEmpty)508                        .help("Empty the else branch first.")509                } else {510                    Button { set(.condition(c, then: thenBody, otherwise: [])) } label: { Label("Add Else", systemImage: "plus") }511                        .buttonStyle(.borderless).controlSize(.small).font(.system(size: 11))512                }513            } controls: { controls }514        case let .loop(count, body):515            VBCard(symbol: "repeat", title: "Loop", tint: ORIX.Palette.success) {516                HStack(spacing: 6) {517                    Text("repeat").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)518                    TextField("Count", value: Binding(get: { count }, set: { set(.loop(count: min(max(0, $0), CompileLimits.maxLoopIterations), body: body)) }), format: .number)519                        .textFieldStyle(.roundedBorder).frame(width: 60).multilineTextAlignment(.trailing).monospacedDigit()520                        .accessibilityLabel("Repeat count")521                    Stepper("Repeat count", value: Binding(get: { count }, set: { set(.loop(count: min(max(0, $0), CompileLimits.maxLoopIterations), body: body)) }), in: 0 ... CompileLimits.maxLoopIterations).labelsHidden()522                    Text("times").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)523                }524                VBLane(title: "do") { VBBlockList(builder: builder, blocks: body, parent: block.id, slot: .body, topLevel: false) }525            } controls: { controls }526        case .stop:527            VBCard(symbol: "stop.fill", title: "Stop the automation", tint: ORIX.Palette.danger) { EmptyView() } controls: { controls }528        }529    }530531    private func waitTag(_ w: VBWait) -> Int { switch w { case .duration: 0; case .nextBeat: 1; case .nextBar: 2 } }532    private func opTag(_ op: VBEffectOp) -> Int { switch op { case .enable: 0; case .disable: 1; case .toggle: 2; case .set: 3 } }533    private func sameType(_ a: ParamAddress, _ b: ParamAddress) -> Bool {534        guard let x = ScriptSchema.definition(for: a), let y = ScriptSchema.definition(for: b) else { return false }535        return x.type == y.type && x.allowed == y.allowed && x.durationUnit == y.durationUnit536    }537    private func defaultValue(_ a: ParamAddress) -> VBValue { ScriptSchema.definition(for: a).map(VBValue.defaultValue(for:)) ?? .number(0) }538    private func comparable(_ a: ParamAddress) -> Bool {539        guard let t = ScriptSchema.definition(for: a)?.type else { return false }540        return [.number, .gain, .frequency, .duration].contains(t)541    }542}543544/// A nested lane of child blocks.545private struct VBLane<Content: View>: View {546    var title: LocalizedStringKey547    @ViewBuilder var content: Content548549    var body: some View {550        HStack(alignment: .top, spacing: 6) {551            Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 30, alignment: .trailing).padding(.top, 12)552            content553                .padding(.leading, 6).padding(.bottom, 4)554                .overlay(alignment: .leading) { Rectangle().fill(ORIX.Palette.hairline).frame(width: 2) }555        }556    }557}558559private struct VBDeckPicker: View {560    var deck: Int561    var onChange: (Int) -> Void562563    var body: some View {564        Picker("Deck", selection: Binding(get: { deck }, set: onChange)) {565            ForEach(0 ..< ScriptSchema.deckCount, id: \.self) { d in Text("Deck \(deckLetters[d])").tag(d) }566        }567        .labelsHidden().fixedSize()568    }569}570571private struct VBEventEditor: View {572    var event: VBEvent573    var onChange: (VBEvent) -> Void574575    private var tag: String {576        switch event { case let .deck(_, name): "deck." + name; case .beat: "beat"; case .bar: "bar"; case .trigger: "trigger" }577    }578579    var body: some View {580        HStack(spacing: 6) {581            Text("on").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)582            Picker("Event", selection: Binding(get: { tag }, set: { new in583                let deck: Int = { if case let .deck(d, _) = event { d } else { 0 } }()584                switch new {585                case "beat": onChange(.beat)586                case "bar": onChange(.bar)587                case "trigger": onChange(.trigger(1))588                default: onChange(.deck(deck, String(new.dropFirst(5))))589                }590            })) {591                ForEach(ScriptSchema.deckEvents, id: \.name) { e in Text(verbatim: "deck " + e.name).tag("deck." + e.name) }592                Text("every beat").tag("beat")593                Text("every bar").tag("bar")594                Text("trigger").tag("trigger")595            }596            .labelsHidden().fixedSize()597            switch event {598            case let .deck(d, name): VBDeckPicker(deck: d) { onChange(.deck($0, name)) }599            case let .trigger(n):600                Picker("Trigger number", selection: Binding(get: { n }, set: { onChange(.trigger($0)) })) {601                    ForEach(1 ... ScriptSchema.triggerCount, id: \.self) { i in Text(verbatim: "\(i)").tag(i) }602                }603                .labelsHidden().fixedSize()604            default: EmptyView()605            }606        }607    }608}609610/// Chooses a parameter: deck, mixer, master, and for ramps the effect racks.611struct VBTargetPicker: View {612    enum Mode { case writable, rampable, readable }613    var target: ParamAddress614    var mode: Mode615    var onChange: (ParamAddress) -> Void616617    private func deckKeys() -> [String] {618        ScriptSchema.deckParams.filter { mode == .readable || (mode == .writable ? $0.writable : $0.rampable) }.map(\.key)619    }620621    var body: some View {622        Menu {623            ForEach(0 ..< ScriptSchema.deckCount, id: \.self) { d in624                Menu("Deck \(deckLetters[d])") {625                    ForEach(deckKeys(), id: \.self) { key in Button { onChange(.deck(d, key)) } label: { Text(verbatim: key) } }626                }627            }628            Menu("Mixer") {629                ForEach(ScriptSchema.mixerParams.filter { mode == .readable || (mode == .writable ? $0.writable : $0.rampable) }, id: \.key) { def in630                    Button { onChange(.mixer(def.key)) } label: { Text(verbatim: def.key) }631                }632            }633            if mode != .rampable {634                Menu("Master clock") {635                    ForEach(ScriptSchema.masterParams.filter { mode == .readable || $0.writable }, id: \.key) { def in636                        Button { onChange(.master(def.key)) } label: { Text(verbatim: def.key) }637                    }638                }639            }640            if mode == .rampable {641                Menu("Effects") {642                    ForEach([-1, 0, 1, 2, 3], id: \.self) { rack in643                        Menu(rack < 0 ? "Master rack" : "Deck \(deckLetters[rack]) rack") {644                            ForEach(EffectKind.allCases, id: \.self) { kind in645                                Menu(EffectCatalog.descriptor(kind).displayName) {646                                    ForEach(VBSchema.rampableEffectTargets(kind, rack: rack < 0 ? nil : rack), id: \.self) { a in647                                        Button { onChange(a) } label: { Text(verbatim: a.key) }648                                    }649                                }650                            }651                        }652                    }653                }654            }655        } label: {656            Text(verbatim: target.description).font(ORIX.Typeface.mono)657        }658        .menuStyle(.borderlessButton).fixedSize()659        .help(Text(verbatim: ScriptSchema.definition(for: target)?.doc ?? ""))660        .accessibilityLabel("Parameter")661        .accessibilityValue(Text(verbatim: target.description))662    }663}664665/// Edits a literal with a control suited to its type and, when known, the parameter's range.666struct VBValueEditor: View {667    var value: VBValue668    var def: ParamDef?669    var onChange: (VBValue) -> Void670671    private func clamped(_ v: VBValue) -> VBValue {672        guard let def, def.max > def.min else { return v }673        switch v {674        case let .gain(x): return .gain(min(max(x, def.min), def.max))675        case let .frequency(x): return .frequency(min(max(x, def.min), def.max))676        case let .number(x): return .number(min(max(x, def.min), def.max))677        default: return v678        }679    }680681    var body: some View {682        switch value {683        case let .bool(b):684            Picker("Value", selection: Binding(get: { b }, set: { onChange(.bool($0)) })) { Text("true").tag(true); Text("false").tag(false) }685                .labelsHidden().pickerStyle(.segmented).fixedSize()686        case let .string(s):687            if let def, !def.allowed.isEmpty {688                Picker("Value", selection: Binding(get: { s }, set: { onChange(.string($0)) })) {689                    ForEach(def.allowed, id: \.self) { a in Text(verbatim: a).tag(a) }690                    if !def.allowed.contains(s) { Text(verbatim: s.isEmpty ? "(empty)" : s).tag(s) }691                }692                .labelsHidden().fixedSize()693            } else {694                TextField("Text", text: Binding(get: { s }, set: { onChange(.string($0)) })).textFieldStyle(.roundedBorder).frame(width: 140)695            }696        case .beats, .seconds:697            HStack(spacing: 4) {698                field699                Picker("Unit", selection: Binding(get: { value.unitLabel }, set: { onChange(value.with(durationUnit: $0)) })) {700                    ForEach(VBValue.durationUnits, id: \.self) { u in Text(verbatim: u).tag(u) }701                }702                .labelsHidden().fixedSize()703            }704        case .number, .gain, .frequency:705            HStack(spacing: 4) {706                field707                if !value.unitLabel.isEmpty { Text(verbatim: value.unitLabel).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary) }708                else if let def, !def.unit.isEmpty, def.unit != "%" { Text(verbatim: def.unit).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary) }709            }710            .help(Text(verbatim: def.map { "Range: " + $0.rangeText } ?? ""))711        }712    }713714    private var field: some View {715        TextField("Value", value: Binding(get: { value.magnitude }, set: { onChange(clamped(value.with(magnitude: $0))) }), format: .number.precision(.fractionLength(0 ... 3)).grouping(.never))716            .textFieldStyle(.roundedBorder).frame(width: 72).multilineTextAlignment(.trailing).monospacedDigit()717            .accessibilityLabel("Value")718            .accessibilityValue(Text(verbatim: value.source))719    }720}721
Files main
Menu

Theme