SPB Git

Repository Public License

Components+FamilyBInputs.swift 30.5 KB 660 lines swift

1import AppKit2import PrismCore3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67// Family B, part 1: value inputs. Each writes its value to state through `$bind` and fires `change`.89struct FBSliderComponent: View {10    @Environment(AppRuntime.self) private var runtime11    let o: PrismObject1213    var body: some View {14        let bounds = FBBounds(o.props)15        let value = runtime.stateBinding(o)16        let current = bounds.clamp(value.wrappedValue.numericValue ?? bounds.lo)17        let label = runtime.fbText(o, "label")18        Labeled(label: label) {19            HStack(spacing: 10) {20                Slider(value: Binding(get: { current }, set: { new in21                    let snapped = bounds.snap(new)22                    if snapped != current { value.wrappedValue = .fbNumber(snapped) }23                }), in: bounds.lo...bounds.hi)24                .frame(minWidth: 140, maxWidth: 360)25                .accessibilityLabel(label.isEmpty ? "Slider" : label)26                if o.props["showValue"]?.boolValue != false {27                    Text(JSONValue.fbNumber(current).displayString).monospacedDigit().foregroundStyle(.secondary).frame(minWidth: 34, alignment: .trailing)28                        .accessibilityHidden(true)29                }30            }31        }32    }33}3435struct FBStepperComponent: View {36    @Environment(AppRuntime.self) private var runtime37    let o: PrismObject3839    var body: some View {40        let bounds = FBBounds(lo: o.props["min"]?.doubleValue ?? -1_000_000, hi: o.props["max"]?.doubleValue ?? 1_000_000, step: o.props["step"]?.doubleValue ?? 1)41        let value = runtime.stateBinding(o)42        let current = bounds.clamp(value.wrappedValue.numericValue ?? 0)43        let label = runtime.fbText(o, "label")44        Labeled(label: label) {45            HStack(spacing: 8) {46                Text(JSONValue.fbNumber(current).displayString).monospacedDigit().frame(minWidth: 40, alignment: .trailing)47                    .modifier(FBFieldFrame())48                Stepper(label.isEmpty ? "Value" : label, value: Binding(get: { current }, set: { value.wrappedValue = .fbNumber(bounds.clamp(($0 * 1e9).rounded() / 1e9)) }),49                        in: bounds.lo...bounds.hi, step: bounds.step)50                    .labelsHidden()51            }52        }53    }54}5556struct FBRatingInputComponent: View {57    @Environment(AppRuntime.self) private var runtime58    @Environment(\.prismTheme) private var theme59    let o: PrismObject6061    var body: some View {62        let count = min(max(o.props["max"]?.intValue ?? 5, 1), 10)63        let value = runtime.stateBinding(o)64        let current = min(max(Int(value.wrappedValue.numericValue ?? 0), 0), count)65        let icon = SymbolName.safe(o.props["icon"]?.stringValue, fallback: "star")66        let filled = SymbolName.safe(icon + ".fill", fallback: icon)67        let label = runtime.fbText(o, "label")68        Labeled(label: label) {69            HStack(spacing: 3) {70                ForEach(1...count, id: \.self) { n in71                    // Clicking the current rating again clears it.72                    Button { value.wrappedValue = .int(n == current ? 0 : n) } label: {73                        Image(systemName: n <= current ? filled : icon).font(.title3)74                            .foregroundStyle(n <= current ? AnyShapeStyle(theme.color("warning")) : AnyShapeStyle(.tertiary))75                            .contentShape(Rectangle())76                    }77                    .buttonStyle(.plain)78                    .accessibilityLabel("\(n) of \(count)")79                    .accessibilityAddTraits(n == current ? .isSelected : [])80                }81            }82            .accessibilityElement(children: .contain)83            .accessibilityValue("\(current) of \(count)")84        }85    }86}8788struct FBColorPickerComponent: View {89    @Environment(AppRuntime.self) private var runtime90    let o: PrismObject9192    var body: some View {93        let value = runtime.stateBinding(o)94        let current = FBColor.normalized(value.wrappedValue.displayString) ?? "#007AFF"95        let presets = o.props["presets"].map { runtime.fbStrings($0).compactMap(FBColor.normalized) } ?? FBColor.presets96        let label = runtime.fbText(o, "label")97        Labeled(label: label) {98            HStack(spacing: 8) {99                ColorPicker(label.isEmpty ? "Color" : label, selection: Binding(100                    get: { Color(hex: current) ?? .accentColor },101                    set: { new in102                        guard let c = NSColor(new).usingColorSpace(.sRGB) else { return }103                        let hex = FBColor.hex(red: c.redComponent, green: c.greenComponent, blue: c.blueComponent)104                        if hex != current { value.wrappedValue = .string(hex) }105                    }106                ), supportsOpacity: false)107                .labelsHidden()108                ForEach(presets, id: \.self) { hex in109                    Button { value.wrappedValue = .string(hex) } label: {110                        Circle().fill(Color(hex: hex) ?? .gray).frame(width: 18, height: 18)111                            .overlay(Circle().strokeBorder(.separator))112                            .overlay(Circle().strokeBorder(Color.primary, lineWidth: hex == current ? 2 : 0).padding(-3))113                            .padding(3)114                    }115                    .buttonStyle(.plain)116                    .accessibilityLabel("Color \(hex)")117                    .accessibilityAddTraits(hex == current ? .isSelected : [])118                }119                Text(current).font(.callout.monospaced()).foregroundStyle(.secondary).textSelection(.enabled)120            }121        }122    }123}124125struct FBTimePickerComponent: View {126    @Environment(AppRuntime.self) private var runtime127    let o: PrismObject128129    var body: some View {130        let value = runtime.stateBinding(o)131        let label = runtime.fbText(o, "label")132        Labeled(label: label) {133            DatePicker(label.isEmpty ? "Time" : label, selection: Binding(134                get: {135                    let t = FBTime.parseHHmm(value.wrappedValue.displayString) ?? (9, 0)136                    return Calendar.current.date(bySettingHour: t.hour, minute: t.minute, second: 0, of: Date()) ?? Date()137                },138                set: { new in139                    let c = Calendar.current.dateComponents([.hour, .minute], from: new)140                    value.wrappedValue = .string(FBTime.hhmm(hour: c.hour ?? 0, minute: c.minute ?? 0))141                }142            ), displayedComponents: .hourAndMinute)143            .labelsHidden()144            .fixedSize()145        }146    }147}148149struct FBDateRangeComponent: View {150    @Environment(AppRuntime.self) private var runtime151    let o: PrismObject152153    private func write(start: String, end: String) {154        if let path = runtime.bindingPath(o.props["start"]) { runtime.setState(path, .string(start)) }155        if let path = runtime.bindingPath(o.props["end"]) { runtime.setState(path, .string(end)) }156        runtime.fire("change", on: o.id, value: ["start": .string(start), "end": .string(end)])157    }158159    var body: some View {160        let today = LocalDate.iso(Date())161        let start = FBDay.normalized(runtime.string(o.props["start"])) ?? today162        let end = FBDay.normalized(runtime.string(o.props["end"])) ?? start163        Labeled(label: runtime.fbText(o, "label")) {164            HStack(spacing: 6) {165                DatePicker("From", selection: Binding(166                    get: { LocalDate.date(start) ?? Date() },167                    set: { let s = LocalDate.iso($0); write(start: s, end: max(s, end)) }168                ), displayedComponents: .date).labelsHidden().accessibilityLabel("From")169                Image(systemName: "arrow.right").foregroundStyle(.secondary).accessibilityHidden(true)170                DatePicker("To", selection: Binding(171                    get: { LocalDate.date(end) ?? Date() },172                    set: { let e = LocalDate.iso($0); write(start: min(start, e), end: e) }173                ), displayedComponents: .date).labelsHidden().accessibilityLabel("To")174            }175            .fixedSize()176        }177    }178}179180struct FBMultiSelectComponent: View {181    @Environment(AppRuntime.self) private var runtime182    let o: PrismObject183184    var body: some View {185        let options = runtime.fbOptions(o)186        let selected = runtime.fbStrings(o.props["value"])187        let label = runtime.fbText(o, "label")188        let placeholder = runtime.fbText(o, "placeholder", "Choose…")189        Labeled(label: label) {190            Menu {191                ForEach(options, id: \.self) { option in192                    Toggle(option, isOn: Binding(193                        get: { selected.contains(option) },194                        set: { _ in runtime.fbSet(o, "value", .array(FBTags.toggling(option, in: selected, order: options).map(JSONValue.string))) }195                    ))196                }197                if !selected.isEmpty {198                    Divider()199                    Button("Clear selection") { runtime.fbSet(o, "value", .array([])) }200                }201            } label: {202                Text(selected.isEmpty ? placeholder : selected.count <= 3 ? selected.joined(separator: ", ") : "\(selected.count) selected").lineLimit(1)203            }204            .fixedSize()205            .accessibilityLabel(label.isEmpty ? "Options" : label)206            .accessibilityValue(selected.isEmpty ? "None" : selected.joined(separator: ", "))207        }208    }209}210211struct FBCheckboxComponent: View {212    @Environment(AppRuntime.self) private var runtime213    let o: PrismObject214215    var body: some View {216        let value = runtime.stateBinding(o)217        Toggle(runtime.fbText(o, "label"), isOn: Binding(get: { value.wrappedValue.isTruthy }, set: { value.wrappedValue = .bool($0) }))218            .toggleStyle(.checkbox)219    }220}221222struct FBCheckboxGroupComponent: View {223    @Environment(AppRuntime.self) private var runtime224    let o: PrismObject225226    var body: some View {227        let options = runtime.fbOptions(o)228        let selected = runtime.fbStrings(o.props["value"])229        let layout = o.props["direction"]?.stringValue == "horizontal" ? AnyLayout(HStackLayout(alignment: .center, spacing: 14)) : AnyLayout(VStackLayout(alignment: .leading, spacing: 6))230        Labeled(label: runtime.fbText(o, "label")) {231            layout {232                ForEach(options, id: \.self) { option in233                    Toggle(option, isOn: Binding(234                        get: { selected.contains(option) },235                        set: { _ in runtime.fbSet(o, "value", .array(FBTags.toggling(option, in: selected, order: options).map(JSONValue.string))) }236                    ))237                    .toggleStyle(.checkbox)238                }239            }240        }241    }242}243244struct FBRadioGroupComponent: View {245    @Environment(AppRuntime.self) private var runtime246    let o: PrismObject247248    var body: some View {249        let options = runtime.fbOptions(o)250        let value = runtime.stateBinding(o)251        let label = runtime.fbText(o, "label")252        let picker = Picker(label.isEmpty ? "Options" : label, selection: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) })) {253            ForEach(options, id: \.self) { Text($0).tag($0) }254        }255        .pickerStyle(.radioGroup)256        .labelsHidden()257        Labeled(label: label) {258            if o.props["direction"]?.stringValue == "horizontal" { picker.horizontalRadioGroupLayout().fixedSize() } else { picker.fixedSize() }259        }260    }261}262263struct FBTagsInputComponent: View {264    @Environment(AppRuntime.self) private var runtime265    let o: PrismObject266    @State private var draft = ""267268    private func add(_ tags: [String]) {269        guard let next = FBTags.adding(draft, to: tags) else { draft = ""; return }270        let added = next.last ?? ""271        draft = ""272        runtime.fbSet(o, "value", .array(next.map(JSONValue.string)))273        runtime.fire("add", on: o.id, value: .string(added))274    }275276    var body: some View {277        let tags = runtime.fbStrings(o.props["value"])278        let label = runtime.fbText(o, "label")279        Labeled(label: label) {280            VStack(alignment: .leading, spacing: 6) {281                if !tags.isEmpty {282                    FBFlowLayout(spacing: 6) {283                        ForEach(tags, id: \.self) { tag in284                            FBChip(title: tag, icon: "xmark") {285                                runtime.fbSet(o, "value", .array(tags.filter { $0 != tag }.map(JSONValue.string)))286                                runtime.fire("remove", on: o.id, value: .string(tag))287                            }288                            .accessibilityLabel("Remove \(tag)")289                        }290                    }291                }292                TextField(runtime.fbText(o, "placeholder", "Add a tag and press Return"), text: $draft)293                    .textFieldStyle(.roundedBorder)294                    .frame(minWidth: 160, maxWidth: 320)295                    .onSubmit { add(tags) }296                    .accessibilityLabel(label.isEmpty ? "New tag" : label)297            }298        }299    }300}301302struct FBTextAreaComponent: View {303    @Environment(AppRuntime.self) private var runtime304    let o: PrismObject305306    var body: some View {307        let value = runtime.stateBinding(o)308        let text = value.wrappedValue.displayString309        let lines = min(max(o.props["lines"]?.intValue ?? 4, 2), 40)310        let label = runtime.fbText(o, "label")311        Labeled(label: label) {312            TextEditor(text: Binding(get: { text }, set: { if $0 != text { value.wrappedValue = .string($0) } }))313                .font(.body)314                .scrollContentBackground(.hidden)315                .frame(minWidth: 180, maxWidth: .infinity, minHeight: CGFloat(lines) * 18, maxHeight: CGFloat(lines) * 18)316                .overlay(alignment: .topLeading) {317                    if text.isEmpty {318                        Text(runtime.fbText(o, "placeholder")).foregroundStyle(.tertiary).padding(.leading, 5).allowsHitTesting(false).accessibilityHidden(true)319                    }320                }321                .modifier(FBFieldFrame())322                .accessibilityLabel(label.isEmpty ? "Text" : label)323        }324    }325}326327struct FBSecureFieldComponent: View {328    @Environment(AppRuntime.self) private var runtime329    let o: PrismObject330331    var body: some View {332        let value = runtime.stateBinding(o)333        Labeled(label: runtime.fbText(o, "label")) {334            SecureField(runtime.fbText(o, "placeholder"), text: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) }))335                .textFieldStyle(.roundedBorder)336                .frame(minWidth: 140, maxWidth: 320)337                .onSubmit { runtime.fire("submit", on: o.id, value: value.wrappedValue) }338        }339    }340}341342struct FBComboBoxComponent: View {343    @Environment(AppRuntime.self) private var runtime344    let o: PrismObject345346    var body: some View {347        let options = runtime.fbOptions(o)348        let value = runtime.stateBinding(o)349        let label = runtime.fbText(o, "label")350        Labeled(label: label) {351            HStack(spacing: 4) {352                TextField(runtime.fbText(o, "placeholder"), text: Binding(get: { value.wrappedValue.displayString }, set: { value.wrappedValue = .string($0) }))353                    .textFieldStyle(.roundedBorder)354                    .frame(minWidth: 130, maxWidth: 280)355                    .accessibilityLabel(label.isEmpty ? "Value" : label)356                Menu {357                    ForEach(options, id: \.self) { option in358                        Button(option) { value.wrappedValue = .string(option) }359                    }360                } label: {361                    Image(systemName: "chevron.down")362                }363                .menuIndicator(.hidden)364                .fixedSize()365                .disabled(options.isEmpty)366                .accessibilityLabel("Choose from the list")367            }368        }369    }370}371372struct FBAutocompleteComponent: View {373    @Environment(AppRuntime.self) private var runtime374    let o: PrismObject375376    var body: some View {377        let value = runtime.stateBinding(o)378        let text = value.wrappedValue.displayString379        let suggestions = FBSuggest.filter(runtime.fbOptions(o), text: text, limit: o.props["maxSuggestions"]?.intValue ?? 6)380        let label = runtime.fbText(o, "label")381        Labeled(label: label) {382            VStack(alignment: .leading, spacing: 4) {383                TextField(runtime.fbText(o, "placeholder"), text: Binding(get: { text }, set: { value.wrappedValue = .string($0) }))384                    .textFieldStyle(.roundedBorder)385                    .onSubmit {386                        // Return accepts the first suggestion.387                        guard let first = suggestions.first else { return }388                        value.wrappedValue = .string(first)389                        runtime.fire("select", on: o.id, value: .string(first))390                    }391                    .accessibilityLabel(label.isEmpty ? "Value" : label)392                if !suggestions.isEmpty {393                    VStack(alignment: .leading, spacing: 0) {394                        ForEach(suggestions, id: \.self) { suggestion in395                            Button {396                                value.wrappedValue = .string(suggestion)397                                runtime.fire("select", on: o.id, value: .string(suggestion))398                            } label: {399                                Text(suggestion).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.vertical, 4).contentShape(Rectangle())400                            }401                            .buttonStyle(.plain)402                            .accessibilityLabel("Use \(suggestion)")403                        }404                    }405                    .padding(.vertical, 3)406                    .background(.background, in: RoundedRectangle(cornerRadius: 6))407                    .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(.separator))408                }409            }410            .frame(minWidth: 160, maxWidth: 320)411        }412    }413}414415struct FBPinInputComponent: View {416    @Environment(AppRuntime.self) private var runtime417    @Environment(\.prismTheme) private var theme418    let o: PrismObject419    @FocusState private var focused: Bool420421    var body: some View {422        let length = min(max(o.props["length"]?.intValue ?? 4, 1), 12)423        let value = runtime.stateBinding(o)424        let current = FBPin.sanitize(value.wrappedValue.displayString, length: length)425        let digits = Array(current)426        let masked = o.props["masked"]?.boolValue == true427        let label = runtime.fbText(o, "label")428        Labeled(label: label) {429            HStack(spacing: 6) {430                ForEach(0..<length, id: \.self) { i in431                    Text(i < digits.count ? (masked ? "•" : String(digits[i])) : " ")432                        .font(.title2.monospacedDigit().weight(.medium))433                        .frame(width: 34, height: 42)434                        .background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 7))435                        .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(focused && i == min(digits.count, length - 1) ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.separator), lineWidth: focused && i == min(digits.count, length - 1) ? 2 : 1))436                }437            }438            .accessibilityHidden(true)439            .overlay {440                // The real field sits invisibly over the boxes: it takes the typing, the paste and the VoiceOver focus.441                TextField("", text: Binding(get: { current }, set: { raw in442                    let next = FBPin.sanitize(raw, length: length)443                    guard next != current else { return }444                    value.wrappedValue = .string(next)445                    if FBPin.isComplete(next, length: length) { runtime.fire("complete", on: o.id, value: .string(next)) }446                }))447                .textFieldStyle(.plain)448                .focused($focused)449                .foregroundStyle(.clear)450                .tint(.clear)451                .accessibilityLabel(label.isEmpty ? "Code, \(length) digits" : label)452                .accessibilityValue(masked ? "\(digits.count) of \(length) digits entered" : current)453            }454            .contentShape(Rectangle())455            .onTapGesture { focused = true }456            .fixedSize()457        }458    }459}460461struct FBRangeSliderComponent: View {462    @Environment(AppRuntime.self) private var runtime463    @Environment(\.prismTheme) private var theme464    let o: PrismObject465    private let knob: CGFloat = 18466467    private func set(low: Double, high: Double) {468        if let path = runtime.bindingPath(o.props["low"]) { runtime.setState(path, .fbNumber(low)) }469        if let path = runtime.bindingPath(o.props["high"]) { runtime.setState(path, .fbNumber(high)) }470        runtime.fire("change", on: o.id, value: ["low": .fbNumber(low), "high": .fbNumber(high)])471    }472473    var body: some View {474        let bounds = FBBounds(o.props)475        let low = bounds.clamp(runtime.number(o.props["low"]) ?? bounds.lo)476        let high = max(bounds.clamp(runtime.number(o.props["high"]) ?? bounds.hi), low)477        let label = runtime.fbText(o, "label")478        Labeled(label: label) {479            HStack(spacing: 10) {480                // The reader only measures the fixed-height track it sits in; it never sizes its own container.481                GeometryReader { geo in482                    let span = max(geo.size.width - knob, 1)483                    let lowX = CGFloat(bounds.fraction(low)) * span, highX = CGFloat(bounds.fraction(high)) * span484                    ZStack(alignment: .leading) {485                        Capsule().fill(.quaternary).frame(height: 4).padding(.horizontal, knob / 2)486                        Capsule().fill(theme.accent).frame(width: max(highX - lowX, 0), height: 4).offset(x: lowX + knob / 2)487                        handle("Lowest value", value: low).offset(x: lowX)488                            .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .named("fbRange")).onChanged { g in489                                let v = min(bounds.value(fraction: Double((g.location.x - knob / 2) / span)), high)490                                if v != low { set(low: v, high: high) }491                            })492                            .accessibilityAdjustableAction { direction in493                                let v = min(bounds.snap(low + (direction == .increment ? bounds.step : -bounds.step)), high)494                                if v != low { set(low: v, high: high) }495                            }496                        handle("Highest value", value: high).offset(x: highX)497                            .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .named("fbRange")).onChanged { g in498                                let v = max(bounds.value(fraction: Double((g.location.x - knob / 2) / span)), low)499                                if v != high { set(low: low, high: v) }500                            })501                            .accessibilityAdjustableAction { direction in502                                let v = max(bounds.snap(high + (direction == .increment ? bounds.step : -bounds.step)), low)503                                if v != high { set(low: low, high: v) }504                            }505                    }506                    .frame(height: geo.size.height)507                    .coordinateSpace(.named("fbRange"))508                }509                .frame(height: 22)510                .frame(minWidth: 160, maxWidth: 360)511                Text("\(JSONValue.fbNumber(low).displayString) – \(JSONValue.fbNumber(high).displayString)").monospacedDigit().foregroundStyle(.secondary)512                    .frame(minWidth: 60, alignment: .trailing).accessibilityHidden(true)513            }514        }515    }516517    private func handle(_ name: String, value: Double) -> some View {518        Circle().fill(Color(nsColor: .controlColor)).frame(width: knob, height: knob)519            .overlay(Circle().strokeBorder(.separator))520            .shadow(color: .black.opacity(0.18), radius: 1.5, y: 1)521            .contentShape(Circle())522            .accessibilityElement()523            .accessibilityLabel(name)524            .accessibilityValue(JSONValue.fbNumber(value).displayString)525    }526}527528struct FBChipSelectComponent: View {529    @Environment(AppRuntime.self) private var runtime530    let o: PrismObject531532    var body: some View {533        let options = runtime.fbOptions(o)534        let multiple = o.props["multiple"]?.boolValue == true535        let raw = runtime.resolve(o.props["value"])536        let selected = multiple ? (raw.arrayValue ?? []).map(\.displayString) : (raw.displayString.isEmpty ? [] : [raw.displayString])537        Labeled(label: runtime.fbText(o, "label")) {538            FBFlowLayout(spacing: 6) {539                ForEach(options, id: \.self) { option in540                    FBChip(title: option, icon: multiple && selected.contains(option) ? "checkmark" : nil, selected: selected.contains(option)) {541                        if multiple {542                            runtime.fbSet(o, "value", .array(FBTags.toggling(option, in: selected, order: options).map(JSONValue.string)))543                        } else {544                            // A single-choice chip can be clicked again to clear the choice.545                            runtime.fbSet(o, "value", .string(selected.contains(option) ? "" : option))546                        }547                    }548                }549            }550        }551    }552}553554/// Email, web address and phone fields: the text is always kept, and a message shows while it is malformed.555struct FBValidatedFieldComponent: View {556    @Environment(AppRuntime.self) private var runtime557    let o: PrismObject558    let kind: FBValidate.Kind559560    private var defaultPlaceholder: String {561        switch kind { case .email: "name@example.com"; case .url: "https://example.com"; case .phone: "+1 555 010 0199" }562    }563564    private var icon: String {565        switch kind { case .email: "envelope"; case .url: "link"; case .phone: "phone" }566    }567568    var body: some View {569        let value = runtime.stateBinding(o)570        let text = value.wrappedValue.displayString571        let message = FBValidate.message(kind, text)572        let label = runtime.fbText(o, "label")573        Labeled(label: label) {574            VStack(alignment: .leading, spacing: 3) {575                HStack(spacing: 6) {576                    Image(systemName: icon).foregroundStyle(.secondary).accessibilityHidden(true)577                    TextField(runtime.fbText(o, "placeholder", defaultPlaceholder), text: Binding(get: { text }, set: { value.wrappedValue = .string($0) }))578                        .textFieldStyle(.plain)579                        .onSubmit { if message == nil { runtime.fire("submit", on: o.id, value: .string(text)) } }580                        .accessibilityLabel(label.isEmpty ? defaultPlaceholder : label)581                        .accessibilityValue(message.map { "\(text). \($0)" } ?? text)582                    if !text.isEmpty && message == nil {583                        Image(systemName: "checkmark.circle.fill").foregroundStyle(.green).accessibilityLabel("Valid")584                    }585                }586                .modifier(FBFieldFrame(invalid: message != nil))587                .frame(minWidth: 180, maxWidth: 340)588                FBInlineMessage(message: message)589            }590        }591    }592}593594/// Percent and unit fields: a number typed as text; only well-formed numbers reach the state.595struct FBNumericTextComponent: View {596    @Environment(AppRuntime.self) private var runtime597    let o: PrismObject598    let percent: Bool599    /// What the user is typing while it differs from the stored number (for example `12.` or `abc`).600    @State private var draft: String?601602    private func parse(_ text: String) -> Double? {603        let lo = o.props["min"]?.doubleValue ?? (percent ? 0 : -Double.greatestFiniteMagnitude)604        let hi = o.props["max"]?.doubleValue ?? (percent ? 100 : Double.greatestFiniteMagnitude)605        if percent { return FBValidate.percent(text, min: lo, max: hi) }606        guard let d = FBValidate.number(text), d >= lo, d <= hi else { return nil }607        return d608    }609610    private var message: String {611        let lo = o.props["min"]?.doubleValue, hi = o.props["max"]?.doubleValue612        if percent { return "Enter a percentage from \(JSONValue.fbNumber(lo ?? 0).displayString) to \(JSONValue.fbNumber(hi ?? 100).displayString)." }613        switch (lo, hi) {614        case let (lo?, hi?): return "Enter a number from \(JSONValue.fbNumber(lo).displayString) to \(JSONValue.fbNumber(hi).displayString)."615        case let (lo?, nil): return "Enter a number of at least \(JSONValue.fbNumber(lo).displayString)."616        case let (nil, hi?): return "Enter a number of at most \(JSONValue.fbNumber(hi).displayString)."617        default: return "Enter a number."618        }619    }620621    var body: some View {622        let value = runtime.stateBinding(o)623        let stored = value.wrappedValue.numericValue624        let canonical = stored.map { JSONValue.fbNumber($0).displayString } ?? ""625        let text = draft ?? canonical626        let invalid = !text.trimmingCharacters(in: .whitespaces).isEmpty && parse(text) == nil627        let suffix = percent ? "%" : runtime.fbText(o, "unit")628        let label = runtime.fbText(o, "label")629        Labeled(label: label) {630            VStack(alignment: .leading, spacing: 3) {631                HStack(spacing: 5) {632                    TextField("0", text: Binding(get: { text }, set: { new in633                        guard new != text else { return }634                        if let parsed = parse(new) {635                            let json = JSONValue.fbNumber(parsed)636                            draft = json.displayString == new ? nil : new637                            value.wrappedValue = json638                        } else {639                            draft = new640                        }641                    }))642                    .textFieldStyle(.plain)643                    .multilineTextAlignment(.trailing)644                    .frame(minWidth: 60, maxWidth: 120)645                    .accessibilityLabel(label.isEmpty ? (percent ? "Percentage" : "Amount") : label)646                    .accessibilityValue(invalid ? "\(text). \(message)" : "\(text) \(suffix)")647                    if !suffix.isEmpty { Text(suffix).foregroundStyle(.secondary).accessibilityHidden(true) }648                }649                .modifier(FBFieldFrame(invalid: invalid))650                .fixedSize()651                FBInlineMessage(message: invalid ? message : nil)652            }653        }654        // A value written from elsewhere replaces what was being typed.655        .onChange(of: stored) { _, new in656            if let draft, parse(draft) != new { self.draft = nil }657        }658    }659}660
Files main
Menu

Theme