SPB Git

Repository Public

SchemaFormView.swift 5.9 KB 120 lines swift

1import MCCCore2import SwiftUI34/// Controls generated from the JSON Schema of an action type (`params_schema`). Validation is the server's; the5/// form only offers the right kind of input and keeps numbers within the advertised bounds.6struct SchemaFormView: View {7    @Environment(\.mccTheme) private var theme8    @Bindable var model: ActionFormModel910    var body: some View {11        VStack(alignment: .leading, spacing: Tokens.Space.s4) {12            ForEach(model.fields) { f in13                VStack(alignment: .leading, spacing: Tokens.Space.s1) {14                    control(f)15                    if let help = f.help { Text(help).font(.footnote).foregroundStyle(theme.textTertiary) }16                    if model.invalidJSONFields.contains(f.name) {17                        StatusLabel(tr("actions.form.invalid_json"), tone: .critical).font(.footnote)18                    }19                }20            }21        }22    }2324    private func title(_ f: SchemaField) -> String { f.required ? f.title + " *" : f.title }2526    @ViewBuilder private func control(_ f: SchemaField) -> some View {27        let id = "field-" + f.name28        switch f.kind {29        case .boolean:30            Toggle(title(f), isOn: Binding(get: { model.values[f.name]?.boolValue ?? false }, set: { model.values[f.name] = .bool($0) }))31                .frame(minHeight: Tokens.Size.touchMin)32                .accessibilityIdentifier(id)33        case .choice(let options):34            HStack {35                Text(title(f)).font(.callout).foregroundStyle(theme.textPrimary)36                Spacer(minLength: Tokens.Space.s3)37                Picker(title(f), selection: Binding(get: { model.values[f.name]?.stringValue ?? "" }, set: { model.values[f.name] = $0.isEmpty ? nil : .string($0) })) {38                    if !f.required || model.values[f.name]?.stringValue == nil { Text(tr("actions.form.choose")).tag("") }39                    ForEach(options, id: \.self) { Text($0).tag($0) }40                }41                .pickerStyle(.menu)42                .accessibilityIdentifier(id)43            }44            .frame(minHeight: Tokens.Size.touchMin)45        case .string:46            labeled(f) {47                TextField(f.title, text: Binding(get: { model.values[f.name]?.stringValue ?? "" }, set: { model.values[f.name] = .string($0) }), axis: .vertical)48                    .lineLimit(1...4)49                    .textInputAutocapitalization(.never).autocorrectionDisabled()50                    .textFieldStyle(.roundedBorder)51                    .accessibilityLabel(f.title)52                    .accessibilityIdentifier(id)53            }54        case .integer(let lo, let hi):55            labeled(f, bounds: SchemaFormView.boundsText(lo.map(Double.init), hi.map(Double.init))) {56                TextField(f.title, text: numberBinding(f.name, integer: true, min: lo.map(Double.init), max: hi.map(Double.init)))57                    .keyboardType(.numberPad)58                    .textFieldStyle(.roundedBorder)59                    .accessibilityLabel(f.title)60                    .accessibilityIdentifier(id)61            }62        case .number(let lo, let hi):63            labeled(f, bounds: SchemaFormView.boundsText(lo, hi)) {64                TextField(f.title, text: numberBinding(f.name, integer: false, min: lo, max: hi))65                    .keyboardType(.decimalPad)66                    .textFieldStyle(.roundedBorder)67                    .accessibilityLabel(f.title)68                    .accessibilityIdentifier(id)69            }70        case .json:71            labeled(f, bounds: tr("actions.form.json")) {72                TextEditor(text: Binding(get: { model.rawJSON[f.name] ?? "" }, set: { model.rawJSON[f.name] = $0 }))73                    .font(.callout.monospaced())74                    .textInputAutocapitalization(.never).autocorrectionDisabled()75                    .frame(minHeight: 96)76                    .scrollContentBackground(.hidden)77                    .background(theme.inset, in: RoundedRectangle(cornerRadius: Tokens.Radius.md))78                    .accessibilityLabel(f.title)79                    .accessibilityIdentifier(id)80            }81        }82    }8384    private func labeled<C: View>(_ f: SchemaField, bounds: String? = nil, @ViewBuilder content: () -> C) -> some View {85        VStack(alignment: .leading, spacing: Tokens.Space.s1) {86            Text([title(f), bounds].compactMap { $0 }.joined(separator: " · ")).font(.footnote.weight(.medium)).foregroundStyle(theme.textSecondary).accessibilityHidden(true)87            content().frame(minHeight: Tokens.Size.touchMin)88        }89    }9091    /// Text ↔ number. An empty field removes the value; a value outside the bounds is clamped.92    private func numberBinding(_ name: String, integer: Bool, min: Double?, max: Double?) -> Binding<String> {93        Binding(get: {94            guard let n = model.values[name]?.doubleValue else { return "" }95            return n.rounded() == n ? String(Int64(n)) : String(n)96        }, set: { text in97            model.values[name] = SchemaFormView.number(from: text, integer: integer, min: min, max: max).map { .number($0) }98        })99    }100101    static func number(from text: String, integer: Bool, min: Double?, max: Double?) -> Double? {102        let t = text.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")103        guard !t.isEmpty, var n = Double(t), n.isFinite else { return nil }104        if integer { n = n.rounded(.towardZero) }105        if let min, n < min { n = min }106        if let max, n > max { n = max }107        return n108    }109110    static func boundsText(_ lo: Double?, _ hi: Double?) -> String? {111        func s(_ d: Double) -> String { d.rounded() == d && abs(d) < 1e15 ? String(Int64(d)) : String(d) }112        switch (lo, hi) {113        case (let l?, let h?): return s(l) + " – " + s(h)114        case (let l?, nil): return "≥ " + s(l)115        case (nil, let h?): return "≤ " + s(h)116        default: return nil117        }118    }119}120
Files main
Menu

Theme