SPB Git

Repository Public License

FormComponents.swift 9.6 KB 232 lines swift

1import PrismCore2import PrismLogicRuntime3import PrismObjectModel4import SwiftUI56extension AppRuntime {7    /// A SwiftUI binding onto the state key a prop is bound to; writes also fire the object's `change` event.8    func stateBinding(_ o: PrismObject, _ prop: String = "value", fire event: String? = "change") -> Binding<JSONValue> {9        Binding(10            get: { self.resolve(o.props[prop]) },11            set: { new in12                if let path = self.bindingPath(o.props[prop]) { self.setState(path, new) }13                if let event { self.fire(event, on: o.id, value: new) }14            }15        )16    }17}1819/// A caption above a control, used by every form field so labels line up and are read by VoiceOver.20struct Labeled<Content: View>: View {21    let label: String22    @ViewBuilder var content: Content2324    var body: some View {25        if label.isEmpty { content } else {26            VStack(alignment: .leading, spacing: 4) {27                Text(label).font(.callout).foregroundStyle(.secondary).accessibilityHidden(true)28                content.accessibilityLabel(label)29            }30        }31    }32}3334struct TextFieldComponent: View {35    @Environment(AppRuntime.self) private var runtime36    let o: PrismObject3738    var body: some View {39        let value = runtime.stateBinding(o)40        Labeled(label: runtime.string(o.props["label"])) {41            TextField(runtime.string(o.props["placeholder"]), text: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) }))42                .textFieldStyle(.roundedBorder)43                .frame(minWidth: 120)44                .onSubmit { runtime.fire("submit", on: o.id, value: value.wrappedValue) }45        }46    }47}4849struct NumberFieldComponent: View {50    @Environment(AppRuntime.self) private var runtime51    let o: PrismObject52    let currency: Bool5354    var body: some View {55        let value = runtime.stateBinding(o)56        let minimum = o.props["min"]?.doubleValue, maximum = o.props["max"]?.doubleValue57        let number = Binding<Double>(58            get: { value.wrappedValue.numericValue ?? 0 },59            set: { new in60                var v = new.isFinite ? new : 061                if let minimum { v = max(v, minimum) }62                if let maximum { v = min(v, maximum) }63                value.wrappedValue = v.rounded() == v && abs(v) < 9e15 ? .int(Int(v)) : .double(v)64            }65        )66        Labeled(label: runtime.string(o.props["label"])) {67            HStack(spacing: 4) {68                if currency {69                    TextField("", value: number, format: .currency(code: o.props["currencyCode"]?.stringValue ?? runtime.currencyCode).locale(runtime.locale))70                        .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(minWidth: 110)71                } else {72                    TextField("", value: number, format: .number.locale(runtime.locale)).textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(minWidth: 80)73                    Stepper("", value: number, step: o.props["step"]?.doubleValue ?? 1).labelsHidden()74                }75            }76        }77    }78}7980enum LocalDate {81    /// ISO `YYYY-MM-DD` to a Date at local midnight, so a DatePicker shows the same calendar day everywhere.82    static func date(_ iso: String) -> Date? {83        let parts = iso.prefix(10).split(separator: "-").compactMap { Int($0) }84        guard parts.count == 3, DateCoding.date(from: iso) != nil else { return nil }85        return Calendar.current.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2]))86    }8788    static func iso(_ date: Date) -> String { DateCoding.string(from: date, timeZone: .current) }89}9091struct DatePickerComponent: View {92    @Environment(AppRuntime.self) private var runtime93    let o: PrismObject9495    var body: some View {96        let value = runtime.stateBinding(o)97        Labeled(label: runtime.string(o.props["label"])) {98            DatePicker("", selection: Binding(99                get: { LocalDate.date(value.wrappedValue.displayString) ?? Date() },100                set: { value.wrappedValue = .string(LocalDate.iso($0)) }101            ), displayedComponents: .date)102            .labelsHidden()103        }104    }105}106107struct DropdownComponent: View {108    @Environment(AppRuntime.self) private var runtime109    let o: PrismObject110111    private var options: [String] {112        var out: [String] = []113        if let all = o.props["includeAll"]?.stringValue { out.append(all) }114        out += (runtime.resolve(o.props["options"]).arrayValue ?? []).map(\.displayString)115        if let from = o.props["optionsFrom"], let table = from["table"]?.stringValue, let column = from["column"]?.stringValue {116            out += runtime.distinctValues(table: table, column: column).map(\.displayString)117        }118        var seen = Set<String>()119        return out.filter { seen.insert($0).inserted }120    }121122    var body: some View {123        let value = runtime.stateBinding(o)124        let current = value.wrappedValue.displayString125        let all = options.contains(current) || current.isEmpty ? options : options + [current]126        Labeled(label: runtime.string(o.props["label"])) {127            Picker(runtime.string(o.props["label"]), selection: Binding(get: { current }, set: { value.wrappedValue = .string($0) })) {128                if current.isEmpty && !all.contains("") { Text("Choose…").tag("") }129                ForEach(all, id: \.self) { Text($0).tag($0) }130            }131            .labelsHidden()132            .fixedSize()133        }134    }135}136137struct SearchComponent: View {138    @Environment(AppRuntime.self) private var runtime139    let o: PrismObject140141    var body: some View {142        let value = runtime.stateBinding(o)143        let placeholder = o.props["placeholder"].map { runtime.string($0) } ?? "Search"144        HStack(spacing: 6) {145            Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true)146            TextField(placeholder, text: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) }))147                .textFieldStyle(.plain)148                .onSubmit { runtime.fire("submit", on: o.id, value: value.wrappedValue) }149                .accessibilityLabel(placeholder)150            if !value.wrappedValue.displayString.isEmpty {151                Button { value.wrappedValue = .string("") } label: { Image(systemName: "xmark.circle.fill") }152                    .buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Clear search")153            }154        }155        .padding(.horizontal, 8).padding(.vertical, 5)156        .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7))157        .frame(minWidth: 160, maxWidth: 320)158    }159}160161struct SegmentedComponent: View {162    @Environment(AppRuntime.self) private var runtime163    let o: PrismObject164165    var body: some View {166        let value = runtime.stateBinding(o)167        let options = (runtime.resolve(o.props["options"]).arrayValue ?? []).map(\.displayString)168        let label = runtime.string(o.props["label"])169        Picker(label.isEmpty ? "Options" : label, selection: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) })) {170            ForEach(options, id: \.self) { Text($0).tag($0) }171        }172        .pickerStyle(.segmented)173        .labelsHidden()174        .fixedSize()175    }176}177178struct FormSectionComponent: View {179    @Environment(AppRuntime.self) private var runtime180    @Environment(\.prismTheme) private var theme181    let o: PrismObject182183    var body: some View {184        let title = runtime.string(o.props["title"])185        VStack(alignment: .leading, spacing: theme.spacing) {186            if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }187            ChildrenView(ids: o.children)188        }189        .frame(maxWidth: .infinity, alignment: .leading)190    }191}192193struct ValidationSummaryComponent: View {194    @Environment(AppRuntime.self) private var runtime195    let o: PrismObject196197    var body: some View {198        let failing = (o.props["rules"]?.arrayValue ?? []).filter { runtime.resolve($0["when"]).isTruthy }.map { runtime.string($0["message"]) }199        if !failing.isEmpty {200            VStack(alignment: .leading, spacing: 4) {201                let title = runtime.string(o.props["title"])202                if !title.isEmpty { Text(title).font(.callout.weight(.semibold)) }203                ForEach(failing, id: \.self) { Label($0, systemImage: "exclamationmark.circle").font(.callout) }204            }205            .foregroundStyle(.red)206            .accessibilityElement(children: .combine)207        }208    }209}210211struct FilePickerComponent: View {212    @Environment(AppRuntime.self) private var runtime213    let o: PrismObject214215    var body: some View {216        let value = runtime.stateBinding(o, fire: nil)217        let name = value.wrappedValue.displayString218        Labeled(label: runtime.string(o.props["label"])) {219            HStack {220                Button(o.props["buttonTitle"].map { runtime.string($0) } ?? "Choose File…") {221                    let extensions = (o.props["allowedExtensions"]?.arrayValue ?? []).compactMap(\.stringValue)222                    guard let url = runtime.dialogs?.chooseFileToOpen(allowedExtensions: extensions) else { return }223                    value.wrappedValue = .string(url.lastPathComponent)224                    runtime.fire("select", on: o.id, value: .string(url.lastPathComponent))225                }226                .disabled(runtime.dialogs == nil || !runtime.has("files.import.userSelected"))227                Text(name.isEmpty ? "No file chosen" : name).foregroundStyle(name.isEmpty ? .secondary : .primary).lineLimit(1).truncationMode(.middle)228            }229        }230    }231}232
Files main
Menu

Theme