SPB Git

Repository Public License

DataComponents.swift 19.7 KB 426 lines swift

1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67struct GridColumn: Identifiable, Equatable {8    var key: String9    var title: String10    var format: String11    var trailing: Bool12    var width: CGFloat?13    var id: String { key }14}1516@MainActor17enum CellFormat {18    static func text(_ value: JSONValue, format: String, runtime: AppRuntime) -> String {19        if value.isNull { return "" }20        switch format {21        case "currency": return value.numericValue.map { $0.formatted(.currency(code: runtime.currencyCode).locale(runtime.locale)) } ?? value.displayString22        case "number": return value.numericValue.map { $0.formatted(.number.precision(.fractionLength(0...2)).locale(runtime.locale)) } ?? value.displayString23        case "percent": return value.numericValue.map { $0.formatted(.percent.precision(.fractionLength(0...1)).locale(runtime.locale)) } ?? value.displayString24        case "date": return LocalDate.date(value.displayString).map { $0.formatted(Date.FormatStyle(date: .abbreviated, time: .omitted).locale(runtime.locale)) } ?? value.displayString25        case "boolean": return value.isTruthy ? "Yes" : "No"26        default: return value.displayString27        }28    }2930    static func defaultFormat(_ type: ColumnType?) -> String {31        switch type {32        case .currency: "currency"33        case .number, .integer: "number"34        case .date: "date"35        case .boolean: "boolean"36        default: "text"37        }38    }3940    /// Columns from a `columns` prop, or every output column of the query when the prop is absent.41    static func columns(_ prop: JSONValue?, query: DataQuery?, schema: TableSchema?) -> [GridColumn] {42        let outputs = (query.flatMap { q in schema.map { q.outputColumns(schema: $0) } } ?? schema.map { $0.columns.map(\.name) } ?? []).filter { $0 != "id" }43        let declared: [JSONValue] = prop?.arrayValue ?? outputs.map(JSONValue.string)44        return declared.compactMap { item in45            guard let key = item["column"]?.stringValue ?? item.stringValue else { return nil }46            let column = schema?.column(key)47            let format = item["format"]?.stringValue ?? defaultFormat(column?.type)48            let trailing = item["align"]?.stringValue.map { $0 == "trailing" } ?? (format == "currency" || format == "number" || format == "percent")49            return GridColumn(key: key, title: item["title"]?.stringValue ?? column?.label ?? key.prefix(1).uppercased() + key.dropFirst(),50                              format: format, trailing: trailing, width: item["width"]?.doubleValue.map { CGFloat($0) })51        }52    }53}5455/// The shared grid: sortable headers, row selection, double-click to activate. Rows are lazy, so large tables stay responsive.56struct DataGrid: View {57    @Environment(AppRuntime.self) private var runtime58    let columns: [GridColumn]59    let rows: [[String: JSONValue]]60    @Binding var selection: Int?61    @Binding var sort: DataQuery.Sort?62    var sortable = true63    var emptyTitle = "Nothing here yet"64    var emptyMessage = ""65    var onActivate: ((Int) -> Void)?6667    var body: some View {68        VStack(spacing: 0) {69            HStack(spacing: 12) {70                ForEach(columns) { column in71                    Button { toggleSort(column.key) } label: {72                        HStack(spacing: 3) {73                            if column.trailing { Spacer(minLength: 0) }74                            Text(column.title).font(.caption.weight(.semibold)).foregroundStyle(.secondary).lineLimit(1)75                            if sort?.column == column.key { Image(systemName: sort?.descending == true ? "chevron.down" : "chevron.up").font(.caption2).foregroundStyle(.secondary) }76                            if !column.trailing { Spacer(minLength: 0) }77                        }78                        .contentShape(Rectangle())79                    }80                    .buttonStyle(.plain)81                    .disabled(!sortable)82                    .frame(width: column.width)83                    .frame(maxWidth: column.width == nil ? .infinity : nil)84                    .accessibilityLabel("Sort by \(column.title)")85                }86            }87            .padding(.horizontal, 18).padding(.vertical, 6)88            Divider()89            if rows.isEmpty {90                ContentUnavailableView(emptyTitle, systemImage: "tray", description: Text(emptyMessage))91                    .frame(maxWidth: .infinity, minHeight: 120, maxHeight: .infinity)92            } else {93                List(rows.indices, id: \.self, selection: Binding<Int?>(94                    get: { selection.flatMap { id in rows.firstIndex { $0["id"]?.intValue == id } } },95                    set: { selection = $0.flatMap { rows.indices.contains($0) ? rows[$0]["id"]?.intValue ?? $0 : nil } }96                )) { index in97                    HStack(spacing: 12) {98                        ForEach(columns) { column in99                            cell(rows[index][column.key] ?? .null, column)100                                .frame(width: column.width, alignment: column.trailing ? .trailing : .leading)101                                .frame(maxWidth: column.width == nil ? .infinity : nil, alignment: column.trailing ? .trailing : .leading)102                        }103                    }104                    .accessibilityElement(children: .combine)105                }106                .listStyle(.inset(alternatesRowBackgrounds: true))107                .contextMenu(forSelectionType: Int.self) { _ in } primaryAction: { indices in108                    if let i = indices.first, rows.indices.contains(i), let id = rows[i]["id"]?.intValue { onActivate?(id) }109                }110            }111        }112        .frame(minHeight: 160)113        .background(.background, in: RoundedRectangle(cornerRadius: 8))114        .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.separator.opacity(0.7)))115        .clipShape(RoundedRectangle(cornerRadius: 8))116    }117118    @ViewBuilder119    private func cell(_ value: JSONValue, _ column: GridColumn) -> some View {120        if column.format == "badge" {121            if !value.displayString.isEmpty { BadgeView(text: value.displayString, tone: "accent") }122        } else {123            Text(CellFormat.text(value, format: column.format, runtime: runtime))124                .monospacedDigit()125                .lineLimit(1)126                .truncationMode(.tail)127        }128    }129130    private func toggleSort(_ key: String) {131        if sort?.column == key { sort = sort?.descending == true ? nil : DataQuery.Sort(column: key, descending: true) }132        else { sort = DataQuery.Sort(column: key, descending: false) }133    }134}135136struct TableComponent: View {137    @Environment(AppRuntime.self) private var runtime138    let o: PrismObject139    @State private var localSelection: Int?140    @State private var sort: DataQuery.Sort?141142    var body: some View {143        let queryJSON = resolvedQuery144        let query = queryJSON.flatMap { try? DataQuery(json: $0) }145        let schema = runtime.schema(query?.table)146        let rows = runtime.rows(queryJSON, sort: sort)147        let bound = runtime.bindingPath(o.props["selection"])148        DataGrid(149            columns: CellFormat.columns(o.props["columns"], query: query, schema: schema), rows: rows,150            selection: Binding(151                get: { bound != nil ? runtime.resolve(o.props["selection"]).intValue : localSelection },152                set: { new in153                    localSelection = new154                    if let bound { runtime.setState(bound, new.map(JSONValue.int) ?? .null) }155                    if let new, let row = rows.first(where: { $0["id"]?.intValue == new }) { runtime.fire("select", on: o.id, value: .int(new), row: .object(row)) }156                }157            ),158            sort: $sort, sortable: o.props["sortable"]?.boolValue != false,159            emptyTitle: o.props["emptyTitle"].map { runtime.string($0) } ?? "No rows",160            emptyMessage: o.props["emptyMessage"].map { runtime.string($0) } ?? "Nothing matches yet."161        )162        .accessibilityLabel(o.name.isEmpty ? "Table" : o.name)163    }164165    private var resolvedQuery: JSONValue? {166        guard let q = o.props["query"] else { return nil }167        if let ref = q["$ref"]?.stringValue { return runtime.blueprint.object(ref)?.props["query"] }168        return q169    }170}171172struct CSVImportComponent: View {173    @Environment(AppRuntime.self) private var runtime174    let o: PrismObject175176    var body: some View {177        Button {178            guard let table = o.props["table"]?.stringValue, let report = runtime.importCSV(into: table) else { return }179            runtime.fire("imported", on: o.id, value: .int(report.imported))180        } label: { Label(o.props["title"].map { runtime.string($0) } ?? "Import CSV…", systemImage: "square.and.arrow.down") }181        .disabled(runtime.dialogs == nil)182        .help(runtime.dialogs == nil ? "File dialogs are not available in this context." : "Import rows from a CSV file")183    }184}185186struct CSVExportComponent: View {187    @Environment(AppRuntime.self) private var runtime188    let o: PrismObject189190    var body: some View {191        Button {192            guard let query = o.props["query"], runtime.exportCSV(query: query, suggestedName: o.props["filename"]?.stringValue ?? "export.csv") != nil else { return }193            runtime.fire("exported", on: o.id)194        } label: { Label(o.props["title"].map { runtime.string($0) } ?? "Export CSV…", systemImage: "square.and.arrow.up") }195        .disabled(runtime.dialogs == nil)196        .help(runtime.dialogs == nil ? "File dialogs are not available in this context." : "Save these rows as a CSV file")197    }198}199200/// The editable form for one record. Used by the record editor component and by the record manager's sheet.201struct RecordForm: View {202    @Environment(AppRuntime.self) private var runtime203    let table: String204    let recordID: Int?205    var fields: [String]?206    var submitTitle = "Save"207    var allowDelete = true208    var onSaved: (Int) -> Void = { _ in }209    var onDeleted: () -> Void = {}210    var onCancelled: (() -> Void)?211212    @State private var draft: [String: JSONValue] = [:]213    @State private var loadedFor: String?214    @State private var error: String?215    @State private var confirmDelete = false216217    private var columns: [ColumnSchema] {218        guard let schema = runtime.schema(table) else { return [] }219        guard let fields else { return schema.columns }220        return fields.compactMap(schema.column)221    }222223    var body: some View {224        VStack(alignment: .leading, spacing: 12) {225            if runtime.schema(table) == nil {226                Label("Table “\(table)” does not exist.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)227            }228            ForEach(columns, id: \.name) { column in field(column) }229            if let error { Label(error, systemImage: "exclamationmark.circle").foregroundStyle(.red).font(.callout) }230            HStack {231                if recordID != nil && allowDelete {232                    Button("Delete", role: .destructive) { confirmDelete = true }233                }234                Spacer()235                if let onCancelled { Button("Cancel") { onCancelled() }.keyboardShortcut(.cancelAction) }236                Button(submitTitle) { save() }.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction)237            }238        }239        .onAppear(perform: load)240        .onChange(of: recordID) { _, _ in load() }241        .confirmationDialog("Delete this record?", isPresented: $confirmDelete) {242            Button("Delete", role: .destructive) {243                guard let recordID else { return }244                if runtime.write("Deleting", { try runtime.store.delete(from: table, id: recordID) }) { onDeleted() }245            }246        } message: { Text("This cannot be undone.") }247    }248249    private func load() {250        let key = "\(table)#\(recordID.map(String.init) ?? "new")"251        guard loadedFor != key else { return }252        loadedFor = key253        error = nil254        if let recordID, let record = try? runtime.store.record(table, id: recordID) {255            draft = record256        } else {257            draft = [:]258            for c in runtime.schema(table)?.columns ?? [] {259                if let d = c.defaultValue { draft[c.name] = d } else if c.type == .date { draft[c.name] = .string(LocalDate.iso(Date())) }260            }261        }262    }263264    private func save() {265        var values: [String: JSONValue] = [:]266        for c in columns { values[c.name] = draft[c.name] ?? .null }267        do {268            if let recordID {269                try runtime.store.update(table, id: recordID, values: values)270                _ = runtime.write("Saving") {}271                onSaved(recordID)272            } else {273                let id = try runtime.store.insert(into: table, values: values)274                _ = runtime.write("Saving") {}275                loadedFor = nil276                load()277                onSaved(id)278            }279            error = nil280        } catch let e {281            error = e.localizedDescription282        }283    }284285    private func text(_ name: String) -> Binding<String> {286        Binding(get: { draft[name]?.displayString ?? "" }, set: { draft[name] = .string($0) })287    }288289    @ViewBuilder290    private func field(_ c: ColumnSchema) -> some View {291        let label = c.label + (c.required ? " *" : "")292        switch c.type {293        case .boolean:294            Toggle(c.label, isOn: Binding(get: { draft[c.name]?.isTruthy ?? false }, set: { draft[c.name] = .bool($0) }))295        case .date:296            Labeled(label: label) {297                DatePicker("", selection: Binding(298                    get: { LocalDate.date(draft[c.name]?.displayString ?? "") ?? Date() },299                    set: { draft[c.name] = .string(LocalDate.iso($0)) }300                ), displayedComponents: .date).labelsHidden()301            }302        case .text where !c.options.isEmpty:303            Labeled(label: label) {304                Picker(c.label, selection: text(c.name)) {305                    if !c.options.contains(draft[c.name]?.displayString ?? "") { Text(draft[c.name]?.displayString.isEmpty == false ? draft[c.name]!.displayString : "Choose…").tag(draft[c.name]?.displayString ?? "") }306                    ForEach(c.options, id: \.self) { Text($0).tag($0) }307                }.labelsHidden().fixedSize()308            }309        case .text:310            Labeled(label: label) { TextField("", text: text(c.name)).textFieldStyle(.roundedBorder) }311        case .number, .integer, .currency:312            Labeled(label: label) {313                TextField("", text: text(c.name), prompt: Text(c.type == .currency ? "0.00" : "0"))314                    .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(maxWidth: 180)315            }316        }317    }318}319320struct RecordEditorComponent: View {321    @Environment(AppRuntime.self) private var runtime322    let o: PrismObject323324    var body: some View {325        let hasCancel = !(o.events["cancelled"] ?? []).isEmpty326        RecordForm(327            table: o.props["table"]?.stringValue ?? "", recordID: runtime.resolve(o.props["recordId"]).intValue,328            fields: o.props["fields"]?.arrayValue?.compactMap(\.stringValue),329            submitTitle: o.props["submitTitle"].map { runtime.string($0) } ?? "Save", allowDelete: o.props["allowDelete"]?.boolValue != false,330            onSaved: { runtime.fire("saved", on: o.id, value: .int($0)) },331            onDeleted: {332                if let path = runtime.bindingPath(o.props["recordId"]) { runtime.setState(path, .null) }333                runtime.fire("deleted", on: o.id)334            },335            onCancelled: hasCancel ? { runtime.fire("cancelled", on: o.id) } : nil336        )337        .frame(maxWidth: 520, alignment: .leading)338    }339}340341struct CrudComponent: View {342    @Environment(AppRuntime.self) private var runtime343    @Environment(\.prismTheme) private var theme344    let o: PrismObject345    @State private var selection: Int?346    @State private var sort: DataQuery.Sort?347    @State private var editing: EditTarget?348349    struct EditTarget: Identifiable { let id: Int; var recordID: Int? { id < 0 ? nil : id } }350351    var body: some View {352        let table = o.props["table"]?.stringValue ?? ""353        let schema = runtime.schema(table)354        let rows = runtime.rows(["table": .string(table)], sort: sort)355        let canEdit = o.props["allowEdit"]?.boolValue != false356        VStack(alignment: .leading, spacing: 8) {357            HStack {358                Text(o.props["title"].map { runtime.string($0) } ?? schema?.title ?? table).font(.headline).accessibilityAddTraits(.isHeader)359                Text("\(rows.count)").font(.caption).foregroundStyle(.secondary).accessibilityLabel("\(rows.count) records")360                Spacer()361                if canEdit { Button("Edit") { if let selection { editing = EditTarget(id: selection) } }.disabled(selection == nil) }362                if o.props["allowAdd"]?.boolValue != false {363                    Button { editing = EditTarget(id: -1) } label: { Label("Add", systemImage: "plus") }364                }365            }366            DataGrid(367                columns: CellFormat.columns(o.props["columns"], query: nil, schema: schema), rows: rows, selection: $selection, sort: $sort,368                emptyTitle: "No records", emptyMessage: "Add the first one with the Add button.",369                onActivate: { if canEdit { editing = EditTarget(id: $0) } }370            )371        }372        .sheet(item: $editing) { target in373            VStack(alignment: .leading, spacing: 12) {374                Text(target.recordID == nil ? "New record" : "Edit record").font(.title3.bold())375                RecordForm(376                    table: table, recordID: target.recordID, allowDelete: o.props["allowDelete"]?.boolValue != false,377                    onSaved: { id in editing = nil; selection = id; runtime.fire("saved", on: o.id, value: .int(id)) },378                    onDeleted: { editing = nil; selection = nil; runtime.fire("deleted", on: o.id) },379                    onCancelled: { editing = nil }380                )381            }382            .padding(20)383            .frame(minWidth: 420)384            .environment(runtime)385            .environment(\.prismTheme, theme)386        }387    }388}389390struct AggregationComponent: View {391    @Environment(AppRuntime.self) private var runtime392    @Environment(\.prismTheme) private var theme393    let o: PrismObject394395    private var value: JSONValue {396        if let query = o.props["query"] {397            let row = runtime.rows(query["$ref"]?.stringValue.flatMap { runtime.blueprint.object($0)?.props["query"] } ?? query).first ?? [:]398            if let column = o.props["valueColumn"]?.stringValue { return row[column] ?? .null }399            return row.sorted { $0.key < $1.key }.first?.value ?? .null400        }401        return runtime.resolve(o.props["value"])402    }403404    var body: some View {405        let tone = runtime.string(o.props["tone"])406        let label = runtime.string(o.props["label"])407        let shown = CellFormat.text(value, format: o.props["format"]?.stringValue ?? "number", runtime: runtime)408        HStack(alignment: .center, spacing: 12) {409            if let icon = o.props["icon"] {410                Image(systemName: SymbolName.safe(runtime.string(icon))).font(.title2).foregroundStyle(theme.tint(tone.isEmpty ? "accent" : tone)).frame(width: 30).accessibilityHidden(true)411            }412            VStack(alignment: .leading, spacing: 2) {413                Text(label).font(.callout).foregroundStyle(.secondary)414                Text(shown.isEmpty ? "—" : shown).font(.title2.weight(.semibold)).monospacedDigit().foregroundStyle(theme.color(tone)).lineLimit(1).minimumScaleFactor(0.6)415            }416            Spacer(minLength: 0)417        }418        .padding(14)419        .frame(maxWidth: .infinity, alignment: .leading)420        .prismSurface()421        .accessibilityElement(children: .ignore)422        .accessibilityLabel(label)423        .accessibilityValue(shown.isEmpty ? "No value" : shown)424    }425}426
Files main
Menu

Theme