Repository Public License
1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67/// A row with a stable identity for `ForEach`: the record id, or the position for grouped rows.8struct FCItem: Identifiable {9 let id: Int10 let index: Int11 let row: FCRow1213 @MainActor static func list(_ rows: [FCRow], cap: Int = FC.rowCap) -> [FCItem] {14 rows.prefix(max(1, cap)).enumerated().map { FCItem(id: $0.element["id"]?.intValue ?? -1 - $0.offset, index: $0.offset, row: $0.element) }15 }16}1718/// Cells laid out in equal flexible columns, used for headers and rows alike so they line up.19struct FCColumnsRow: View {20 let cells: [(text: String, trailing: Bool)]21 var header = false2223 var body: some View {24 HStack(spacing: 12) {25 ForEach(cells.indices, id: \.self) { i in26 Text(cells[i].text)27 .font(header ? .caption.weight(.semibold) : .body)28 .foregroundStyle(header ? AnyShapeStyle(.secondary) : AnyShapeStyle(.primary))29 .monospacedDigit().lineLimit(1).truncationMode(.tail)30 .frame(maxWidth: .infinity, alignment: cells[i].trailing ? .trailing : .leading)31 }32 }33 }34}3536extension FCSource {37 func text(_ row: FCRow, _ column: String?, runtime: AppRuntime, format: String? = nil) -> String {38 guard let column, !column.isEmpty else { return "" }39 return CellFormat.text(row[column] ?? .null, format: self.format(column, override: format), runtime: runtime)40 }4142 func isNumeric(_ column: String) -> Bool { ["number", "currency", "percent"].contains(format(column)) }43}4445// MARK: Pivot4647struct FCPivot: View {48 @Environment(AppRuntime.self) private var runtime49 let o: PrismObject5051 var body: some View {52 let row = FC.column(o, "row"), column = FC.column(o, "column"), value = FC.column(o, "valueColumn")53 let fn = o.props["aggregate"]?.stringValue ?? (value == nil ? "count" : "sum")54 let source = FC.source(runtime, o, columns: [row, column, value])55 .orProblem(row == nil || column == nil, "Set `row` and `column` to columns of the query.")56 .orProblem(value == nil && fn != "count", "`\(fn)` needs a `valueColumn`.")57 let pivot = FamilyCMath.pivot(source.rows, row: row ?? "", column: column ?? "", value: value, fn: fn)58 let format = o.props["format"]?.stringValue ?? (fn == "count" ? "number" : value.map { source.format($0) } ?? "number")59 let text: (Double?) -> String = { v in v.map { FC.number(runtime, $0, format) } ?? "" }60 let totals = o.props["showTotals"]?.boolValue != false61 let rowKeys = Array(pivot.rowKeys.prefix(FC.rowCap)), columnKeys = Array(pivot.columnKeys.prefix(24))62 FCPanel(63 title: runtime.string(o.props["title"]), fallbackLabel: "Pivot table", problem: source.problem, isEmpty: source.rows.isEmpty, emptySymbol: "tablecells",64 summary: "\(pivot.rowKeys.count) rows by \(pivot.columnKeys.count) columns, \(fn). Overall: \(text(pivot.grandTotal))."65 ) {66 ScrollView(.horizontal) {67 Grid(alignment: .trailing, horizontalSpacing: 18, verticalSpacing: 6) {68 GridRow {69 Text(row.map { source.title($0) } ?? "").gridColumnAlignment(.leading)70 ForEach(columnKeys, id: \.self) { Text($0.isEmpty ? "(none)" : $0) }71 if totals { Text("Total") }72 }73 .font(.caption.weight(.semibold)).foregroundStyle(.secondary)74 Divider()75 ForEach(rowKeys, id: \.self) { rk in76 GridRow {77 Text(rk.isEmpty ? "(none)" : rk)78 ForEach(columnKeys, id: \.self) { ck in Text(text(pivot.cell(rk, ck))).accessibilityLabel("\(rk), \(ck): \(text(pivot.cell(rk, ck)))") }79 if totals { Text(text(pivot.rowTotals[rk])).fontWeight(.semibold) }80 }81 }82 if totals {83 Divider()84 GridRow {85 Text("Total")86 ForEach(columnKeys, id: \.self) { Text(text(pivot.columnTotals[$0])) }87 Text(text(pivot.grandTotal))88 }89 .fontWeight(.semibold)90 }91 }92 .monospacedDigit()93 .padding(.bottom, 4)94 }95 if pivot.columnKeys.count > columnKeys.count { Text("Showing the first \(columnKeys.count) of \(pivot.columnKeys.count) columns.").font(.caption).foregroundStyle(.secondary) }96 FCMoreFooter(shown: rowKeys.count, total: pivot.rowKeys.count)97 }98 }99}100101// MARK: Editable grid102103struct FCDataGrid: View {104 @Environment(AppRuntime.self) private var runtime105 let o: PrismObject106107 var body: some View {108 let table = FC.column(o, "table") ?? ""109 let names = o.props["columns"]?.arrayValue?.compactMap(\.stringValue)110 let source = FC.tableSource(runtime, table: table, columns: names ?? [])111 let columns = (names ?? source.schema?.columns.map(\.name) ?? []).compactMap { source.schema?.column($0) }112 let items = FCItem.list(source.rows, cap: o.props["limit"]?.intValue ?? 100)113 FCPanel(114 title: runtime.string(o.props["title"]), fallbackLabel: "Editable grid", problem: source.problem, isEmpty: source.rows.isEmpty,115 emptyTitle: "No records", emptyMessage: "Rows appear here once the table has records.", emptySymbol: "tablecells",116 summary: "\(source.rows.count) records, \(columns.count) editable columns.", trailing: "\(source.rows.count) record\(source.rows.count == 1 ? "" : "s")"117 ) {118 Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 5) {119 GridRow {120 ForEach(columns, id: \.name) { c in121 Text(c.label).font(.caption.weight(.semibold)).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: c.type.isNumeric ? .trailing : .leading)122 }123 }124 ForEach(items) { item in125 GridRow {126 ForEach(columns, id: \.name) { c in127 FCGridCell(objectID: o.id, table: table, recordID: item.id, column: c, value: item.row[c.name] ?? .null)128 }129 }130 }131 }132 FCMoreFooter(shown: items.count, total: source.rows.count)133 }134 }135}136137/// One editable cell: committing (Return, or leaving the field) updates the record; a rejected value is reported and reverted.138struct FCGridCell: View {139 @Environment(AppRuntime.self) private var runtime140 let objectID: String141 let table: String142 let recordID: Int143 let column: ColumnSchema144 let value: JSONValue145 @State private var text = ""146 @FocusState private var focused: Bool147148 var body: some View {149 let name = "\(column.label), record \(recordID)"150 switch column.type {151 case .boolean:152 Toggle(column.label, isOn: Binding(get: { value.isTruthy }, set: { commit(.bool($0)) })).labelsHidden().accessibilityLabel(name)153 case .text where !column.options.isEmpty:154 Picker(column.label, selection: Binding(get: { value.displayString }, set: { commit(.string($0)) })) {155 if !column.options.contains(value.displayString) { Text(value.displayString.isEmpty ? "—" : value.displayString).tag(value.displayString) }156 ForEach(column.options, id: \.self) { Text($0).tag($0) }157 }158 .labelsHidden().accessibilityLabel(name)159 default:160 TextField(column.label, text: $text)161 .textFieldStyle(.roundedBorder)162 .multilineTextAlignment(column.type.isNumeric ? .trailing : .leading)163 .focused($focused)164 .onSubmit(commitText)165 .onChange(of: focused) { _, isFocused in if !isFocused { commitText() } }166 .onAppear { text = value.displayString }167 .onChange(of: value) { _, new in text = new.displayString }168 .accessibilityLabel(name)169 }170 }171172 private func commitText() {173 guard text != value.displayString else { return }174 if !commit(.string(text)) { text = value.displayString }175 }176177 @discardableResult178 private func commit(_ new: JSONValue) -> Bool {179 let ok = runtime.write("Saving") { try runtime.store.update(table, id: recordID, values: [column.name: new]) }180 if ok { runtime.fire("saved", on: objectID, value: .int(recordID), row: (try? runtime.store.record(table, id: recordID)).flatMap { $0 }.map(JSONValue.object)) }181 return ok182 }183}184185// MARK: Cards, gallery186187struct FCCardList: View {188 @Environment(AppRuntime.self) private var runtime189 @Environment(\.prismTheme) private var theme190 let o: PrismObject191 @State private var local: Int?192193 var body: some View {194 let title = FC.column(o, "titleColumn"), subtitle = FC.column(o, "subtitleColumn"), badge = FC.column(o, "badgeColumn"), value = FC.column(o, "valueColumn")195 let source = FC.source(runtime, o, columns: [title, subtitle, badge, value], sort: FC.sort(runtime, o.props["sort"]))196 let selection = FCSelection(runtime: runtime, o: o, local: $local)197 let items = FCItem.list(source.rows)198 if source.problem != nil || items.isEmpty {199 FCPanel(fallbackLabel: "Cards", problem: source.problem ?? (title == nil ? "Set `titleColumn` to a column of the query." : nil), isEmpty: true,200 emptyTitle: o.props["emptyText"].map { runtime.string($0) } ?? "Nothing to show", emptyMessage: "") { EmptyView() }201 } else {202 VStack(alignment: .leading, spacing: 8) {203 ForEach(items) { item in204 let heading = source.text(item.row, title, runtime: runtime), sub = source.text(item.row, subtitle, runtime: runtime)205 let amount = source.text(item.row, value, runtime: runtime, format: o.props["format"]?.stringValue), tag = source.text(item.row, badge, runtime: runtime)206 Button { selection.select(item.row) } label: {207 HStack(alignment: .center, spacing: 10) {208 VStack(alignment: .leading, spacing: 2) {209 Text(heading.isEmpty ? "(untitled)" : heading).font(.headline).lineLimit(1)210 if !sub.isEmpty { Text(sub).font(.callout).foregroundStyle(.secondary).lineLimit(2) }211 }212 Spacer(minLength: 8)213 if !tag.isEmpty { BadgeView(text: tag, tone: "accent") }214 if !amount.isEmpty { Text(amount).font(.title3.weight(.semibold)).monospacedDigit().lineLimit(1) }215 }216 .padding(.horizontal, 14).padding(.vertical, 10)217 .frame(maxWidth: .infinity, alignment: .leading)218 .prismSurface()219 .overlay(RoundedRectangle(cornerRadius: theme.radius, style: .continuous).strokeBorder(theme.accent, lineWidth: selection.isSelected(item.row) ? 2 : 0))220 .contentShape(Rectangle())221 }222 .buttonStyle(.plain)223 .accessibilityLabel([heading, sub, tag, amount].filter { !$0.isEmpty }.joined(separator: ", "))224 .accessibilityAddTraits(selection.isSelected(item.row) ? [.isSelected] : [])225 }226 FCMoreFooter(shown: items.count, total: source.rows.count)227 }228 .frame(maxWidth: .infinity, alignment: .leading)229 }230 }231}232233struct FCGallery: View {234 @Environment(AppRuntime.self) private var runtime235 @Environment(\.prismTheme) private var theme236 let o: PrismObject237 @State private var local: Int?238239 var body: some View {240 let title = FC.column(o, "titleColumn"), caption = FC.column(o, "captionColumn"), symbolColumn = FC.column(o, "symbolColumn")241 let source = FC.source(runtime, o, columns: [title, caption, symbolColumn])242 let selection = FCSelection(runtime: runtime, o: o, local: $local)243 let items = FCItem.list(source.rows)244 let fixedSymbol = runtime.string(o.props["symbol"])245 let perRow = min(max(o.props["tilesPerRow"]?.intValue ?? 4, 1), 12)246 let palette = FC.palette(theme)247 if source.problem != nil || items.isEmpty {248 FCPanel(fallbackLabel: "Gallery", problem: source.problem ?? (title == nil ? "Set `titleColumn` to a column of the query." : nil), isEmpty: true, emptyTitle: "Nothing to show", emptyMessage: "", emptySymbol: "square.grid.2x2") { EmptyView() }249 } else {250 VStack(alignment: .leading, spacing: 8) {251 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10, alignment: .top), count: perRow), spacing: 10) {252 ForEach(items) { item in253 let heading = source.text(item.row, title, runtime: runtime), sub = source.text(item.row, caption, runtime: runtime)254 let symbol = symbolColumn.map { item.row[$0]?.displayString ?? "" } ?? fixedSymbol255 Button { selection.select(item.row) } label: {256 VStack(spacing: 6) {257 FCAvatar(name: heading, symbol: symbol.isEmpty ? nil : symbol, color: palette[item.index % palette.count], size: 44)258 Text(heading.isEmpty ? "(untitled)" : heading).font(.callout.weight(.medium)).lineLimit(1)259 if !sub.isEmpty { Text(sub).font(.caption).foregroundStyle(.secondary).lineLimit(1) }260 }261 .padding(10)262 .frame(maxWidth: .infinity)263 .prismSurface()264 .overlay(RoundedRectangle(cornerRadius: theme.radius, style: .continuous).strokeBorder(theme.accent, lineWidth: selection.isSelected(item.row) ? 2 : 0))265 .contentShape(Rectangle())266 }267 .buttonStyle(.plain)268 .accessibilityLabel(sub.isEmpty ? heading : "\(heading), \(sub)")269 .accessibilityAddTraits(selection.isSelected(item.row) ? [.isSelected] : [])270 }271 }272 FCMoreFooter(shown: items.count, total: source.rows.count)273 }274 }275 }276}277278// MARK: One record279280@MainActor281private func fcRecord(_ runtime: AppRuntime, _ o: PrismObject, columns: [String?]) -> (source: FCSource, id: Int?, row: FCRow?) {282 let id = runtime.resolve(o.props["recordId"]).intValue283 guard let id else { return (FC.tableSource(runtime, table: FC.column(o, "table"), columns: columns, filter: ("id", .int(-1))), nil, nil) }284 let source = FC.tableSource(runtime, table: FC.column(o, "table"), columns: columns, filter: ("id", .int(id)))285 return (source, id, source.rows.first)286}287288struct FCRecordDetail: View {289 @Environment(AppRuntime.self) private var runtime290 let o: PrismObject291292 var body: some View {293 let fields = o.props["fields"]?.arrayValue?.compactMap(\.stringValue)294 let record = fcRecord(runtime, o, columns: fields ?? [])295 let columns = (fields ?? record.source.schema?.columns.map(\.name) ?? []).compactMap { record.source.schema?.column($0) }296 FCPanel(297 title: runtime.string(o.props["title"]), fallbackLabel: "Record details", problem: record.source.problem, isEmpty: record.row == nil,298 emptyTitle: record.id == nil ? (o.props["emptyText"].map { runtime.string($0) } ?? "No record selected") : "Record \(record.id ?? 0) was not found",299 emptyMessage: "", emptySymbol: "doc.text.magnifyingglass",300 summary: columns.map { "\($0.label): \(record.source.text(record.row ?? [:], $0.name, runtime: runtime))" }.joined(separator: "; ")301 ) {302 Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 7) {303 ForEach(columns, id: \.name) { c in304 let shown = record.source.text(record.row ?? [:], c.name, runtime: runtime)305 GridRow {306 Text(c.label).foregroundStyle(.secondary).gridColumnAlignment(.leading)307 Text(shown.isEmpty ? "—" : shown).monospacedDigit().textSelection(.enabled).fixedSize(horizontal: false, vertical: true)308 }309 .accessibilityElement(children: .combine)310 }311 }312 }313 }314}315316struct FCRecordCard: View {317 @Environment(AppRuntime.self) private var runtime318 @Environment(\.prismTheme) private var theme319 let o: PrismObject320321 var body: some View {322 let title = FC.column(o, "titleColumn"), subtitle = FC.column(o, "subtitleColumn"), value = FC.column(o, "valueColumn"), badge = FC.column(o, "badgeColumn")323 let record = fcRecord(runtime, o, columns: [title, subtitle, value, badge])324 let row = record.row ?? [:]325 let heading = record.source.text(row, title, runtime: runtime), sub = record.source.text(row, subtitle, runtime: runtime)326 let amount = record.source.text(row, value, runtime: runtime), tag = record.source.text(row, badge, runtime: runtime)327 let symbol = runtime.string(o.props["symbol"])328 FCPanel(329 fallbackLabel: "Record", problem: record.source.problem ?? (title == nil ? "Set `titleColumn` to a column of the table." : nil), isEmpty: record.row == nil,330 emptyTitle: record.id == nil ? "No record selected" : "Record \(record.id ?? 0) was not found", emptyMessage: "", emptySymbol: "doc",331 summary: [heading, sub, tag, amount].filter { !$0.isEmpty }.joined(separator: ", ")332 ) {333 HStack(spacing: 12) {334 FCAvatar(name: heading, symbol: symbol.isEmpty ? nil : symbol, color: theme.accent, size: 40)335 VStack(alignment: .leading, spacing: 2) {336 Text(heading.isEmpty ? "(untitled)" : heading).font(.headline).lineLimit(1)337 if !sub.isEmpty { Text(sub).font(.callout).foregroundStyle(.secondary).lineLimit(1) }338 }339 Spacer(minLength: 8)340 if !tag.isEmpty { BadgeView(text: tag, tone: "accent") }341 if !amount.isEmpty { Text(amount).font(.title3.weight(.semibold)).monospacedDigit().lineLimit(1) }342 }343 }344 }345}346347struct FCLookup: View {348 @Environment(AppRuntime.self) private var runtime349 let o: PrismObject350351 var body: some View {352 let labelColumn = FC.column(o, "labelColumn")353 let source = FC.tableSource(runtime, table: FC.column(o, "table"), columns: [labelColumn])354 let options = source.rows.compactMap { row in row["id"]?.intValue.map { (id: $0, label: source.text(row, labelColumn, runtime: runtime), row: row) } }355 .sorted { $0.label.localizedCaseInsensitiveCompare($1.label) == .orderedAscending }356 let current = runtime.resolve(o.props["value"]).intValue357 let label = runtime.string(o.props["label"])358 let placeholder = o.props["placeholder"].map { runtime.string($0) } ?? "Choose…"359 Labeled(label: label) {360 if let problem = source.problem ?? (labelColumn == nil ? "Set `labelColumn` to a column of the table." : nil) {361 Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)362 } else {363 Picker(label.isEmpty ? "Record" : label, selection: Binding<Int?>(364 get: { current.flatMap { id in options.contains { $0.id == id } ? id : nil } },365 set: { new in366 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, new.map(JSONValue.int) ?? .null) }367 runtime.fire("change", on: o.id, value: new.map(JSONValue.int) ?? .null, row: options.first { $0.id == new }.map { .object($0.row) })368 }369 )) {370 Text(options.isEmpty ? "No records" : placeholder).tag(Int?.none)371 ForEach(options, id: \.id) { Text($0.label.isEmpty ? "#\($0.id)" : $0.label).tag(Int?.some($0.id)) }372 }373 .labelsHidden()374 .fixedSize()375 .disabled(options.isEmpty)376 }377 }378 }379}380381struct FCRelatedList: View {382 @Environment(AppRuntime.self) private var runtime383 let o: PrismObject384385 var body: some View {386 let foreignKey = FC.column(o, "foreignKey")387 let names = o.props["columns"]?.arrayValue?.compactMap(\.stringValue)388 let parent = runtime.resolve(o.props["parentId"])389 let source: FCSource = foreignKey == nil ? FCSource(problem: "Set `foreignKey` to the column that holds the parent's id.")390 : FC.tableSource(runtime, table: FC.column(o, "table"), columns: names ?? [], filter: (foreignKey ?? "", parent.isNull ? .int(-1) : parent))391 let columns = names ?? (source.schema?.columns.map(\.name) ?? []).filter { $0 != foreignKey }392 let items = FCItem.list(parent.isNull ? [] : source.rows)393 FCPanel(394 title: runtime.string(o.props["title"]), fallbackLabel: "Related records", problem: source.problem, isEmpty: items.isEmpty,395 emptyTitle: parent.isNull ? "Nothing selected" : (o.props["emptyText"].map { runtime.string($0) } ?? "No related records"), emptyMessage: "", emptySymbol: "link",396 summary: "\(source.rows.count) related records.", trailing: items.isEmpty ? "" : "\(source.rows.count)"397 ) {398 VStack(alignment: .leading, spacing: 0) {399 FCColumnsRow(cells: columns.map { (source.title($0), source.isNumeric($0)) }, header: true).padding(.horizontal, 10).padding(.bottom, 4)400 Divider()401 ForEach(items) { item in402 let cells = columns.map { (text: source.text(item.row, $0, runtime: runtime), trailing: source.isNumeric($0)) }403 FCRowButton(selected: false, accessibility: cells.map(\.text).joined(separator: ", "), action: {404 runtime.fire("select", on: o.id, value: item.row["id"] ?? .null, row: .object(item.row))405 }) { FCColumnsRow(cells: cells) }406 }407 FCMoreFooter(shown: items.count, total: source.rows.count)408 }409 }410 }411}412413struct FCCountBadge: View {414 @Environment(AppRuntime.self) private var runtime415 @Environment(\.prismTheme) private var theme416 let o: PrismObject417418 var body: some View {419 let source = FC.source(runtime, o)420 let count = source.rows.count421 let label = runtime.string(o.props["label"])422 let tone = runtime.string(o.props["tone"])423 let color = theme.tint(tone.isEmpty ? "accent" : tone)424 if let problem = source.problem {425 Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)426 } else if count > 0 || o.props["hideWhenZero"]?.boolValue != true {427 HStack(spacing: 5) {428 if let icon = o.props["icon"] { Image(systemName: SymbolName.safe(runtime.string(icon), fallback: "number")).font(.caption) }429 Text(count.formatted(.number.locale(runtime.locale))).font(.callout.weight(.semibold)).monospacedDigit()430 if !label.isEmpty { Text(label).font(.callout) }431 }432 .padding(.horizontal, 10).padding(.vertical, 3)433 .foregroundStyle(color)434 .background(color.opacity(0.14), in: Capsule())435 .accessibilityElement(children: .ignore)436 .accessibilityLabel(label.isEmpty ? "Count" : label)437 .accessibilityValue("\(count)")438 }439 }440}441442struct FCGroupedList: View {443 @Environment(AppRuntime.self) private var runtime444 let o: PrismObject445 @State private var local: Int?446447 var body: some View {448 let group = FC.column(o, "groupColumn"), title = FC.column(o, "titleColumn"), detail = FC.column(o, "detailColumn")449 let source = FC.source(runtime, o, columns: [group, title, detail]).orProblem(group == nil || title == nil, "Set `groupColumn` and `titleColumn` to columns of the query.")450 let selection = FCSelection(runtime: runtime, o: o, local: $local)451 let groups = FamilyCMath.group(Array(source.rows.prefix(FC.rowCap)), by: group ?? "")452 FCPanel(453 title: runtime.string(o.props["title"]), fallbackLabel: "Grouped list", problem: source.problem, isEmpty: source.rows.isEmpty, emptyTitle: "Nothing to show", emptyMessage: "",454 emptySymbol: "list.bullet.indent", summary: groups.map { "\($0.key.isEmpty ? "(none)" : $0.key): \($0.rows.count)" }.joined(separator: "; ")455 ) {456 VStack(alignment: .leading, spacing: 2) {457 ForEach(groups, id: \.key) { g in458 HStack {459 Text(source.format(group ?? "") == "date" ? CellFormat.text(.string(g.key), format: "date", runtime: runtime) : (g.key.isEmpty ? "(none)" : g.key))460 .font(.subheadline.weight(.semibold)).foregroundStyle(.secondary).accessibilityAddTraits(.isHeader)461 if o.props["showCounts"]?.boolValue != false { Text("\(g.rows.count)").font(.caption).foregroundStyle(.tertiary).monospacedDigit().accessibilityLabel("\(g.rows.count) rows") }462 Spacer(minLength: 0)463 }464 .padding(.top, 8).padding(.horizontal, 10)465 ForEach(FCItem.list(g.rows)) { item in466 let heading = source.text(item.row, title, runtime: runtime), sub = source.text(item.row, detail, runtime: runtime, format: o.props["format"]?.stringValue)467 FCRowButton(selected: selection.isSelected(item.row), accessibility: sub.isEmpty ? heading : "\(heading), \(sub)", action: { selection.select(item.row) }) {468 HStack {469 Text(heading.isEmpty ? "(untitled)" : heading).lineLimit(1)470 Spacer(minLength: 8)471 if !sub.isEmpty { Text(sub).foregroundStyle(.secondary).monospacedDigit().lineLimit(1) }472 }473 }474 }475 }476 FCMoreFooter(shown: min(source.rows.count, FC.rowCap), total: source.rows.count)477 }478 }479 }480}481482struct FCLeaderboard: View {483 @Environment(AppRuntime.self) private var runtime484 @Environment(\.prismTheme) private var theme485 let o: PrismObject486487 var body: some View {488 let label = FC.column(o, "labelColumn"), value = FC.column(o, "valueColumn")489 let source = FC.source(runtime, o, columns: [label, value]).orProblem(label == nil || value == nil, "Set `labelColumn` and `valueColumn` to columns of the query.")490 let highestFirst = o.props["descending"]?.boolValue != false491 let ranked = FamilyCMath.leaderboard(source.rows, value: value ?? "", highestFirst: highestFirst, limit: o.props["limit"]?.intValue ?? 10)492 let format = source.format(value ?? "", override: o.props["format"]?.stringValue)493 let medals: [Color] = [Color(red: 0.85, green: 0.65, blue: 0.13), Color(white: 0.62), Color(red: 0.72, green: 0.45, blue: 0.2)]494 FCPanel(495 title: runtime.string(o.props["title"]), fallbackLabel: "Leaderboard", problem: source.problem, isEmpty: ranked.isEmpty, emptyTitle: "No ranking yet", emptyMessage: "",496 emptySymbol: "trophy", summary: ranked.enumerated().map { "\($0.offset + 1). \(source.text($0.element.row, label, runtime: runtime)): \(FC.number(runtime, $0.element.value, format))" }.joined(separator: "; ")497 ) {498 VStack(alignment: .leading, spacing: 6) {499 ForEach(Array(ranked.enumerated()), id: \.offset) { rank, entry in500 HStack(spacing: 10) {501 Group {502 if rank < 3 { Image(systemName: "medal.fill").foregroundStyle(medals[rank]).font(.title3) }503 else { Text("\(rank + 1)").font(.callout.weight(.medium)).foregroundStyle(.secondary).monospacedDigit() }504 }505 .frame(width: 26)506 .accessibilityLabel("Rank \(rank + 1)")507 Text(FC.label(.string(source.text(entry.row, label, runtime: runtime)))).fontWeight(rank < 3 ? .semibold : .regular).lineLimit(1)508 Spacer(minLength: 8)509 Text(FC.number(runtime, entry.value, format)).monospacedDigit().foregroundStyle(rank == 0 ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.primary))510 }511 .accessibilityElement(children: .combine)512 }513 }514 }515 }516}517518struct FCComparison: View {519 @Environment(AppRuntime.self) private var runtime520 let o: PrismObject521522 var body: some View {523 let ids = (runtime.resolve(o.props["recordIds"]).arrayValue ?? []).compactMap(\.intValue)524 let fields = o.props["fields"]?.arrayValue?.compactMap(\.stringValue)525 let labelColumn = FC.column(o, "labelColumn")526 let table = FC.column(o, "table")527 let query: JSONValue = ["table": .string(table ?? ""), "filters": [["column": "id", "op": "in", "value": .array((ids.isEmpty ? [-1] : ids).map(JSONValue.int))]]]528 let source = table == nil ? FCSource(problem: "This component needs a `table`.") : FC.source(runtime, query: query, columns: (fields ?? []) + [labelColumn])529 let records = Array(ids.compactMap { id in source.rows.first { $0["id"]?.intValue == id } }.prefix(8))530 let columns = (fields ?? source.schema?.columns.map(\.name) ?? []).filter { $0 != labelColumn }531 let heading: (FCRow) -> String = { row in532 let text = source.text(row, labelColumn, runtime: runtime)533 return text.isEmpty ? "#\(row["id"]?.displayString ?? "")" : text534 }535 FCPanel(536 title: runtime.string(o.props["title"]), fallbackLabel: "Comparison", problem: source.problem, isEmpty: records.isEmpty,537 emptyTitle: ids.isEmpty ? "Nothing to compare yet" : "Those records were not found", emptyMessage: ids.isEmpty ? "Choose records to see them side by side." : "", emptySymbol: "rectangle.split.3x1",538 summary: records.map { row in heading(row) + ": " + columns.map { "\(source.title($0)) \(source.text(row, $0, runtime: runtime))" }.joined(separator: ", ") }.joined(separator: "; ")539 ) {540 ScrollView(.horizontal) {541 Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 7) {542 GridRow {543 Text("")544 ForEach(records.indices, id: \.self) { i in Text(heading(records[i])).font(.headline).lineLimit(1) }545 }546 Divider()547 ForEach(columns, id: \.self) { c in548 GridRow {549 Text(source.title(c)).foregroundStyle(.secondary)550 ForEach(records.indices, id: \.self) { i in cell(source, records[i], c, heading: heading(records[i])) }551 }552 }553 }554 .padding(.bottom, 4)555 }556 }557 }558559 private func cell(_ source: FCSource, _ row: FCRow, _ column: String, heading: String) -> some View {560 let shown = source.text(row, column, runtime: runtime)561 return Text(shown.isEmpty ? "—" : shown).monospacedDigit().lineLimit(2)562 .accessibilityLabel("\(heading), \(source.title(column)): \(shown)")563 }564}565566struct FCSummaryRow: View {567 @Environment(AppRuntime.self) private var runtime568 let o: PrismObject569570 struct Entry: Identifiable {571 let id: Int572 var label: String573 var shown: String574 }575576 var body: some View {577 let specs = o.props["items"]?.arrayValue ?? []578 let unknown = specs.first { !FamilyCMath.aggregateFunctions.contains($0["fn"]?.stringValue ?? "count") }579 let source = FC.source(runtime, o, columns: specs.map { $0["column"]?.stringValue })580 .orProblem(specs.isEmpty, "Add `items`: `{label, fn, column}`.")581 .orProblem(unknown != nil, "Unknown aggregate `\(unknown?["fn"]?.displayString ?? "")`. Use sum, count, avg, min or max.")582 let entries = specs.enumerated().map { i, spec -> Entry in583 let fn = spec["fn"]?.stringValue ?? "count", column = spec["column"]?.stringValue584 let value = FamilyCMath.aggregate(rows: source.rows, column: column, fn: fn)585 let format = spec["format"]?.stringValue ?? (fn == "count" ? "number" : column.map { source.format($0) } ?? "number")586 return Entry(id: i, label: runtime.string(spec["label"]), shown: FC.number(runtime, value, format))587 }588 FCPanel(title: runtime.string(o.props["title"]), fallbackLabel: "Summary", problem: source.problem, summary: entries.map { "\($0.label): \($0.shown)" }.joined(separator: "; ")) {589 HStack(alignment: .top, spacing: 0) {590 ForEach(entries) { e in591 if e.id > 0 { Divider().padding(.horizontal, 14) }592 VStack(alignment: .leading, spacing: 2) {593 Text(e.label).font(.caption).foregroundStyle(.secondary).lineLimit(1)594 Text(e.shown).font(.title3.weight(.semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)595 }596 .frame(maxWidth: .infinity, alignment: .leading)597 .accessibilityElement(children: .combine)598 }599 }600 .fixedSize(horizontal: false, vertical: true)601 }602 }603}604