SPB Git

Repository Public License

CustomComponents.swift 24.2 KB 498 lines swift

1import PrismComponentSDK2import PrismCore3import PrismIconKit4import PrismObjectModel5import SwiftUI67/// What a node of an on-demand component needs to resolve colors and call back into its script.8@MainActor9struct CustomContext {10    let runtime: AppRuntime11    let theme: PrismTheme12    let definition: String13    let instance: String14    let props: JSONValue15    let interactive: Bool1617    /// A handler is a function name or `{call, args}`; it receives its args, then one event object.18    func fire(_ handler: JSONValue?, _ event: [String: JSONValue] = [:]) {19        guard interactive, let handler, let name = handler.stringValue ?? handler["call"]?.stringValue else { return }20        var e = event21        e["props"] = props22        runtime.callComponent(definition, name, (handler["args"]?.arrayValue ?? []) + [.object(e)], instance: instance)23    }2425    func color(_ value: JSONValue?) -> Color? {26        guard let name = value?.stringValue, !name.isEmpty else { return nil }27        if name.hasPrefix("#") { return Color(hex: name) }28        switch name {29        case "accent": return theme.accent30        case "text", "primary": return .primary31        case "secondary": return .secondary32        case "tertiary": return Color(nsColor: .tertiaryLabelColor)33        case "surface": return theme.surfaceColor ?? Color(nsColor: .controlBackgroundColor)34        case "background": return theme.background ?? Color(nsColor: .windowBackgroundColor)35        case "border": return theme.border ?? Color(nsColor: .separatorColor)36        case "success", "warning", "danger", "info": return theme.color(name)37        case "white": return .white38        case "black": return .black39        case "clear": return .clear40        default: return nil41        }42    }4344    func fill(_ value: JSONValue?) -> AnyShapeStyle? {45        if let stops = value?["gradient"]?.arrayValue {46            let colors = stops.compactMap(color)47            guard colors.count > 1 else { return colors.first.map(AnyShapeStyle.init) }48            let a = (value?["angle"]?.doubleValue ?? 90) * .pi / 18049            return AnyShapeStyle(LinearGradient(colors: colors, startPoint: UnitPoint(x: 0.5 - cos(a) / 2, y: 0.5 - sin(a) / 2), endPoint: UnitPoint(x: 0.5 + cos(a) / 2, y: 0.5 + sin(a) / 2)))50        }51        return color(value).map(AnyShapeStyle.init)52    }53}5455/// An instance of an on-demand component: asks the definition's `render(props)` for a view tree and draws it.56struct CustomComponentView: View {57    @Environment(AppRuntime.self) private var runtime58    @Environment(\.prismTheme) private var theme59    @Environment(\.prismDesign) private var design60    @FocusState private var focused: Bool61    let o: PrismObject6263    var body: some View {64        let id = CustomComponent.id(ofType: o.type) ?? ""65        if let definition = runtime.blueprint.object(id), definition.isComponentDefinition {66            let props = resolvedProps(definition)67            let context = CustomContext(runtime: runtime, theme: theme, definition: id, instance: o.id, props: props, interactive: design == nil)68            // Reading local state here makes the view follow `app.setLocal`.69            let _ = runtime.localState[o.id]70            let _ = runtime.dataRevision71            if let tree = runtime.callComponent(id, "render", [props], instance: o.id, readOnly: true), tree.objectValue != nil {72                let tick = definition.props["tick"]?.doubleValue73                CustomNode(node: tree, context: context, depth: 0)74                    .animation(tree["animate"]?.boolValue == true ? .snappy(duration: 0.25) : nil, value: tree)75                    .modifier(KeyHandling(enabled: definition.props["keys"]?.boolValue == true && design == nil, focused: $focused) { key in context.fire("key", ["key": .string(key)]) })76                    .task(id: tick.map { "\($0)-\(design == nil)" } ?? "") {77                        guard let tick, tick >= 0.03, design == nil else { return }78                        while !Task.isCancelled {79                            try? await Task.sleep(for: .seconds(tick))80                            if Task.isCancelled { break }81                            runtime.callComponent(id, "tick", [props], instance: o.id, optional: true)82                        }83                    }84            } else {85                Label("“\(definition.name.isEmpty ? id : definition.name)” could not be drawn. See the app's log.", systemImage: "exclamationmark.triangle")86                    .foregroundStyle(.orange).font(.callout).padding(8)87            }88        } else {89            Label("Unknown component “\(o.type)”", systemImage: "puzzlepiece.extension").foregroundStyle(.orange).padding(8)90        }91    }9293    /// Declared props with their current values: expressions evaluated, bindings read, queries run, defaults filled in.94    private func resolvedProps(_ definition: PrismObject) -> JSONValue {95        var out: [String: JSONValue] = [:]96        for spec in definition.props["props"]?.arrayValue ?? [] {97            guard let name = spec["name"]?.stringValue else { continue }98            let raw = o.props[name]99            if spec["kind"]?.stringValue == "query", raw != nil { out[name] = .array(runtime.rows(raw).map(JSONValue.object)) }100            else if let path = runtime.bindingPath(raw) { out[name] = StatePathBridge.get(path, runtime) }101            else if raw != nil { out[name] = runtime.resolve(raw) }102            else { out[name] = spec["default"] ?? .null }103        }104        return .object(out)105    }106}107108enum StatePathBridge {109    @MainActor static func get(_ path: String, _ runtime: AppRuntime) -> JSONValue { runtime.resolve(["$expr": .string("state." + path)]) }110}111112private struct KeyHandling: ViewModifier {113    let enabled: Bool114    var focused: FocusState<Bool>.Binding115    let handle: (String) -> Void116117    func body(content: Content) -> some View {118        if enabled {119            content.focusable().focused(focused).focusEffectDisabled()120                .onKeyPress(phases: .down) { press in121                    let name: String = switch press.key {122                    case .upArrow: "ArrowUp"123                    case .downArrow: "ArrowDown"124                    case .leftArrow: "ArrowLeft"125                    case .rightArrow: "ArrowRight"126                    case .space: "Space"127                    case .return: "Enter"128                    case .escape: "Escape"129                    case .delete: "Backspace"130                    case .tab: "Tab"131                    default: press.characters132                    }133                    handle(name)134                    return .handled135                }136                .onAppear { focused.wrappedValue = true }137                .simultaneousGesture(TapGesture().onEnded { focused.wrappedValue = true })138        } else { content }139    }140}141142private struct KeyedNode: Identifiable {143    let id: String144    let node: JSONValue145}146147/// One node of a component's view tree. Unknown node types draw nothing rather than failing.148struct CustomNode: View {149    static let maxDepth = 40150    static let maxChildren = 2000151152    let node: JSONValue153    let context: CustomContext154    let depth: Int155156    private var children: [KeyedNode] {157        (node["children"]?.arrayValue ?? []).prefix(Self.maxChildren).enumerated().map { i, child in158            KeyedNode(id: child["id"].map { "id:" + $0.displayString } ?? "#\(i)", node: child)159        }160    }161162    private func number(_ key: String) -> CGFloat? { node[key]?.doubleValue.map { CGFloat($0) } }163    private func text(_ key: String) -> String { node[key]?.displayString ?? "" }164165    var body: some View {166        if depth < Self.maxDepth { core.modifier(NodeBox(node: node, context: context)) }167    }168169    @ViewBuilder private var kids: some View {170        ForEach(children) { CustomNode(node: $0.node, context: context, depth: depth + 1) }171    }172173    @ViewBuilder private var core: some View {174        switch node["type"]?.stringValue ?? "" {175        case "vstack":176            let a = node["align"]?.stringValue177            VStack(alignment: a == "center" ? .center : a == "trailing" ? .trailing : .leading, spacing: number("spacing") ?? context.theme.spacing) { kids }178        case "hstack":179            let a = node["align"]?.stringValue180            HStack(alignment: a == "top" ? .top : a == "bottom" ? .bottom : .center, spacing: number("spacing") ?? context.theme.spacing) { kids }181        case "zstack":182            ZStack(alignment: zAlignment(node["align"]?.stringValue)) { kids }183        case "grid":184            let count = max(1, min(Int(number("columns") ?? 2), 60))185            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: number("spacing") ?? context.theme.spacing), count: count), spacing: number("spacing") ?? context.theme.spacing) { kids }186        case "scroll":187            ScrollView(node["axis"]?.stringValue == "horizontal" ? .horizontal : .vertical) { kids }188        case "text":189            textView190        case "symbol":191            Image(systemName: SymbolName.safe(node["name"]?.stringValue))192                .font(.system(size: number("size") ?? 17, weight: weight(node["weight"]?.stringValue)))193                .foregroundStyle(context.color(node["color"]) ?? .primary)194        case "rect":195            shape(RoundedRectangle(cornerRadius: number("radius") ?? 0, style: .continuous))196        case "circle":197            shape(Circle())198        case "ellipse":199            shape(Ellipse())200        case "capsule":201            shape(Capsule())202        case "spacer":203            Spacer(minLength: number("minLength") ?? 0)204        case "divider":205            Divider()206        case "button":207            buttonView208        case "input":209            TextField(text("placeholder"), text: Binding(get: { text("value") }, set: { context.fire(node["onChange"], ["value": .string($0)]) }))210                .textFieldStyle(.roundedBorder)211                .onSubmit { context.fire(node["onSubmit"], ["value": node["value"] ?? ""]) }212                .accessibilityLabel(text("label").isEmpty ? text("placeholder") : text("label"))213        case "toggle":214            Toggle(text("label"), isOn: Binding(get: { node["value"]?.isTruthy ?? false }, set: { context.fire(node["onChange"], ["value": .bool($0)]) }))215        case "slider":216            let lo = node["min"]?.doubleValue ?? 0, hi = max(node["max"]?.doubleValue ?? 1, lo + 0.0001)217            Slider(value: Binding(get: { min(max(node["value"]?.doubleValue ?? lo, lo), hi) }, set: { context.fire(node["onChange"], ["value": .double($0)]) }), in: lo...hi)218                .accessibilityLabel(text("label").isEmpty ? "Slider" : text("label"))219        case "picker":220            pickerView221        case "progress":222            ProgressView(value: min(max(node["value"]?.doubleValue ?? 0, 0), 1)).tint(context.color(node["color"]) ?? context.theme.accent)223        case "canvas":224            CustomCanvas(node: node, context: context)225        default:226            EmptyView()227        }228    }229230    @ViewBuilder private var textView: some View {231        let design: Font.Design? = switch node["font"]?.stringValue { case "rounded": .rounded; case "serif": .serif; case "monospaced": .monospaced; default: nil }232        let base: Text = node["markdown"]?.boolValue == true233            ? Text((try? AttributedString(markdown: text("text"), options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text("text")))234            : Text(text("text"))235        let a = node["align"]?.stringValue236        base.font(.system(size: number("size") ?? 13, weight: weight(node["weight"]?.stringValue), design: design))237            .italic(node["italic"]?.boolValue == true)238            .strikethrough(node["strike"]?.boolValue == true)239            .monospacedDigit()240            .foregroundStyle(context.color(node["color"]) ?? .primary)241            .multilineTextAlignment(a == "center" ? .center : a == "trailing" ? .trailing : .leading)242            .lineLimit(node["lineLimit"]?.intValue)243    }244245    @ViewBuilder private var buttonView: some View {246        let title = text("title"), symbol = node["symbol"]?.stringValue247        let button = Button(role: node["style"]?.stringValue == "destructive" ? .destructive : nil) { context.fire(node["onTap"]) } label: {248            if let symbol, !title.isEmpty { Label(title, systemImage: SymbolName.safe(symbol)) }249            else if let symbol { Image(systemName: SymbolName.safe(symbol)) }250            else { Text(title) }251        }252        .disabled(node["disabled"]?.boolValue == true || node["onTap"] == nil)253        .accessibilityLabel(title.isEmpty ? text("label") : title)254        switch node["style"]?.stringValue {255        case "primary": button.buttonStyle(.borderedProminent)256        case "plain": button.buttonStyle(.plain)257        default: button.buttonStyle(.bordered)258        }259    }260261    @ViewBuilder private var pickerView: some View {262        let options = (node["options"]?.arrayValue ?? []).prefix(200).map { (value: $0["value"] ?? $0, label: ($0["label"] ?? $0).displayString) }263        let picker = Picker(text("label"), selection: Binding(get: { (node["value"] ?? .null).canonicalString() }, set: { chosen in264            if let o = options.first(where: { $0.value.canonicalString() == chosen }) { context.fire(node["onChange"], ["value": o.value]) }265        })) {266            ForEach(Array(options.enumerated()), id: \.offset) { _, o in Text(o.label).tag(o.value.canonicalString()) }267        }268        if node["style"]?.stringValue == "segmented" { picker.pickerStyle(.segmented).labelsHidden() } else { picker }269    }270271    @ViewBuilder private func shape<S: InsettableShape>(_ s: S) -> some View {272        let width = number("strokeWidth") ?? 1273        s.fill(context.fill(node["fill"]) ?? AnyShapeStyle(.clear))274            .overlay { if let stroke = context.color(node["stroke"]) { s.strokeBorder(stroke, lineWidth: width) } }275    }276277    private func weight(_ name: String?) -> Font.Weight {278        switch name {279        case "light": .light280        case "medium": .medium281        case "semibold": .semibold282        case "bold": .bold283        case "heavy": .heavy284        case "black": .black285        default: .regular286        }287    }288289    private func zAlignment(_ name: String?) -> Alignment {290        switch name {291        case "topLeading": .topLeading292        case "top": .top293        case "topTrailing": .topTrailing294        case "leading": .leading295        case "trailing": .trailing296        case "bottomLeading": .bottomLeading297        case "bottom": .bottom298        case "bottomTrailing": .bottomTrailing299        default: .center300        }301    }302}303304/// The box model every node shares: size, padding, background, border, effects, gestures, drag and drop.305private struct NodeBox: ViewModifier {306    let node: JSONValue307    let context: CustomContext308309    private func n(_ key: String) -> CGFloat? { node[key]?.doubleValue.map { CGFloat($0) } }310    private func limit(_ key: String) -> CGFloat? { node[key]?.stringValue == "infinity" ? .infinity : n(key) }311312    func body(content: Content) -> some View {313        let radius = n("cornerRadius") ?? 0314        let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)315        let grow = node["grow"]?.boolValue == true316        content317            .frame(width: n("width"), height: n("height"))318            .frame(minWidth: n("minWidth"), maxWidth: grow ? .infinity : limit("maxWidth"), minHeight: n("minHeight"), maxHeight: grow ? .infinity : limit("maxHeight"), alignment: frameAlignment)319            .padding(.horizontal, n("paddingH") ?? n("padding") ?? 0)320            .padding(.vertical, n("paddingV") ?? n("padding") ?? 0)321            .background { if let fill = context.fill(node["background"]) { shape.fill(fill) } }322            .clipShape(radius > 0 && node["clip"]?.boolValue != false ? AnyShape(shape) : AnyShape(Rectangle().inset(by: -10_000)))323            .overlay { if let c = context.color(node["borderColor"]) { shape.strokeBorder(c, lineWidth: n("borderWidth") ?? 1) } }324            .shadow(color: .black.opacity(n("shadow") == nil ? 0 : 0.18), radius: n("shadow") ?? 0, y: (n("shadow") ?? 0) / 3)325            .opacity(Double(n("opacity") ?? 1))326            .scaleEffect(n("scale") ?? 1)327            .rotationEffect(.degrees(Double(n("rotation") ?? 0)))328            .offset(x: n("offsetX") ?? 0, y: n("offsetY") ?? 0)329            .modifier(NodeGestures(node: node, context: context))330            .help(node["tooltip"]?.stringValue ?? "")331            .modifier(NodeAccessibility(label: node["label"]?.stringValue, isButton: node["onTap"] != nil && node["type"]?.stringValue != "button"))332    }333334    private var frameAlignment: Alignment {335        switch node["frameAlign"]?.stringValue {336        case "leading": .leading337        case "trailing": .trailing338        case "top": .top339        case "bottom": .bottom340        case "topLeading": .topLeading341        default: .center342        }343    }344}345346private struct NodeAccessibility: ViewModifier {347    let label: String?348    let isButton: Bool349    func body(content: Content) -> some View {350        if let label, !label.isEmpty { content.accessibilityElement(children: .combine).accessibilityLabel(label).accessibilityAddTraits(isButton ? .isButton : []) }351        else { content }352    }353}354355private struct NodeGestures: ViewModifier {356    let node: JSONValue357    let context: CustomContext358359    func body(content: Content) -> some View {360        let isControl = ["button", "input", "toggle", "slider", "picker", "canvas"].contains(node["type"]?.stringValue ?? "")361        content362            .modifier(TapHandling(active: node["onTap"] != nil && !isControl) { context.fire(node["onTap"]) })363            .modifier(DragSource(payload: context.interactive ? node["drag"] : nil))364            .modifier(DropTarget(active: node["onDrop"] != nil && context.interactive, radius: CGFloat(node["cornerRadius"]?.doubleValue ?? 6), accent: context.theme.accent) { payload in365                context.fire(node["onDrop"], ["payload": payload])366            })367    }368}369370private struct TapHandling: ViewModifier {371    let active: Bool372    let action: () -> Void373    func body(content: Content) -> some View {374        if active { content.contentShape(Rectangle()).onTapGesture(perform: action) } else { content }375    }376}377378private struct DragSource: ViewModifier {379    let payload: JSONValue?380    func body(content: Content) -> some View {381        if let payload { content.draggable(payload.canonicalString()) } else { content }382    }383}384385private struct DropTarget: ViewModifier {386    let active: Bool387    let radius: CGFloat388    let accent: Color389    let receive: (JSONValue) -> Void390    @State private var targeted = false391392    func body(content: Content) -> some View {393        if active {394            content395                .dropDestination(for: String.self) { items, _ in396                    guard let first = items.first else { return false }397                    receive((try? JSONValue.parse(Data(first.utf8))) ?? .string(first))398                    return true399                } isTargeted: { targeted = $0 }400                .overlay { if targeted { RoundedRectangle(cornerRadius: radius).strokeBorder(accent, lineWidth: 2) } }401        } else { content }402    }403}404405/// Free drawing: `commands` are painted in order, in points from the top-left corner.406/// Ops: rect, circle, ellipse, line, polyline, polygon, path (SVG data), text, symbol.407private struct CustomCanvas: View {408    static let maxCommands = 5000409    let node: JSONValue410    let context: CustomContext411412    var body: some View {413        let commands = Array((node["commands"]?.arrayValue ?? []).prefix(Self.maxCommands))414        Canvas { g, _ in415            for c in commands { draw(c, in: &g) }416        }417        .contentShape(Rectangle())418        .gesture(SpatialTapGesture().onEnded { context.fire(node["onTap"], ["x": .double(Double($0.location.x)), "y": .double(Double($0.location.y))]) }, including: node["onTap"] == nil ? .none : .all)419        .gesture(DragGesture(minimumDistance: 2)420            .onChanged { context.fire(node["onDrag"], dragEvent($0, "changed")) }421            .onEnded { context.fire(node["onDrag"], dragEvent($0, "ended")) }, including: node["onDrag"] == nil ? .none : .all)422        .accessibilityLabel(node["label"]?.stringValue ?? "Drawing")423    }424425    private func dragEvent(_ v: DragGesture.Value, _ phase: String) -> [String: JSONValue] {426        ["x": .double(Double(v.location.x)), "y": .double(Double(v.location.y)), "startX": .double(Double(v.startLocation.x)), "startY": .double(Double(v.startLocation.y)), "phase": .string(phase)]427    }428429    private func draw(_ c: JSONValue, in g: inout GraphicsContext) {430        func n(_ key: String, _ d: CGFloat = 0) -> CGFloat { c[key]?.doubleValue.map { CGFloat($0) } ?? d }431        var path = Path()432        switch c["op"]?.stringValue ?? "" {433        case "rect":434            path.addRoundedRect(in: CGRect(x: n("x"), y: n("y"), width: n("width"), height: n("height")), cornerSize: CGSize(width: n("radius"), height: n("radius")))435        case "circle":436            path.addEllipse(in: CGRect(x: n("x") - n("r"), y: n("y") - n("r"), width: 2 * n("r"), height: 2 * n("r")))437        case "ellipse":438            path.addEllipse(in: CGRect(x: n("x"), y: n("y"), width: n("width"), height: n("height")))439        case "line":440            path.move(to: CGPoint(x: n("x1"), y: n("y1"))); path.addLine(to: CGPoint(x: n("x2"), y: n("y2")))441        case "polyline", "polygon":442            let points = (c["points"]?.arrayValue ?? []).prefix(5000).compactMap { p -> CGPoint? in443                guard let x = p[0]?.doubleValue ?? p["x"]?.doubleValue, let y = p[1]?.doubleValue ?? p["y"]?.doubleValue else { return nil }444                return CGPoint(x: x, y: y)445            }446            guard points.count > 1 else { return }447            path.addLines(Array(points))448            if c["op"]?.stringValue == "polygon" { path.closeSubpath() }449        case "path":450            guard let cg = try? SVGPath.parse(c["d"]?.stringValue ?? "") else { return }451            path = Path(cg).offsetBy(dx: n("x"), dy: n("y"))452        case "text":453            let design: Font.Design? = switch c["font"]?.stringValue { case "rounded": .rounded; case "serif": .serif; case "monospaced": .monospaced; default: nil }454            let t = Text(c["text"]?.displayString ?? "").font(.system(size: n("size", 13), weight: c["weight"]?.stringValue == "bold" ? .bold : .regular, design: design))455                .foregroundStyle(context.color(c["color"] ?? c["fill"]) ?? .primary)456            let anchor: UnitPoint = switch c["anchor"]?.stringValue { case "leading": .leading; case "trailing": .trailing; case "topLeading": .topLeading; default: .center }457            g.draw(t, at: CGPoint(x: n("x"), y: n("y")), anchor: anchor)458            return459        case "symbol":460            let image = Text(Image(systemName: SymbolName.safe(c["name"]?.stringValue))).font(.system(size: n("size", 17))).foregroundStyle(context.color(c["color"] ?? c["fill"]) ?? .primary)461            g.draw(image, at: CGPoint(x: n("x"), y: n("y")), anchor: .center)462            return463        default:464            return465        }466        var layer = g467        layer.opacity = Double(n("opacity", 1))468        if let fill = context.fill(c["fill"]) { layer.fill(path, with: .style(fill), style: FillStyle(eoFill: c["evenOdd"]?.boolValue == true)) }469        if let stroke = context.color(c["stroke"]) {470            layer.stroke(path, with: .color(stroke), style: StrokeStyle(lineWidth: n("lineWidth", 1), lineCap: .round, lineJoin: .round, dash: (c["dash"]?.arrayValue ?? []).compactMap { $0.doubleValue.map { CGFloat($0) } }))471        }472    }473}474475/// `prism.timer`: fires `tick` at an interval while it is running. It draws nothing.476struct TimerComponent: View {477    @Environment(AppRuntime.self) private var runtime478    @Environment(\.prismDesign) private var design479    let o: PrismObject480481    var body: some View {482        let interval = max(o.props["interval"]?.doubleValue ?? 1, 0.05)483        let running = runtime.bool(o.props["running"], default: true) && design == nil484        Group {485            if design != nil { Label("Timer · every \(interval.formatted()) s", systemImage: "timer").font(.caption).foregroundStyle(.secondary) }486            else { Color.clear.frame(width: 0, height: 0).accessibilityHidden(true) }487        }488        .task(id: "\(interval)-\(running)") {489            guard running else { return }490            while !Task.isCancelled {491                try? await Task.sleep(for: .seconds(interval))492                if Task.isCancelled { break }493                runtime.fire("tick", on: o.id)494            }495        }496    }497}498
Files main
Menu

Theme