SPB Git

Repository Public License

DesignView.swift 22.5 KB 459 lines swift

1import PrismComponentSDK2import PrismCore3import PrismLogicRuntime4import PrismObjectModel5import PrismRenderer6import PrismIconKit7import SwiftUI89/// Design mode: hierarchy, palette, the real running app as canvas, and an inspector.10/// Every edit here is a deterministic blueprint patch; no model call is made.11struct DesignView: View {12    @Bindable var model: StudioModel13    @Bindable var session: ProjectSession14    @State private var paletteQuery = ""15    @State private var clipboard: PrismObject?1617    var body: some View {18        ResizableSplit(initial: .first(264), minFirst: 220, minSecond: 560) {19            VStack(spacing: 0) {20                hierarchy21                Divider()22                palette23            }24        } second: {25            ResizableSplit(initial: .second(304), minFirst: 280, minSecond: 250) {26                canvas.frame(maxWidth: .infinity, maxHeight: .infinity)27            } second: {28                InspectorPane(model: model, session: session)29            }30        }31    }3233    // MARK: Canvas3435    private var canvas: some View {36        VStack(spacing: 0) {37            let issues = session.currentIssues38            if issues.hasErrors {39                HStack {40                    Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange)41                    Text("\(issues.errors.count) problem(s): \(issues.errors[0].message)").font(.callout).lineLimit(2)42                    Spacer()43                    if let id = issues.errors[0].objectID { Button("Select") { session.designSelection = id } }44                }45                .padding(8).background(.orange.opacity(0.12))46            }47            if let runtime = session.runtime {48                // Apps have a natural minimum size; a narrow canvas scrolls instead of squeezing or clipping the app.49                GeometryReader { geo in50                    ScrollView([.horizontal, .vertical]) {51                        AppView(runtime: runtime)52                            .environment(\.prismDesign, DesignContext(selectedID: session.designSelection) { session.designSelection = $0 })53                            .frame(width: max(geo.size.width, 940), height: max(geo.size.height, 620))54                    }55                }56                    .dropDestination(for: String.self) { items, _ in57                        guard let type = items.first, type.hasPrefix("prism.") else { return false }58                        return session.addComponent(type) != nil59                    }60            } else {61                ContentUnavailableView("Nothing to design yet", systemImage: "paintbrush")62            }63        }64    }6566    // MARK: Hierarchy6768    struct Node: Identifiable {69        let id: String70        let object: PrismObject71        let depth: Int72    }7374    /// The tree flattened in display order, always fully expanded so a selection made on the canvas is visible here.75    private func nodes(_ bp: AppBlueprint) -> [Node] {76        var out: [Node] = []77        func walk(_ id: String, _ depth: Int) {78            guard let o = bp.object(id), depth < 40, !out.contains(where: { $0.id == id }) else { return }79            out.append(Node(id: o.id, object: o, depth: depth))80            o.children.forEach { walk($0, depth + 1) }81        }82        bp.pages.forEach { walk($0.id, 0) }83        return out84    }8586    private var hierarchy: some View {87        VStack(alignment: .leading, spacing: 0) {88            HStack {89                Text("Hierarchy").font(.headline)90                Spacer()91                Button { move(-1) } label: { Image(systemName: "arrow.up") }.help("Move up").disabled(!canMove(-1)).accessibilityLabel("Move up")92                Button { move(1) } label: { Image(systemName: "arrow.down") }.help("Move down").disabled(!canMove(1)).accessibilityLabel("Move down")93                Button { copySelection() } label: { Image(systemName: "doc.on.doc") }.help("Copy (⌘C)").disabled(selected?.isComponent != true).keyboardShortcut("c").accessibilityLabel("Copy")94                Button { paste() } label: { Image(systemName: "doc.on.clipboard") }.help("Paste (⌘V)").disabled(clipboard == nil).keyboardShortcut("v").accessibilityLabel("Paste")95                Button(role: .destructive) { deleteSelection() } label: { Image(systemName: "trash") }.help("Delete (⌫)").disabled(selected?.isComponent != true).keyboardShortcut(.delete, modifiers: []).accessibilityLabel("Delete")96            }97            .buttonStyle(.borderless)98            .padding(10)99            if let bp = session.blueprint {100                List(nodes(bp), selection: $session.designSelection) { node in101                    Label {102                        VStack(alignment: .leading, spacing: 0) {103                            Text(node.object.name.isEmpty ? node.object.id : node.object.name).lineLimit(1)104                            Text(node.object.type.replacingOccurrences(of: "prism.", with: "")).font(.caption2).foregroundStyle(.secondary)105                        }106                    } icon: { Image(systemName: node.object.isPage ? "doc" : icon(node.object.type)) }107                    .padding(.leading, CGFloat(node.depth) * 12)108                    .tag(node.id)109                    .draggable(node.id)110                    .dropDestination(for: String.self) { items, _ in _ = drop(items.first, on: node.object) }111                }112                .listStyle(.sidebar)113            }114        }115        .frame(minHeight: 220, maxHeight: .infinity)116    }117118    private func icon(_ type: String) -> String {119        switch session.manifest(type)?.category {120        case "forms": "character.cursor.ibeam"121        case "data": "tablecells"122        case "charts": "chart.bar"123        case "navigation": "sidebar.left"124        default: "square.on.square"125        }126    }127128    private var selected: PrismObject? { session.designSelection.flatMap { session.blueprint?.object($0) } }129130    private func canMove(_ delta: Int) -> Bool {131        guard let s = selected, let parent = session.blueprint?.parent(of: s.id), let i = parent.children.firstIndex(of: s.id) else { return false }132        return parent.children.indices.contains(i + delta)133    }134135    private func move(_ delta: Int) {136        guard let s = selected, let parent = session.blueprint?.parent(of: s.id), let i = parent.children.firstIndex(of: s.id) else { return }137        session.edit([.moveChild(id: s.id, toParent: parent.id, index: i + delta)], label: "Move \(s.name.isEmpty ? s.id : s.name)")138    }139140    private func deleteSelection() {141        guard let s = selected, s.isComponent else { return }142        session.designSelection = session.blueprint?.parent(of: s.id)?.id143        session.edit([.removeObject(id: s.id)], label: "Delete \(s.name.isEmpty ? s.id : s.name)")144    }145146    private func copySelection() { clipboard = selected }147148    private func paste() {149        guard var copy = clipboard, let bp = session.blueprint, copy.children.isEmpty || true else { return }150        copy.id = bp.uniqueID(copy.id)151        copy.children = []152        let target = selected.flatMap { s in session.manifest(s.type)?.acceptsChildren == true ? s.id : bp.parent(of: s.id)?.id } ?? bp.pages.first?.children.first153        guard let target else { return }154        if session.edit([.addObject(copy, parent: target, index: nil)], label: "Paste \(copy.name.isEmpty ? copy.type : copy.name)") { session.designSelection = copy.id }155    }156157    /// Dropping a palette item adds it; dropping a hierarchy row moves it (into containers, or next to leaves).158    private func drop(_ item: String?, on target: PrismObject) -> Bool {159        guard let item, let bp = session.blueprint else { return false }160        if item.hasPrefix("prism."), bp.object(item) == nil { return session.addComponent(item, to: target.id) != nil }161        guard item != target.id, let moving = bp.object(item), moving.isComponent else { return false }162        let name = moving.name.isEmpty ? moving.id : moving.name163        if target.isPage || session.manifest(target.type)?.acceptsChildren == true {164            return session.edit([.moveChild(id: item, toParent: target.id, index: nil)], label: "Move \(name)")165        }166        guard let parent = bp.parent(of: target.id), let index = parent.children.firstIndex(of: target.id) else { return false }167        return session.edit([.moveChild(id: item, toParent: parent.id, index: index)], label: "Move \(name)")168    }169170    // MARK: Palette171172    private var palette: some View {173        VStack(alignment: .leading, spacing: 6) {174            TextField("Search components", text: $paletteQuery).textFieldStyle(.roundedBorder).padding([.horizontal, .top], 10)175            List(model.registry.search(paletteQuery, limit: 60).map(\.manifest)) { manifest in176                HStack {177                    Image(systemName: icon(manifest.type)).foregroundStyle(.secondary).frame(width: 18)178                    VStack(alignment: .leading, spacing: 0) {179                        Text(manifest.name)180                        Text(manifest.summary).font(.caption2).foregroundStyle(.secondary).lineLimit(1)181                    }182                    Spacer()183                    Button { session.addComponent(manifest.type) } label: { Image(systemName: "plus.circle") }184                        .buttonStyle(.borderless).help("Add to the selected container").accessibilityLabel("Add \(manifest.name)")185                }186                .draggable(manifest.type)187            }188            .listStyle(.inset)189        }190        .frame(minHeight: 200, maxHeight: .infinity)191    }192}193194/// Properties of the selected component, or the app's theme when nothing is selected.195struct InspectorPane: View {196    @Bindable var model: StudioModel197    @Bindable var session: ProjectSession198199    var body: some View {200        ScrollView {201            VStack(alignment: .leading, spacing: 14) {202                if let id = session.designSelection, let object = session.blueprint?.object(id) {203                    objectInspector(object)204                } else {205                    themeInspector206                }207            }208            .padding(14)209            .frame(maxWidth: .infinity, alignment: .leading)210        }211        .background(.background.secondary)212    }213214    @ViewBuilder215    private func objectInspector(_ object: PrismObject) -> some View {216        let manifest = session.manifest(object.type)217        VStack(alignment: .leading, spacing: 4) {218            Text(manifest?.name ?? (object.isPage ? "Page" : object.type)).font(.headline)219            Text(object.id).font(.caption.monospaced()).foregroundStyle(.secondary).textSelection(.enabled)220        }221        CommitField(label: "Name", value: object.name) { session.edit([.setField(id: object.id, field: "name", value: .string($0))], label: "Rename") }222        if let manifest {223            Text(manifest.summary).font(.caption).foregroundStyle(.secondary)224            Divider()225            ForEach(manifest.props + CommonProps.all, id: \.name) { spec in226                PropEditor(spec: spec, value: object.props[spec.name]) { new in227                    if let new { session.edit([.setProp(id: object.id, key: spec.name, value: new)], label: "Change \(spec.name)") }228                    else { session.edit([.removeProp(id: object.id, key: spec.name)], label: "Reset \(spec.name)") }229                }230                .id(object.id + "." + spec.name)231            }232            if !manifest.events.isEmpty {233                Divider()234                Text("Events").font(.headline)235                ForEach(manifest.events, id: \.self) { event in236                    JSONEditor(label: event, summary: "Actions run on \(event).", value: object.events[event].map(JSONValue.array)) { new in237                        session.edit([.setEvent(id: object.id, event: event, actions: new?.arrayValue ?? [])], label: "Change \(event) actions")238                    }239                    .id(object.id + ".event." + event)240                }241            }242        } else if object.isPage {243            Text("A page shows its first child. Select a component to edit it.").font(.caption).foregroundStyle(.secondary)244        }245        let issues = session.currentIssues.filter { $0.objectID == object.id }246        if !issues.isEmpty {247            Divider()248            ForEach(Array(issues.enumerated()), id: \.offset) { _, issue in249                Label(issue.message, systemImage: issue.severity == .error ? "xmark.circle" : "exclamationmark.triangle").font(.caption).foregroundStyle(issue.severity == .error ? .red : .orange)250            }251        }252        Button("Edit App Theme") { session.designSelection = nil }.buttonStyle(.link)253    }254255    private var themeInspector: some View {256        let theme = session.blueprint?.theme ?? [:]257        func set(_ key: String, _ value: JSONValue?) {258            var t = theme259            t[key] = value260            session.edit([.setBlueprintField(field: "theme", value: .object(t))], label: "Change theme")261        }262        return VStack(alignment: .leading, spacing: 12) {263            Text("App theme").font(.headline)264            Text("Select a component on the canvas or in the hierarchy to edit it.").font(.caption).foregroundStyle(.secondary)265            Picker("Preset", selection: Binding(get: { theme["preset"]?.stringValue ?? "" }, set: { set("preset", $0.isEmpty ? nil : .string($0)) })) {266                Text("None").tag("")267                ForEach(ThemeSpec.presets, id: \.name) { Text($0.name.capitalized).tag($0.name).help($0.summary) }268            }269            .help("A complete look: colors, fonts and panel style. The settings below override it.")270            Picker("Font", selection: Binding(get: { theme["font"]?.stringValue ?? "" }, set: { set("font", $0.isEmpty ? nil : .string($0)) })) {271                Text("From preset").tag("")272                ForEach(ThemeSpec.fonts, id: \.self) { Text($0.capitalized).tag($0) }273            }274            Picker("Panels", selection: Binding(get: { theme["surface"]?.stringValue ?? "" }, set: { set("surface", $0.isEmpty ? nil : .string($0)) })) {275                Text("From preset").tag("")276                ForEach(ThemeSpec.surfaces, id: \.self) { Text($0.capitalized).tag($0) }277            }278            Text("Accent color").font(.callout)279            HStack(spacing: 6) {280                ForEach(PrismTheme.accentChoices, id: \.hex) { choice in281                    Button { set("accent", .string(choice.hex)) } label: {282                        Circle().fill(Color(hex: choice.hex) ?? .accentColor).frame(width: 22, height: 22)283                            .overlay(Circle().strokeBorder(.primary, lineWidth: theme["accent"]?.stringValue == choice.hex ? 2 : 0))284                    }285                    .buttonStyle(.plain).accessibilityLabel("\(choice.name) accent").help(choice.name)286                }287            }288            Picker("Appearance", selection: Binding(get: { theme["appearance"]?.stringValue ?? "system" }, set: { set("appearance", .string($0)) })) {289                Text("System").tag("system"); Text("Light").tag("light"); Text("Dark").tag("dark")290            }291            Picker("Density", selection: Binding(get: { theme["density"]?.stringValue ?? "regular" }, set: { set("density", .string($0)) })) {292                Text("Compact").tag("compact"); Text("Regular").tag("regular"); Text("Comfortable").tag("comfortable")293            }294            LabeledContent("Corner radius") {295                Slider(value: Binding(get: { theme["radius"]?.doubleValue ?? 10 }, set: { set("radius", .double($0.rounded())) }), in: 0...20, step: 2).frame(width: 140)296            }297            CommitField(label: "App name", value: session.blueprint?.name ?? "") { session.edit([.setBlueprintField(field: "name", value: .string($0))], label: "Rename app") }298        }299    }300}301302/// A text field that commits on Return or when focus leaves, so each change is one undo step.303struct CommitField: View {304    let label: String305    let value: String306    var showsLabel = true307    let commit: (String) -> Void308    @State private var draft = ""309    @FocusState private var focused: Bool310311    var body: some View {312        VStack(alignment: .leading, spacing: 3) {313            if showsLabel { Text(label).font(.caption).foregroundStyle(.secondary) }314            TextField(label, text: $draft).textFieldStyle(.roundedBorder).focused($focused).onSubmit(apply).labelsHidden().accessibilityLabel(label)315        }316        .onAppear { draft = value }317        .onChange(of: value) { _, new in if !focused { draft = new } }318        .onChange(of: focused) { _, isFocused in if !isFocused { apply() } }319    }320321    private func apply() { if draft != value { commit(draft) } }322}323324struct PropEditor: View {325    let spec: PropSpec326    let value: JSONValue?327    let commit: (JSONValue?) -> Void328329    private var dynamic: DynamicValue? { value.map(DynamicValue.init) }330331    var body: some View {332        VStack(alignment: .leading, spacing: 3) {333            HStack(spacing: 4) {334                Text(spec.name + (spec.required ? " *" : "")).font(.caption).foregroundStyle(.secondary)335                Spacer()336                if spec.dynamic || spec.binding != .none, spec.kind != .query, spec.kind != .list, spec.kind != .object {337                    Menu {338                        Button("Fixed value") { commit(spec.defaultValue) }339                        if spec.dynamic { Button("Expression") { commit(["$expr": "''"]) } }340                        if spec.binding != .none { Button("Bound to state") { commit(["$bind": "key"]) } }341                        if !spec.required { Button("Reset to default") { commit(nil) } }342                    } label: { Image(systemName: modeSymbol) }343                    .menuStyle(.borderlessButton).fixedSize().help("How this value is provided").accessibilityLabel("Value kind for \(spec.name)")344                }345            }346            editor347        }348        .help(spec.summary)349    }350351    private var modeSymbol: String {352        switch dynamic {353        case .expression: "function"354        case .binding: "link"355        default: "textformat"356        }357    }358359    @ViewBuilder360    private var editor: some View {361        switch dynamic {362        case .expression(let source):363            ExpressionField(prefix: "fx", text: source) { commit(["$expr": .string($0)]) }364        case .binding(let path):365            ExpressionField(prefix: "state.", text: path) { commit(["$bind": .string($0)]) }366        default:367            switch spec.kind {368            case .boolean:369                Toggle(spec.summary, isOn: Binding(get: { value?.boolValue ?? spec.defaultValue?.boolValue ?? false }, set: { commit(.bool($0)) })).font(.caption).toggleStyle(.switch).controlSize(.small)370            case .enum:371                Picker(spec.name, selection: Binding(get: { value?.stringValue ?? spec.defaultValue?.stringValue ?? "" }, set: { commit(.string($0)) })) {372                    if value == nil && spec.defaultValue == nil { Text("—").tag("") }373                    ForEach(spec.enumValues, id: \.self) { Text($0).tag($0) }374                }.labelsHidden()375            case .number:376                CommitField(label: spec.name, value: value?.displayString ?? "", showsLabel: false) { text in377                    if text.isEmpty { commit(nil) } else if let d = Double(text) { commit(d.rounded() == d ? .int(Int(d)) : .double(d)) }378                }379            case .string:380                CommitField(label: spec.name, value: value?.stringValue ?? "", showsLabel: false) { commit($0.isEmpty && !spec.required ? nil : .string($0)) }381            case .list, .object, .query, .any:382                JSONEditor(label: nil, summary: spec.summary, value: value, commit: commit)383            }384        }385    }386}387388struct ExpressionField: View {389    let prefix: String390    let text: String391    let commit: (String) -> Void392    @State private var draft = ""393    @FocusState private var focused: Bool394395    var body: some View {396        let problem: String? = prefix == "fx" ? (try? Expression(draft)).map { _ in nil } ?? "Not a valid expression" : (StatePath.isValid(draft) ? nil : "Not a valid state key")397        VStack(alignment: .leading, spacing: 2) {398            HStack(spacing: 4) {399                Text(prefix).font(.caption.monospaced()).foregroundStyle(.tint)400                TextField("", text: $draft).font(.callout.monospaced()).textFieldStyle(.roundedBorder).focused($focused)401                    .onSubmit { if problem == nil, draft != text { commit(draft) } }402                    .accessibilityLabel(prefix == "fx" ? "Expression" : "State key")403            }404            if let problem, draft != text { Text(problem).font(.caption2).foregroundStyle(.red) }405        }406        .onAppear { draft = text }407        .onChange(of: text) { _, new in if !focused { draft = new } }408        .onChange(of: focused) { _, isFocused in if !isFocused, problem == nil, draft != text { commit(draft) } }409    }410}411412/// Structured values (queries, lists, actions) are edited as JSON, validated before they are applied.413struct JSONEditor: View {414    let label: String?415    let summary: String416    let value: JSONValue?417    let commit: (JSONValue?) -> Void418    @State private var draft = ""419    @State private var error: String?420    @State private var editing = false421422    var body: some View {423        VStack(alignment: .leading, spacing: 3) {424            HStack {425                if let label { Text(label).font(.caption.monospaced()) }426                Text(value == nil ? "not set" : shortDescription).font(.caption).foregroundStyle(.secondary).lineLimit(1)427                Spacer()428                Button(editing ? "Done" : "Edit") {429                    if editing { apply() } else { draft = value?.prettyString() ?? ""; error = nil; editing = true }430                }431                .controlSize(.small)432            }433            if editing {434                TextEditor(text: $draft).font(.caption.monospaced()).frame(minHeight: 90, maxHeight: 220)435                    .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.separator)).accessibilityLabel("JSON for \(label ?? "value")")436                Text(summary).font(.caption2).foregroundStyle(.secondary)437                if let error { Text(error).font(.caption2).foregroundStyle(.red) }438            }439        }440    }441442    private var shortDescription: String {443        if let a = value?.arrayValue { return "\(a.count) item\(a.count == 1 ? "" : "s")" }444        if let t = value?["table"]?.stringValue { return "query on \(t)" }445        if let r = value?["$ref"]?.stringValue { return "query \(r)" }446        return String((value?.canonicalString() ?? "").prefix(40))447    }448449    private func apply() {450        let trimmed = draft.trimmingCharacters(in: .whitespacesAndNewlines)451        if trimmed.isEmpty { commit(nil); editing = false; return }452        do {453            let parsed = try JSONValue.parse(trimmed)454            if parsed != value { commit(parsed) }455            editing = false456        } catch let e { error = e.localizedDescription }457    }458}459
Files main
Menu

Theme