SPB Git

Repository Public License

Components+FamilyCDataMore.swift 23.1 KB 448 lines swift

1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67// MARK: Filter bar and sort menu89/// Auto-generated filter controls for chosen columns of a table. They write one state object:10/// `{<textColumn>: "text"|null, <numberColumn>Min: n|null, <numberColumn>Max: n|null, <dateColumn>From: "YYYY-MM-DD"|null,11///   <dateColumn>To: "YYYY-MM-DD"|null, <booleanColumn>: 1|0|null}` — a key is null (or absent) while its control is unset.12struct FCFilterBar: View {13    @Environment(AppRuntime.self) private var runtime14    let o: PrismObject1516    var body: some View {17        let table = FC.column(o, "table") ?? ""18        let names = o.props["columns"]?.arrayValue?.compactMap(\.stringValue) ?? []19        let schema = runtime.schema(table)20        let columns = names.compactMap { schema?.column($0) }21        let state = runtime.resolve(o.props["value"])22        let active = FamilyCMath.activeFilterCount(state)23        let title = runtime.string(o.props["title"])24        let problem: String? = schema == nil ? "Table “\(table)” does not exist." : names.isEmpty ? "List the `columns` to filter on."25            : names.first { schema?.column($0) == nil }.map { "“\($0)” is not a column of “\(table)”." }26        VStack(alignment: .leading, spacing: 8) {27            if let problem {28                Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)29            } else {30                HStack {31                    Label(title.isEmpty ? "Filters" : title, systemImage: "line.3.horizontal.decrease.circle").font(.subheadline.weight(.semibold))32                    if active > 0 { Text("\(active)").font(.caption.weight(.semibold)).monospacedDigit().accessibilityLabel("\(active) active filters") }33                    Spacer()34                    if o.props["showClear"]?.boolValue != false {35                        Button("Clear") { write(nil, .object([:])) }.disabled(active == 0).controlSize(.small).accessibilityLabel("Clear all filters")36                    }37                }38                LazyVGrid(columns: [GridItem(.adaptive(minimum: 176), spacing: 12, alignment: .topLeading)], alignment: .leading, spacing: 10) {39                    ForEach(columns, id: \.name) { c in40                        Labeled(label: c.label) { control(c, table: table, state: state) }.frame(maxWidth: .infinity, alignment: .leading)41                    }42                }43            }44        }45        .padding(12)46        .frame(maxWidth: .infinity, alignment: .leading)47        .prismSurface()48        .accessibilityElement(children: .contain)49        .accessibilityLabel(title.isEmpty ? "Filters" : title)50    }5152    /// Writes one key of the bound object (or the whole object when `key` is nil), then fires `change` with the new object.53    private func write(_ key: String?, _ value: JSONValue) {54        guard let path = runtime.bindingPath(o.props["value"]) else { return }55        runtime.setState(key.map { path + "." + $0 } ?? path, value)56        runtime.fire("change", on: o.id, value: runtime.resolve(o.props["value"]))57    }5859    @ViewBuilder60    private func control(_ c: ColumnSchema, table: String, state: JSONValue) -> some View {61        let distinct = c.type == .text || c.type == .date ? runtime.distinctValues(table: table, column: c.name).map(\.displayString) : []62        switch FamilyCMath.filterControl(type: c.type, options: c.options, distinct: distinct) {63        case .choice(let values):64            Picker(c.label, selection: Binding(get: { state[c.name]?.stringValue ?? "" }, set: { write(c.name, $0.isEmpty ? .null : .string($0)) })) {65                Text("Any").tag("")66                ForEach(values, id: \.self) { Text($0).tag($0) }67            }68            .labelsHidden()69        case .text:70            TextField("Contains…", text: Binding(get: { state[c.name]?.stringValue ?? "" }, set: { write(c.name, $0.isEmpty ? .null : .string($0)) }))71                .textFieldStyle(.roundedBorder)72        case .range:73            HStack(spacing: 6) {74                bound(c, "Min", state: state)75                Text("–").foregroundStyle(.secondary).accessibilityHidden(true)76                bound(c, "Max", state: state)77            }78        case .dateRange:79            HStack(spacing: 6) {80                day(c, "From", fallback: distinct.min(), state: state)81                day(c, "To", fallback: distinct.max(), state: state)82            }83        case .flag:84            Picker(c.label, selection: Binding(85                get: { state[c.name].flatMap { $0.isNull ? nil : ($0.isTruthy ? 1 : 0) } ?? -1 },86                set: { write(c.name, $0 < 0 ? .null : .int($0)) }87            )) {88                Text("Any").tag(-1)89                Text("Yes").tag(1)90                Text("No").tag(0)91            }92            .labelsHidden()93        }94    }9596    private func bound(_ c: ColumnSchema, _ suffix: String, state: JSONValue) -> some View {97        let key = c.name + suffix98        return TextField(suffix, value: Binding<Double?>(get: { state[key]?.numericValue }, set: { write(key, $0.map(JSONValue.double) ?? .null) }), format: .number.locale(runtime.locale))99            .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(minWidth: 56, maxWidth: 90)100            .accessibilityLabel("\(c.label), \(suffix == "Min" ? "minimum" : "maximum")")101    }102103    @ViewBuilder104    private func day(_ c: ColumnSchema, _ suffix: String, fallback: String?, state: JSONValue) -> some View {105        let key = c.name + suffix106        if let iso = state[key]?.stringValue, let date = LocalDate.date(iso) {107            HStack(spacing: 2) {108                DatePicker(suffix, selection: Binding(get: { date }, set: { write(key, .string(LocalDate.iso($0))) }), displayedComponents: .date)109                    .labelsHidden().accessibilityLabel("\(c.label), \(suffix.lowercased())")110                Button { write(key, .null) } label: { Image(systemName: "xmark.circle.fill") }111                    .buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Clear \(c.label) \(suffix.lowercased())")112            }113        } else {114            Button("\(suffix)…") { write(key, .string(fallback.flatMap { LocalDate.date($0) == nil ? nil : String($0.prefix(10)) } ?? LocalDate.iso(Date()))) }115                .controlSize(.small).accessibilityLabel("Set \(c.label) \(suffix.lowercased())")116        }117    }118}119120struct FCSortMenu: View {121    @Environment(AppRuntime.self) private var runtime122    let o: PrismObject123124    var body: some View {125        let options: [(column: String, title: String)] = (o.props["columns"]?.arrayValue ?? []).compactMap { item in126            guard let column = item["column"]?.stringValue ?? item.stringValue, !column.isEmpty else { return nil }127            return (column, item["title"]?.stringValue ?? column.prefix(1).uppercased() + column.dropFirst())128        }129        let state = runtime.resolve(o.props["value"])130        let current = state["column"]?.stringValue ?? "", descending = state["descending"]?.isTruthy ?? false131        let label = o.props["label"].map { runtime.string($0) } ?? "Sort"132        let currentTitle = options.first { $0.column == current }?.title133        Menu {134            ForEach(options, id: \.column) { option in135                Button { write(option.column, descending) } label: {136                    if option.column == current { Label(option.title, systemImage: "checkmark") } else { Text(option.title) }137                }138            }139            Divider()140            Button { write(current.isEmpty ? options.first?.column ?? "" : current, false) } label: {141                if !descending { Label("Ascending", systemImage: "checkmark") } else { Text("Ascending") }142            }143            Button { write(current.isEmpty ? options.first?.column ?? "" : current, true) } label: {144                if descending { Label("Descending", systemImage: "checkmark") } else { Text("Descending") }145            }146        } label: {147            Label(currentTitle.map { "\(label): \($0)" } ?? label, systemImage: descending ? "arrow.down" : "arrow.up")148        }149        .fixedSize()150        .disabled(options.isEmpty)151        .accessibilityLabel(label)152        .accessibilityValue(currentTitle.map { "\($0), \(descending ? "descending" : "ascending")" } ?? "Not sorted")153    }154155    private func write(_ column: String, _ descending: Bool) {156        guard !column.isEmpty else { return }157        let value: JSONValue = ["column": .string(column), "descending": .bool(descending)]158        if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, value) }159        runtime.fire("change", on: o.id, value: value)160    }161}162163// MARK: Statistics164165struct FCColumnStats: View {166    @Environment(AppRuntime.self) private var runtime167    let o: PrismObject168169    var body: some View {170        let column = FC.column(o, "valueColumn")171        let source = FC.source(runtime, o, columns: [column]).orProblem(column == nil, "Set `valueColumn` to a column of the query.")172        let stats = FamilyCMath.stats(source.rows.compactMap { $0[column ?? ""]?.numericValue })173        let format = source.format(column ?? "", override: o.props["format"]?.stringValue)174        let entries: [(String, String)] = [175            ("Count", FC.number(runtime, Double(stats.count))), ("Min", FC.number(runtime, stats.min, format)), ("Max", FC.number(runtime, stats.max, format)),176            ("Average", FC.number(runtime, stats.average, format)), ("Sum", FC.number(runtime, stats.count == 0 ? nil : stats.sum, format)),177        ]178        FCPanel(179            title: o.props["title"].map { runtime.string($0) } ?? column.map { source.title($0) } ?? "", fallbackLabel: "Column statistics", problem: source.problem,180            isEmpty: stats.count == 0, emptyTitle: source.rows.isEmpty ? "No data yet" : "No numeric values", emptyMessage: "", emptySymbol: "sum",181            summary: entries.map { "\($0.0): \($0.1)" }.joined(separator: "; ")182        ) {183            HStack(alignment: .top, spacing: 0) {184                ForEach(entries.indices, id: \.self) { i in185                    if i > 0 { Divider().padding(.horizontal, 10) }186                    VStack(alignment: .leading, spacing: 2) {187                        Text(entries[i].0).font(.caption).foregroundStyle(.secondary)188                        Text(entries[i].1).font(.headline).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)189                    }190                    .frame(maxWidth: .infinity, alignment: .leading)191                    .accessibilityElement(children: .combine)192                }193            }194            .fixedSize(horizontal: false, vertical: true)195        }196    }197}198199struct FCStatGrid: View {200    @Environment(AppRuntime.self) private var runtime201    @Environment(\.prismTheme) private var theme202    let o: PrismObject203204    var body: some View {205        let specs = o.props["items"]?.arrayValue ?? []206        let perRow = min(max(o.props["perRow"]?.intValue ?? 3, 1), 8)207        if specs.isEmpty {208            Label("Add `items`: `{label, query, valueColumn, format}`.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)209        } else {210            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: theme.spacing, alignment: .top), count: perRow), spacing: theme.spacing) {211                ForEach(specs.indices, id: \.self) { i in tile(specs[i]) }212            }213        }214    }215216    @ViewBuilder217    private func tile(_ spec: JSONValue) -> some View {218        let column = spec["valueColumn"]?.stringValue219        let source = spec["query"].map { FC.source(runtime, query: $0, columns: [column]) } ?? FCSource(problem: "This statistic has no `query`.")220        let row = source.rows.first ?? [:]221        let value = column.map { row[$0] ?? .null } ?? row.sorted { $0.key < $1.key }.first?.value ?? .null222        let shown = CellFormat.text(value, format: spec["format"]?.stringValue ?? column.map { source.format($0) } ?? "number", runtime: runtime)223        let label = runtime.string(spec["label"])224        HStack(spacing: 10) {225            if let icon = spec["icon"]?.stringValue {226                Image(systemName: SymbolName.safe(icon)).font(.title3).foregroundStyle(theme.accent).frame(width: 26).accessibilityHidden(true)227            }228            VStack(alignment: .leading, spacing: 2) {229                Text(label).font(.callout).foregroundStyle(.secondary).lineLimit(1)230                if let problem = source.problem {231                    Text(problem).font(.caption).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)232                } else {233                    Text(shown.isEmpty ? "—" : shown).font(.title2.weight(.semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)234                }235            }236            Spacer(minLength: 0)237        }238        .padding(12)239        .frame(maxWidth: .infinity, alignment: .leading)240        .prismSurface()241        .accessibilityElement(children: .ignore)242        .accessibilityLabel(label)243        .accessibilityValue(source.problem ?? (shown.isEmpty ? "No value" : shown))244    }245}246247struct FCRankList: View {248    @Environment(AppRuntime.self) private var runtime249    @Environment(\.prismTheme) private var theme250    let o: PrismObject251252    var body: some View {253        let label = FC.column(o, "labelColumn"), value = FC.column(o, "valueColumn")254        let fn = o.props["aggregate"]?.stringValue ?? (value == nil ? "count" : "sum")255        let source = FC.source(runtime, o, columns: [label, value])256            .orProblem(label == nil, "Set `labelColumn` to the column to group by.")257            .orProblem(value == nil && fn != "count", "`\(fn)` needs a `valueColumn`.")258        let ranked = FamilyCMath.rank(source.rows, label: label ?? "", value: value, fn: fn, limit: o.props["limit"]?.intValue ?? 5)259        let top = max(ranked.map(\.value).max() ?? 0, .leastNonzeroMagnitude)260        let format = o.props["format"]?.stringValue ?? (fn == "count" ? "number" : value.map { source.format($0) } ?? "number")261        let color = FC.toneColor(theme, runtime.string(o.props["tone"]))262        FCPanel(263            title: runtime.string(o.props["title"]), fallbackLabel: "Top list", problem: source.problem, isEmpty: source.rows.isEmpty, emptySymbol: "list.number",264            summary: ranked.enumerated().map { "\($0.offset + 1). \($0.element.label): \(FC.number(runtime, $0.element.value, format))" }.joined(separator: "; ")265        ) {266            VStack(alignment: .leading, spacing: 8) {267                ForEach(Array(ranked.enumerated()), id: \.offset) { i, entry in268                    VStack(alignment: .leading, spacing: 3) {269                        HStack {270                            Text("\(i + 1).").foregroundStyle(.secondary).monospacedDigit()271                            Text(entry.label).lineLimit(1)272                            Spacer(minLength: 8)273                            Text(FC.number(runtime, entry.value, format)).monospacedDigit().fontWeight(.medium)274                        }275                        FCBar(fraction: max(entry.value, 0) / top, color: color, height: 6)276                    }277                    .accessibilityElement(children: .combine)278                }279            }280        }281    }282}283284struct FCProgressList: View {285    @Environment(AppRuntime.self) private var runtime286    @Environment(\.prismTheme) private var theme287    let o: PrismObject288289    var body: some View {290        let label = FC.column(o, "labelColumn"), value = FC.column(o, "valueColumn")291        let source = FC.source(runtime, o, columns: [label, value]).orProblem(label == nil || value == nil, "Set `labelColumn` and `valueColumn` to columns of the query.")292        let items = FCItem.list(source.rows)293        let color = FC.toneColor(theme, runtime.string(o.props["tone"]))294        let percent: (Double) -> String = { $0.formatted(.percent.precision(.fractionLength(0)).locale(runtime.locale)) }295        FCPanel(296            title: runtime.string(o.props["title"]), fallbackLabel: "Progress", problem: source.problem, isEmpty: items.isEmpty, emptySymbol: "chart.bar.doc.horizontal",297            summary: items.map { "\(source.text($0.row, label, runtime: runtime)): \(percent(FamilyCMath.fraction($0.row[value ?? ""]?.numericValue ?? 0, min: 0, max: 1)))" }.joined(separator: "; ")298        ) {299            VStack(alignment: .leading, spacing: 9) {300                ForEach(items) { item in301                    let f = FamilyCMath.fraction(item.row[value ?? ""]?.numericValue ?? 0, min: 0, max: 1)302                    VStack(alignment: .leading, spacing: 3) {303                        HStack {304                            Text(FC.label(.string(source.text(item.row, label, runtime: runtime)))).lineLimit(1)305                            Spacer(minLength: 8)306                            if o.props["showPercent"]?.boolValue != false { Text(percent(f)).font(.callout).foregroundStyle(.secondary).monospacedDigit() }307                        }308                        FCBar(fraction: f, color: f >= 1 ? theme.color("success") : color)309                    }310                    .accessibilityElement(children: .ignore)311                    .accessibilityLabel(source.text(item.row, label, runtime: runtime))312                    .accessibilityValue(percent(f))313                }314                FCMoreFooter(shown: items.count, total: source.rows.count)315            }316        }317    }318}319320struct FCDuplicateFinder: View {321    @Environment(AppRuntime.self) private var runtime322    let o: PrismObject323324    var body: some View {325        let column = FC.column(o, "valueColumn"), label = FC.column(o, "labelColumn")326        let source = FC.source(runtime, o, columns: [column, label]).orProblem(column == nil, "Set `valueColumn` to the column to compare.")327        let groups = FamilyCMath.duplicates(source.rows, column: column ?? "", caseSensitive: o.props["caseSensitive"]?.boolValue == true)328        let extra = groups.reduce(0) { $0 + $1.rows.count - 1 }329        FCPanel(330            title: runtime.string(o.props["title"]), fallbackLabel: "Duplicates", problem: source.problem, isEmpty: groups.isEmpty,331            emptyTitle: source.rows.isEmpty ? "No data yet" : "No duplicates", emptyMessage: source.rows.isEmpty ? "" : "Every row has a different \(source.title(column ?? "")).", emptySymbol: source.rows.isEmpty ? "tray" : "checkmark.seal",332            summary: groups.map { "\($0.value): \($0.rows.count) rows" }.joined(separator: "; "), trailing: groups.isEmpty ? "" : "\(groups.count) group\(groups.count == 1 ? "" : "s"), \(extra) extra"333        ) {334            VStack(alignment: .leading, spacing: 2) {335                ForEach(Array(groups.prefix(50).enumerated()), id: \.offset) { _, g in336                    HStack(spacing: 6) {337                        Text(g.value).font(.subheadline.weight(.semibold)).lineLimit(1).accessibilityAddTraits(.isHeader)338                        BadgeView(text: "×\(g.rows.count)", tone: "warning").accessibilityLabel("\(g.rows.count) rows")339                    }340                    .padding(.top, 6).padding(.horizontal, 10)341                    ForEach(FCItem.list(g.rows, cap: 20)) { item in342                        let id = item.row["id"]?.displayString ?? ""343                        let detail = label.map { source.text(item.row, $0, runtime: runtime) } ?? ""344                        FCRowButton(selected: false, accessibility: "Record \(id) \(detail)", action: { runtime.fire("select", on: o.id, value: item.row["id"] ?? .null, row: .object(item.row)) }) {345                            HStack {346                                Text("#\(id)").foregroundStyle(.secondary).monospacedDigit()347                                Text(detail.isEmpty ? g.value : detail).lineLimit(1)348                                Spacer(minLength: 0)349                            }350                        }351                    }352                }353                FCMoreFooter(shown: min(groups.count, 50), total: groups.count)354            }355        }356    }357}358359// MARK: JSON360361struct FCJSONViewer: View {362    @Environment(AppRuntime.self) private var runtime363    let o: PrismObject364365    var body: some View {366        let value = runtime.resolve(o.props["value"])367        FCPanel(title: runtime.string(o.props["title"]), fallbackLabel: "JSON", summary: FCJSONNode.summary(value)) {368            FCJSONNode(key: nil, value: value, depth: 0, expandDepth: o.props["expandDepth"]?.intValue ?? 1)369                .font(.callout.monospaced())370                .fontDesign(.monospaced)371                .frame(maxWidth: .infinity, alignment: .leading)372        }373    }374}375376/// One node of the tree; containers collapse and expand.377struct FCJSONNode: View {378    @Environment(\.prismTheme) private var theme379    let key: String?380    let value: JSONValue381    let depth: Int382    let expandDepth: Int383    @State private var toggled: Bool?384385    static func summary(_ value: JSONValue) -> String {386        switch value {387        case .object(let o): "{\(o.count) key\(o.count == 1 ? "" : "s")}"388        case .array(let a): "[\(a.count) item\(a.count == 1 ? "" : "s")]"389        case .string(let s): "\"\(s)\""390        case .null: "null"391        default: value.displayString392        }393    }394395    private var children: [(key: String, value: JSONValue)]? {396        switch value {397        case .object(let o): o.sorted { $0.key < $1.key }.map { (key: $0.key, value: $0.value) }398        case .array(let a): a.enumerated().map { (key: String($0.offset), value: $0.element) }399        default: nil400        }401    }402403    private var leafColor: Color {404        switch value {405        case .string: theme.color("success")406        case .int, .double: theme.color("info")407        case .bool: theme.color("warning")408        default: .secondary409        }410    }411412    var body: some View {413        let open = toggled ?? (depth < expandDepth)414        VStack(alignment: .leading, spacing: 3) {415            if let children {416                Button { toggled = !open } label: {417                    HStack(spacing: 4) {418                        Image(systemName: open ? "chevron.down" : "chevron.right").font(.caption2).foregroundStyle(.secondary).frame(width: 12)419                        if let key { Text(key + ":") }420                        Text(Self.summary(value)).foregroundStyle(.secondary)421                    }422                    .contentShape(Rectangle())423                }424                .buttonStyle(.plain)425                .disabled(children.isEmpty)426                .accessibilityLabel("\(key ?? "Value"), \(Self.summary(value))")427                .accessibilityValue(open ? "Expanded" : "Collapsed")428                if open {429                    VStack(alignment: .leading, spacing: 3) {430                        ForEach(children.prefix(200), id: \.key) { child in431                            FCJSONNode(key: child.key, value: child.value, depth: depth + 1, expandDepth: expandDepth)432                        }433                        if children.count > 200 { Text("… \(children.count - 200) more").foregroundStyle(.secondary) }434                    }435                    .padding(.leading, 16)436                }437            } else {438                HStack(alignment: .firstTextBaseline, spacing: 4) {439                    Color.clear.frame(width: 12, height: 1)440                    if let key { Text(key + ":") }441                    Text(Self.summary(value)).foregroundStyle(leafColor).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)442                }443                .accessibilityElement(children: .combine)444            }445        }446    }447}448
Files main
Menu

Theme