SPB Git

Repository Public

RangePicker.swift 10.2 KB 213 lines swift

1import SwiftUI2import SheetCore3import SheetUI45/// Reusable range control: A1 text field, "Use Selection" button and header-row toggle.6/// Column choosers (`ColumnPicker`, `ColumnMultiPicker`) read the header names of the same range.7public struct RangePicker: View {8    let label: String9    @Binding var value: RangeValue10    let session: WorkbookSession11    var identifier: String12    var frame: DataFrame?1314    public init(_ label: String, value: Binding<RangeValue>, session: WorkbookSession, identifier: String = "range", frame: DataFrame? = nil) {15        self.label = label; _value = value; self.session = session; self.identifier = identifier; self.frame = frame16    }1718    public var body: some View {19        VStack(alignment: .leading, spacing: 5) {20            HStack(spacing: 6) {21                TextField(L("Range, e.g. A1:D50"), text: $value.text)22                    .textFieldStyle(.roundedBorder)23                    .font(ORIX.Typeface.mono)24                    .frame(minWidth: 110, maxWidth: 240)25                    .accessibilityLabel(label)26                    .accessibilityIdentifier("\(identifier)-text")27                Button {28                    let area = ToolInputResolver.selectionArea(session)29                    value = RangeValue(text: area.range.a1, hasHeader: RangeReader.guessHeader(workbook: session.workbook, area: area))30                } label: { Label(L("Use Selection"), systemImage: "scope") }31                    .controlSize(.small)32                    .help(L("Use the selected range (or the data region around the active cell)"))33                    .accessibilityIdentifier("\(identifier)-use-selection")34            }35            HStack(spacing: 10) {36                Toggle(L("First row contains headers"), isOn: $value.hasHeader)37                    .toggleStyle(.checkbox)38                    .font(.system(size: 11.5))39                    .accessibilityIdentifier("\(identifier)-header")40                statusText41            }42        }43    }4445    @ViewBuilder private var statusText: some View {46        if value.text.trimmingCharacters(in: .whitespaces).isEmpty {47            EmptyView()48        } else if let frame {49            Text(L("%d rows × %d columns", frame.rowCount, frame.columns.count))50                .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)51        } else {52            Label(L("Not a valid range"), systemImage: "exclamationmark.triangle.fill")53                .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.warning)54        }55    }56}5758/// One cell (or a list of cells) typed in A1 notation, with a "Use Selection" button.59public struct CellField: View {60    let label: String61    @Binding var text: String62    let session: WorkbookSession63    let multiple: Bool64    var identifier: String6566    public init(_ label: String, text: Binding<String>, session: WorkbookSession, multiple: Bool = false, identifier: String = "cell") {67        self.label = label; _text = text; self.session = session; self.multiple = multiple; self.identifier = identifier68    }6970    public var body: some View {71        HStack(spacing: 6) {72            TextField(multiple ? L("Cells, e.g. B3, B5:B7") : L("Cell, e.g. B3"), text: $text)73                .textFieldStyle(.roundedBorder)74                .font(ORIX.Typeface.mono)75                .frame(minWidth: 80, maxWidth: multiple ? 240 : 150)76                .accessibilityLabel(label)77                .accessibilityIdentifier("\(identifier)-text")78            Button {79                let s = session.selection80                text = multiple ? s.ranges.map(\.a1).joined(separator: ", ") : s.active.a181            } label: { Image(systemName: "scope") }82                .controlSize(.small)83                .help(multiple ? L("Use the selected cells") : L("Use the active cell"))84                .accessibilityLabel(multiple ? L("Use the selected cells") : L("Use the active cell"))85                .accessibilityIdentifier("\(identifier)-use-selection")86            if !multiple, let v = currentValue {87                Text(v).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)88            }89        }90    }9192    /// Current content of the referenced cell, as feedback that the reference is the intended one.93    private var currentValue: String? {94        _ = session.contentRevision95        guard let c = RangeReader.cells(text, workbook: session.workbook, sheet: session.sheetIndex)?.first, c.sheet < session.workbook.sheets.count else { return nil }96        let sh = session.workbook.sheets[c.sheet]97        let v = sh.value(c.cell.row, c.cell.col)98        let shown = v.isBlank ? L("empty") : Fmt.text(v)99        return (sh.cell(c.cell.row, c.cell.col)?.formula != nil ? "ƒ " : "") + "= " + shown100    }101}102103/// Chooser of one column of a range, listing the header names.104public struct ColumnPicker: View {105    let label: String106    @Binding var selection: Int?107    let frame: DataFrame?108    let numericOnly: Bool109    let optional: Bool110    var identifier: String111112    public init(_ label: String, selection: Binding<Int?>, frame: DataFrame?, numericOnly: Bool = true, optional: Bool = false, identifier: String = "column") {113        self.label = label; _selection = selection; self.frame = frame; self.numericOnly = numericOnly; self.optional = optional; self.identifier = identifier114    }115116    public var body: some View {117        let columns = (frame?.columns ?? []).filter { !numericOnly || $0.isNumeric }118        Picker(label, selection: $selection) {119            if optional || columns.isEmpty { Text(columns.isEmpty ? L("No column available") : L("None")).tag(Int?.none) }120            ForEach(columns, id: \.index) { c in Text(c.name).tag(Int?.some(c.index)) }121        }122        .labelsHidden()123        .frame(minWidth: 120, maxWidth: 240, alignment: .leading)124        .disabled(columns.isEmpty)125        .accessibilityLabel(label)126        .accessibilityIdentifier(identifier)127    }128}129130/// Chooser of several columns of a range (toggle chips with the header names).131public struct ColumnMultiPicker: View {132    let label: String133    @Binding var selection: [Int]134    let frame: DataFrame?135    let numericOnly: Bool136    var identifier: String137138    public init(_ label: String, selection: Binding<[Int]>, frame: DataFrame?, numericOnly: Bool = true, identifier: String = "columns") {139        self.label = label; _selection = selection; self.frame = frame; self.numericOnly = numericOnly; self.identifier = identifier140    }141142    public var body: some View {143        let columns = (frame?.columns ?? []).filter { !numericOnly || $0.isNumeric }144        if columns.isEmpty {145            Text(numericOnly ? L("No numeric column in the range") : L("No column available"))146                .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)147        } else {148            VStack(alignment: .leading, spacing: 5) {149                FlowLayout(spacing: 5) {150                    ForEach(columns, id: \.index) { c in151                        let on = selection.contains(c.index)152                        Button {153                            if on { selection.removeAll { $0 == c.index } } else { selection = (selection + [c.index]).sorted() }154                        } label: {155                            Text(c.name)156                                .font(.system(size: 11.5, weight: .medium))157                                .lineLimit(1)158                                .padding(.horizontal, 8).padding(.vertical, 3.5)159                                .foregroundStyle(on ? ORIX.Palette.accent : ORIX.Palette.textSecondary)160                                .background(RoundedRectangle(cornerRadius: ORIX.Radius.chip).fill(on ? ORIX.Palette.accent.opacity(0.14) : ORIX.Palette.surfaceRaised))161                                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip).strokeBorder(on ? ORIX.Palette.accent.opacity(0.55) : ORIX.Palette.hairline))162                                .contentShape(Rectangle())163                        }164                        .buttonStyle(.plain)165                        .accessibilityLabel(c.name)166                        .accessibilityValue(on ? L("selected") : L("not selected"))167                        .accessibilityAddTraits(on ? .isSelected : [])168                        .accessibilityIdentifier("\(identifier)-\(c.index)")169                    }170                }171                HStack(spacing: 8) {172                    Button(L("All")) { selection = columns.map(\.index) }.accessibilityIdentifier("\(identifier)-all")173                    Button(L("None")) { selection = [] }.accessibilityIdentifier("\(identifier)-none")174                    Text(L("%d of %d selected", selection.filter { i in columns.contains { $0.index == i } }.count, columns.count))175                        .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)176                }177                .buttonStyle(.link).font(.system(size: 11))178            }179            .accessibilityElement(children: .contain)180            .accessibilityLabel(label)181        }182    }183}184185/// Wrapping horizontal layout for chips.186public struct FlowLayout: Layout {187    public var spacing: CGFloat188    public init(spacing: CGFloat = 6) { self.spacing = spacing }189190    public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {191        arrange(width: proposal.width ?? .infinity, subviews: subviews).size192    }193194    public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {195        let a = arrange(width: bounds.width, subviews: subviews)196        for (i, p) in a.points.enumerated() { subviews[i].place(at: CGPoint(x: bounds.minX + p.x, y: bounds.minY + p.y), proposal: .unspecified) }197    }198199    private func arrange(width: CGFloat, subviews: Subviews) -> (points: [CGPoint], size: CGSize) {200        var points = [CGPoint]()201        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0202        for s in subviews {203            let size = s.sizeThatFits(.unspecified)204            if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }205            points.append(CGPoint(x: x, y: y))206            x += size.width + spacing207            rowHeight = max(rowHeight, size.height)208            maxX = max(maxX, x - spacing)209        }210        return (points, CGSize(width: maxX, height: y + rowHeight))211    }212}213
Files main
Menu

Theme