SPB Git

Repository Public License

FoundationComponents.swift 15.8 KB 402 lines swift

1import PrismCore2import PrismObjectModel3import SwiftUI45struct TextComponent: View {6    @Environment(AppRuntime.self) private var runtime7    @Environment(\.prismTheme) private var theme8    let o: PrismObject910    var body: some View {11        let align = o.props["align"]?.stringValue ?? "leading"12        Text(runtime.string(o.props["text"]))13            .font(font(o.props["style"]?.stringValue ?? "body"))14            .foregroundStyle(theme.color(runtime.string(o.props["tone"])))15            .multilineTextAlignment(align == "center" ? .center : align == "trailing" ? .trailing : .leading)16            .frame(maxWidth: align == "leading" ? nil : .infinity, alignment: align == "center" ? .center : .trailing)17            .fixedSize(horizontal: false, vertical: true)18            .textSelection(.enabled)19    }2021    private func font(_ style: String) -> Font {22        switch style {23        case "caption": .caption24        case "footnote": .footnote25        case "callout": .callout26        case "headline": .headline27        case "title": .title228        case "largeTitle": .largeTitle29        case "monospaced": .body.monospaced()30        default: .body31        }32    }33}3435struct HeadingComponent: View {36    @Environment(AppRuntime.self) private var runtime37    @Environment(\.prismTheme) private var theme38    let o: PrismObject3940    var body: some View {41        let level = o.props["level"]?.intValue ?? 242        Text(runtime.string(o.props["text"]))43            .font(theme.headingFont(level <= 1 ? .largeTitle : level == 2 ? .title2 : .headline))44            .fontDesign(theme.headingDesign ?? theme.fontDesign)45            .accessibilityAddTraits(.isHeader)46    }47}4849struct IconComponent: View {50    @Environment(AppRuntime.self) private var runtime51    @Environment(\.prismTheme) private var theme52    let o: PrismObject5354    var body: some View {55        Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"])))56            .font(.system(size: CGFloat(o.props["size"]?.doubleValue ?? 18)))57            .foregroundStyle(theme.color(runtime.string(o.props["tone"])))58    }59}6061struct ButtonComponent: View {62    @Environment(AppRuntime.self) private var runtime63    let o: PrismObject6465    var body: some View {66        let title = runtime.string(o.props["title"])67        let icon = o.props["icon"].map { SymbolName.safe(runtime.string($0)) }68        let connected = !(o.events["click"] ?? []).isEmpty69        let button = Button(role: o.props["style"]?.stringValue == "destructive" ? .destructive : nil) {70            runtime.fire("click", on: o.id)71        } label: {72            if let icon, !title.isEmpty { Label(title, systemImage: icon) }73            else if let icon { Image(systemName: icon) }74            else { Text(title) }75        }76        .disabled(!connected || runtime.bool(o.props["disabled"], default: false))77        .help(connected ? "" : "No action is connected to this button yet.")78        switch o.props["style"]?.stringValue {79        case "primary": button.buttonStyle(.borderedProminent)80        case "plain": button.buttonStyle(.borderless)81        default: button.buttonStyle(.bordered)82        }83    }84}8586struct BadgeView: View {87    @Environment(\.prismTheme) private var theme88    let text: String89    let tone: String9091    var body: some View {92        Text(text)93            .font(.caption.weight(.medium))94            .padding(.horizontal, 8).padding(.vertical, 2)95            .foregroundStyle(theme.tint(tone))96            .background(theme.tint(tone).opacity(0.14), in: Capsule())97            .lineLimit(1)98    }99}100101struct CardComponent: View {102    @Environment(AppRuntime.self) private var runtime103    @Environment(\.prismTheme) private var theme104    let o: PrismObject105106    var body: some View {107        let title = runtime.string(o.props["title"])108        VStack(alignment: .leading, spacing: theme.spacing) {109            if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }110            ChildrenView(ids: o.children)111        }112        .padding(16)113        .frame(maxWidth: .infinity, alignment: .leading)114        .prismSurface()115    }116}117118struct ProgressComponent: View {119    @Environment(AppRuntime.self) private var runtime120    @Environment(\.prismTheme) private var theme121    let o: PrismObject122123    var body: some View {124        let raw = runtime.number(o.props["value"]) ?? 0125        let value = min(max(raw.isFinite ? raw : 0, 0), 1)126        let label = runtime.string(o.props["label"])127        let tone = runtime.string(o.props["tone"])128        VStack(alignment: .leading, spacing: 4) {129            if !label.isEmpty || o.props["showPercent"]?.boolValue != false {130                HStack {131                    Text(label)132                    Spacer()133                    if o.props["showPercent"]?.boolValue != false { Text(raw.formatted(.percent.precision(.fractionLength(0)))).monospacedDigit().foregroundStyle(.secondary) }134                }135                .font(.callout)136            }137            ProgressView(value: value).tint(tone.isEmpty || tone == "neutral" ? (raw > 1 ? .red : theme.accent) : theme.color(tone))138        }139        .accessibilityElement(children: .ignore)140        .accessibilityLabel(label.isEmpty ? "Progress" : label)141        .accessibilityValue(raw.formatted(.percent.precision(.fractionLength(0))))142    }143}144145struct ToggleComponent: View {146    @Environment(AppRuntime.self) private var runtime147    let o: PrismObject148149    var body: some View {150        Toggle(runtime.string(o.props["label"]), isOn: Binding(151            get: { runtime.resolve(o.props["value"]).isTruthy },152            set: { new in153                if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .bool(new)) }154                runtime.fire("change", on: o.id, value: .bool(new))155            }156        ))157        .toggleStyle(.switch)158    }159}160161struct StackComponent: View {162    @Environment(\.prismTheme) private var theme163    let o: PrismObject164165    var body: some View {166        let spacing = CGFloat(o.props["spacing"]?.doubleValue ?? Double(theme.spacing))167        let align = o.props["align"]?.stringValue ?? "leading"168        if o.props["direction"]?.stringValue == "horizontal" {169            HStack(alignment: align == "leading" ? .top : align == "trailing" ? .bottom : .center, spacing: spacing) { ChildrenView(ids: o.children) }170        } else {171            VStack(alignment: align == "center" ? .center : align == "trailing" ? .trailing : .leading, spacing: spacing) { ChildrenView(ids: o.children) }172                .frame(maxWidth: align == "stretch" ? .infinity : nil, alignment: .leading)173        }174    }175}176177struct GridComponent: View {178    @Environment(\.prismTheme) private var theme179    let o: PrismObject180181    var body: some View {182        let count = min(max(o.props["columns"]?.intValue ?? 2, 1), 12)183        let spacing = CGFloat(o.props["spacing"]?.doubleValue ?? Double(theme.spacing))184        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: spacing, alignment: .top), count: count), alignment: .leading, spacing: spacing) {185            ChildrenView(ids: o.children)186        }187    }188}189190struct ScrollComponent: View {191    @Environment(\.prismTheme) private var theme192    let o: PrismObject193194    var body: some View {195        let horizontal = o.props["axis"]?.stringValue == "horizontal"196        ScrollView(horizontal ? .horizontal : .vertical) {197            if horizontal { HStack(alignment: .top, spacing: theme.spacing) { ChildrenView(ids: o.children) } }198            else { VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }.frame(maxWidth: .infinity, alignment: .leading) }199        }200    }201}202203struct SplitComponent: View {204    @Environment(AppRuntime.self) private var runtime205    let o: PrismObject206207    var body: some View {208        let ids = Array(o.children.prefix(2))209        let vertical = o.props["direction"]?.stringValue == "vertical"210        if ids.count == 2 {211            ResizableSplit(vertical: vertical, initial: initial(ids, vertical: vertical)) { pane(ids[0]) } second: { pane(ids[1]) }212        } else if let only = ids.first {213            pane(only)214        }215    }216217    private func pane(_ id: String) -> some View {218        NodeView(id: id).padding(8).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)219    }220221    /// A child with a fixed size along the split axis keeps that size; otherwise the panes start equal.222    private func initial(_ ids: [String], vertical: Bool) -> SplitInitial {223        let key = vertical ? "height" : "width"224        func fixed(_ id: String) -> CGFloat? { runtime.blueprint.object(id)?.props[key]?.doubleValue.map { CGFloat($0) + 16 } }225        if let second = fixed(ids[1]) { return .second(second) }226        if let first = fixed(ids[0]) { return .first(first) }227        return .fraction(0.5)228    }229}230231/// Shared selection logic for tab bars and sidebars: bound to state when `selection` is a binding, local otherwise.232@MainActor233struct ChildSelection {234    let runtime: AppRuntime235    let o: PrismObject236    let local: Binding<String?>237238    var current: String {239        let bound = runtime.resolve(o.props["selection"]).stringValue240        let candidate = bound ?? local.wrappedValue241        return candidate.flatMap { o.children.contains($0) ? $0 : nil } ?? o.children.first ?? ""242    }243244    func select(_ id: String) {245        local.wrappedValue = id246        if let path = runtime.bindingPath(o.props["selection"]) { runtime.setState(path, .string(id)) }247        runtime.fire("change", on: o.id, value: .string(id))248    }249250    func title(_ id: String) -> String {251        let child = runtime.blueprint.object(id)252        return child.map { $0.name.isEmpty ? $0.id : $0.name } ?? id253    }254}255256struct TabsComponent: View {257    @Environment(AppRuntime.self) private var runtime258    @Environment(\.prismTheme) private var theme259    let o: PrismObject260    @State private var local: String?261262    var body: some View {263        let selection = ChildSelection(runtime: runtime, o: o, local: $local)264        VStack(alignment: .leading, spacing: theme.spacing) {265            Picker("Tabs", selection: Binding(get: { selection.current }, set: { selection.select($0) })) {266                ForEach(o.children, id: \.self) { Text(selection.title($0)).tag($0) }267            }268            .pickerStyle(.segmented)269            .labelsHidden()270            .fixedSize()271            if !selection.current.isEmpty {272                NodeView(id: selection.current).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)273            }274        }275    }276}277278struct ToolbarComponent: View {279    @Environment(\.prismTheme) private var theme280    let o: PrismObject281282    var body: some View {283        HStack(alignment: .bottom, spacing: theme.spacing) { ChildrenView(ids: o.children) }284            .fixedSize(horizontal: false, vertical: true)285            .padding(.horizontal, 12).padding(.vertical, 8)286            .frame(maxWidth: .infinity, alignment: .leading)287            .background(.bar, in: RoundedRectangle(cornerRadius: theme.radius))288            .overlay(RoundedRectangle(cornerRadius: theme.radius).strokeBorder(.separator.opacity(0.6)))289    }290}291292struct ModalComponent: View {293    @Environment(AppRuntime.self) private var runtime294    @Environment(\.prismTheme) private var theme295    @Environment(\.prismDesign) private var design296    let o: PrismObject297298    var body: some View {299        let presented = Binding(300            get: { runtime.resolve(o.props["presented"]).isTruthy },301            set: { new in if let path = runtime.bindingPath(o.props["presented"]) { runtime.setState(path, .bool(new)) } }302        )303        if design != nil {304            // In Design mode the sheet is laid out inline so its content can be selected.305            GroupBox("Sheet: \(runtime.string(o.props["title"]))") { sheetBody(presented) }306        } else {307            Color.clear.frame(width: 0, height: 0).accessibilityHidden(true)308                .sheet(isPresented: presented) {309                    sheetBody(presented)310                        .padding(20)311                        .frame(minWidth: CGFloat(o.props["minWidth"]?.doubleValue ?? 420))312                        .environment(runtime)313                        .environment(\.prismTheme, theme)314                }315        }316    }317318    private func sheetBody(_ presented: Binding<Bool>) -> some View {319        VStack(alignment: .leading, spacing: theme.spacing) {320            HStack {321                Text(runtime.string(o.props["title"])).font(.title3.bold()).accessibilityAddTraits(.isHeader)322                Spacer()323                Button("Close") { presented.wrappedValue = false }.keyboardShortcut(.cancelAction)324            }325            ChildrenView(ids: o.children)326        }327    }328}329330struct AlertComponent: View {331    @Environment(AppRuntime.self) private var runtime332    @Environment(\.prismTheme) private var theme333    let o: PrismObject334335    var body: some View {336        let tone = o.props["tone"].map { runtime.string($0) } ?? "warning"337        let message = runtime.string(o.props["message"])338        HStack(alignment: .firstTextBaseline, spacing: 10) {339            Image(systemName: tone == "danger" ? "exclamationmark.octagon.fill" : tone == "success" ? "checkmark.circle.fill" : tone == "info" ? "info.circle.fill" : "exclamationmark.triangle.fill")340                .foregroundStyle(theme.tint(tone))341                .accessibilityHidden(true)342            VStack(alignment: .leading, spacing: 2) {343                Text(runtime.string(o.props["title"])).font(.headline)344                if !message.isEmpty { Text(message).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }345            }346            Spacer(minLength: 0)347        }348        .padding(12)349        .background(theme.tint(tone).opacity(0.12), in: RoundedRectangle(cornerRadius: theme.radius))350        .overlay(RoundedRectangle(cornerRadius: theme.radius).strokeBorder(theme.tint(tone).opacity(0.4)))351        .accessibilityElement(children: .combine)352    }353}354355struct NotificationComponent: View {356    @Environment(AppRuntime.self) private var runtime357    @Environment(\.prismTheme) private var theme358    let o: PrismObject359360    var body: some View {361        VStack(alignment: .leading, spacing: 6) {362            if runtime.notices.isEmpty {363                Text(o.props["emptyText"].map { runtime.string($0) } ?? "No messages.").foregroundStyle(.secondary).font(.callout)364            }365            ForEach(runtime.notices.reversed()) { notice in366                HStack(alignment: .firstTextBaseline) {367                    Circle().fill(theme.tint(notice.tone)).frame(width: 7, height: 7).accessibilityHidden(true)368                    Text(notice.message).font(.callout)369                    Spacer()370                    Text(notice.date, style: .time).font(.caption).foregroundStyle(.secondary)371                    Button { runtime.dismissNotice(notice.id) } label: { Image(systemName: "xmark") }372                        .buttonStyle(.borderless).accessibilityLabel("Dismiss")373                }374            }375        }376        .frame(maxWidth: .infinity, alignment: .leading)377    }378}379380struct MenuComponent: View {381    @Environment(AppRuntime.self) private var runtime382    let o: PrismObject383384    var body: some View {385        let items = o.props["items"]?.arrayValue ?? []386        let title = runtime.string(o.props["title"])387        Menu {388            ForEach(Array(items.enumerated()), id: \.offset) { _, item in389                let actions = item["actions"]?.arrayValue ?? []390                Button { runtime.run(actions) } label: {391                    if let icon = item["icon"]?.stringValue { Label(item["title"]?.stringValue ?? "", systemImage: SymbolName.safe(icon)) }392                    else { Text(item["title"]?.stringValue ?? "") }393                }394                .disabled(actions.isEmpty)395            }396        } label: {397            if let icon = o.props["icon"]?.stringValue { Label(title.isEmpty ? "Menu" : title, systemImage: SymbolName.safe(icon)) } else { Text(title.isEmpty ? "Menu" : title) }398        }399        .fixedSize()400    }401}402
Files main
Menu

Theme