SPB Git

Repository Public

FormView.swift 9.2 KB 191 lines swift

1import SwiftUI2import SheetCore3import SheetUI45private struct CompactFormKey: EnvironmentKey { static let defaultValue = false }6public extension EnvironmentValues {7    /// True inside narrow hosts (inspector): labels sit above their controls.8    var compactForm: Bool {9        get { self[CompactFormKey.self] }10        set { self[CompactFormKey.self] = newValue }11    }12}1314/// Renders the declarative form of a tool and keeps column choices in step with their ranges.15public struct FormView: View {16    let tool: ToolDescriptor17    @Binding var values: FormValues18    let session: WorkbookSession19    @Environment(\.compactForm) private var compact20    @State private var frames: [String: DataFrame] = [:]2122    public init(tool: ToolDescriptor, values: Binding<FormValues>, session: WorkbookSession) {23        self.tool = tool; _values = values; self.session = session24    }2526    /// Changes when a range field or the workbook content changes: the frames are then read again.27    private var refreshKey: String {28        var parts = [String(session.contentRevision), String(session.sheetIndex)]29        for f in tool.fields { if case .range = f.kind { let r = values.range(f.id); parts.append("\(f.id)=\(r.text)|\(r.hasHeader)") } }30        return parts.joined(separator: ";")31    }3233    public var body: some View {34        let visible = tool.fields.filter { $0.isVisible(values) }35        VStack(alignment: .leading, spacing: compact ? 10 : 9) {36            ForEach(visible) { field in row(field) }37        }38        .task(id: refreshKey) { refreshFrames() }39    }4041    private func refreshFrames() {42        var out = [String: DataFrame]()43        for f in tool.fields {44            if case .range = f.kind, let frame = ToolInputResolver.frame(values.range(f.id), session: session) { out[f.id] = frame }45        }46        frames = out47        var v = values48        ToolInputResolver.applyColumnDefaults(tool, values: &v, session: session)49        if v != values { values = v }50    }5152    @ViewBuilder private func row(_ field: FormField) -> some View {53        if case .section = field.kind {54            Text(field.label.uppercased())55                .font(.system(size: 10.5, weight: .semibold)).kerning(0.6)56                .foregroundStyle(ORIX.Palette.textTertiary)57                .padding(.top, 6)58                .accessibilityAddTraits(.isHeader)59        } else if case .toggle = field.kind {60            labelled(field, showLabel: false) { control(field) }61        } else {62            labelled(field, showLabel: true) { control(field) }63        }64    }6566    @ViewBuilder private func labelled<C: View>(_ field: FormField, showLabel: Bool, @ViewBuilder _ content: () -> C) -> some View {67        if compact {68            VStack(alignment: .leading, spacing: 3) {69                if showLabel { Text(field.label).font(.system(size: 11.5, weight: .medium)).foregroundStyle(ORIX.Palette.textSecondary) }70                content()71                if let help = field.help { helpText(help) }72            }73        } else {74            HStack(alignment: .firstTextBaseline, spacing: 12) {75                Text(showLabel ? field.label : "")76                    .font(.system(size: 12.5)).foregroundStyle(ORIX.Palette.textSecondary)77                    .frame(width: 178, alignment: .trailing)78                    .multilineTextAlignment(.trailing)79                    .accessibilityHidden(true)80                VStack(alignment: .leading, spacing: 3) {81                    content()82                    if let help = field.help { helpText(help) }83                }84                Spacer(minLength: 0)85            }86        }87    }8889    private func helpText(_ s: String) -> some View {90        Text(s).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)91    }9293    private func textBinding(_ id: String) -> Binding<String> {94        Binding(get: { values.text(id) }, set: { values.set(id, text: $0) })95    }9697    @ViewBuilder private func control(_ field: FormField) -> some View {98        let id = field.id99        let ident = "\(tool.id).\(id)"100        switch field.kind {101        case .range:102            RangePicker(field.label, value: Binding(get: { values.range(id) }, set: { values[id] = .range($0) }), session: session,103                        identifier: ident, frame: frames[id])104        case .column(let range, let numericOnly, let optional, _):105            ColumnPicker(field.label, selection: Binding(get: { values.columnIndex(id) }, set: { values.set(id, column: $0) }),106                         frame: frames[range], numericOnly: numericOnly, optional: optional, identifier: ident)107        case .columns(let range, let numericOnly, _):108            ColumnMultiPicker(field.label, selection: Binding(get: { values.columnIndices(id) }, set: { values.set(id, columns: $0) }),109                              frame: frames[range], numericOnly: numericOnly, identifier: ident)110        case .choice(let options, _):111            if options.count <= 3 && !compact && options.map(\.label.count).reduce(0, +) <= 44 {112                Picker(field.label, selection: textBinding(id)) { ForEach(options) { Text($0.label).tag($0.id) } }113                    .pickerStyle(.segmented).labelsHidden().fixedSize()114                    .accessibilityLabel(field.label).accessibilityIdentifier(ident)115            } else {116                Picker(field.label, selection: textBinding(id)) { ForEach(options) { Text($0.label).tag($0.id) } }117                    .labelsHidden().frame(minWidth: 120, maxWidth: 280, alignment: .leading)118                    .accessibilityLabel(field.label).accessibilityIdentifier(ident)119            }120        case .number(_, let lo, let hi, let style, let unit):121            NumberField(label: field.label, value: Binding(get: { values.number(id) }, set: { values.set(id, number: $0) }),122                        min: lo, max: hi, style: style, unit: unit, identifier: ident)123        case .integer(_, let lo, let hi):124            HStack(spacing: 4) {125                TextField("", value: Binding(get: { values.int(id) }, set: { values.set(id, int: Swift.min(Swift.max($0, lo), hi)) }), format: .number.grouping(.never))126                    .textFieldStyle(.roundedBorder).monospacedDigit().multilineTextAlignment(.trailing).frame(width: 84)127                    .accessibilityLabel(field.label).accessibilityIdentifier(ident)128                Stepper("", value: Binding(get: { values.int(id) }, set: { values.set(id, int: $0) }), in: lo...hi).labelsHidden()129                    .accessibilityLabel(field.label)130            }131        case .toggle:132            Toggle(field.label, isOn: Binding(get: { values.bool(id) }, set: { values.set(id, bool: $0) }))133                .toggleStyle(.checkbox).font(.system(size: 12.5))134                .accessibilityIdentifier(ident)135        case .text(_, let placeholder):136            TextField(placeholder, text: textBinding(id))137                .textFieldStyle(.roundedBorder).frame(minWidth: 120, maxWidth: 320)138                .accessibilityLabel(field.label).accessibilityIdentifier(ident)139        case .cell:140            CellField(field.label, text: textBinding(id), session: session, multiple: false, identifier: ident)141        case .cells:142            CellField(field.label, text: textBinding(id), session: session, multiple: true, identifier: ident)143        case .date:144            DatePicker(field.label, selection: Binding(get: { values.date(id) }, set: { values.set(id, date: $0) }), displayedComponents: .date)145                .labelsHidden().datePickerStyle(.field).fixedSize()146                .accessibilityLabel(field.label).accessibilityIdentifier(ident)147        case .section:148            EmptyView()149        }150    }151}152153/// Numeric text field with locale-aware parsing; percentages are edited as "5.25" and stored as 0.0525.154public struct NumberField: View {155    let label: String156    @Binding var value: Double157    var min: Double?158    var max: Double?159    var style: NumberStyle160    var unit: String?161    var identifier: String162    var width: CGFloat163164    public init(label: String, value: Binding<Double>, min: Double? = nil, max: Double? = nil, style: NumberStyle = .plain, unit: String? = nil,165                identifier: String = "number", width: CGFloat = 110) {166        self.label = label; _value = value; self.min = min; self.max = max; self.style = style; self.unit = unit; self.identifier = identifier; self.width = width167    }168169    private var scaled: Binding<Double> {170        let k = style == .percent ? 100.0 : 1.0171        return Binding(172            get: { value.isFinite ? (value * k * 1e10).rounded() / 1e10 : 0 },173            set: { new in174                var v = new / k175                if let min, v < min { v = min }176                if let max, v > max { v = max }177                value = v178            })179    }180181    public var body: some View {182        HStack(spacing: 5) {183            TextField("", value: scaled, format: .number.precision(.fractionLength(0...8)).grouping(.automatic))184                .textFieldStyle(.roundedBorder).monospacedDigit().multilineTextAlignment(.trailing).frame(width: width)185                .accessibilityLabel(unit.map { "\(label) (\($0))" } ?? label)186                .accessibilityIdentifier(identifier)187            if let unit { Text(unit).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textTertiary) }188        }189    }190}191
Files main
Menu

Theme