Repository Public License
1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67/// Renderers of catalog family C: data views, charts, commerce and social.8struct FamilyCComponents: View {9 static let chartTypes: Set<String> = [10 "prism.chart.area", "prism.chart.scatter", "prism.chart.stackedBar", "prism.chart.horizontalBar", "prism.chart.multiLine",11 "prism.chart.heatmap", "prism.chart.histogram", "prism.chart.gauge", "prism.chart.radar", "prism.chart.funnel",12 "prism.chart.sparkline", "prism.chart.treemap", "prism.chart.waterfall", "prism.chart.candlestick", "prism.chart.bullet",13 "prism.chart.bubble",14 ]15 static let dataTypes: Set<String> = [16 "prism.pivot", "prism.dataGrid", "prism.cardList", "prism.gallery", "prism.recordDetail", "prism.recordCard", "prism.lookup",17 "prism.relatedList", "prism.countBadge", "prism.groupedList", "prism.leaderboard", "prism.comparison", "prism.summaryRow",18 "prism.filterBar", "prism.sortMenu", "prism.columnStats", "prism.jsonViewer", "prism.recordTimeline", "prism.activityFeed",19 "prism.comments", "prism.chat", "prism.progressList", "prism.dataList", "prism.statGrid", "prism.rankList", "prism.duplicateFinder",20 ]21 static let commerceTypes: Set<String> = [22 "prism.priceTag", "prism.cartSummary", "prism.invoice", "prism.productCard", "prism.quantity", "prism.receipt", "prism.converter",23 "prism.profileCard", "prism.reactionBar", "prism.likeButton", "prism.poll",24 ]25 static let types: Set<String> = chartTypes.union(dataTypes).union(commerceTypes)26 let o: PrismObject2728 var body: some View {29 if Self.chartTypes.contains(o.type) { FamilyCCharts(o: o) }30 else if Self.dataTypes.contains(o.type) { FamilyCDataViews(o: o) }31 else if Self.commerceTypes.contains(o.type) { FamilyCCommerce(o: o) }32 else { UnknownComponent(o: o) }33 }34}3536private struct FamilyCCharts: View {37 let o: PrismObject38 var body: some View {39 switch o.type {40 case "prism.chart.area": FCAreaChart(o: o)41 case "prism.chart.scatter": FCScatterChart(o: o, bubble: false)42 case "prism.chart.bubble": FCScatterChart(o: o, bubble: true)43 case "prism.chart.stackedBar": FCSeriesChart(o: o, lines: false)44 case "prism.chart.multiLine": FCSeriesChart(o: o, lines: true)45 case "prism.chart.horizontalBar": FCHorizontalBarChart(o: o)46 case "prism.chart.heatmap": FCHeatmapChart(o: o)47 case "prism.chart.histogram": FCHistogramChart(o: o)48 case "prism.chart.gauge": FCGaugeChart(o: o)49 case "prism.chart.radar": FCRadarChart(o: o)50 case "prism.chart.funnel": FCFunnelChart(o: o)51 case "prism.chart.sparkline": FCSparklineChart(o: o)52 case "prism.chart.treemap": FCTreemapChart(o: o)53 case "prism.chart.waterfall": FCWaterfallChart(o: o)54 case "prism.chart.candlestick": FCCandlestickChart(o: o)55 case "prism.chart.bullet": FCBulletChart(o: o)56 default: UnknownComponent(o: o)57 }58 }59}6061private struct FamilyCDataViews: View {62 let o: PrismObject63 var body: some View {64 switch o.type {65 case "prism.pivot": FCPivot(o: o)66 case "prism.dataGrid": FCDataGrid(o: o)67 case "prism.cardList": FCCardList(o: o)68 case "prism.gallery": FCGallery(o: o)69 case "prism.recordDetail": FCRecordDetail(o: o)70 case "prism.recordCard": FCRecordCard(o: o)71 case "prism.lookup": FCLookup(o: o)72 case "prism.relatedList": FCRelatedList(o: o)73 case "prism.countBadge": FCCountBadge(o: o)74 case "prism.groupedList": FCGroupedList(o: o)75 case "prism.leaderboard": FCLeaderboard(o: o)76 case "prism.comparison": FCComparison(o: o)77 case "prism.summaryRow": FCSummaryRow(o: o)78 default: FamilyCDataViewsMore(o: o)79 }80 }81}8283private struct FamilyCDataViewsMore: View {84 let o: PrismObject85 var body: some View {86 switch o.type {87 case "prism.filterBar": FCFilterBar(o: o)88 case "prism.sortMenu": FCSortMenu(o: o)89 case "prism.columnStats": FCColumnStats(o: o)90 case "prism.jsonViewer": FCJSONViewer(o: o)91 case "prism.recordTimeline": FCRecordTimeline(o: o)92 case "prism.activityFeed": FCActivityFeed(o: o)93 case "prism.comments": FCThread(o: o, chat: false)94 case "prism.chat": FCThread(o: o, chat: true)95 case "prism.progressList": FCProgressList(o: o)96 case "prism.dataList": FCDataList(o: o)97 case "prism.statGrid": FCStatGrid(o: o)98 case "prism.rankList": FCRankList(o: o)99 case "prism.duplicateFinder": FCDuplicateFinder(o: o)100 default: UnknownComponent(o: o)101 }102 }103}104105private struct FamilyCCommerce: View {106 let o: PrismObject107 var body: some View {108 switch o.type {109 case "prism.priceTag": FCPriceTag(o: o)110 case "prism.cartSummary": FCCartSummary(o: o)111 case "prism.invoice": FCInvoice(o: o)112 case "prism.productCard": FCProductCard(o: o)113 case "prism.quantity": FCQuantity(o: o)114 case "prism.receipt": FCReceipt(o: o)115 case "prism.converter": FCConverter(o: o)116 case "prism.profileCard": FCProfileCard(o: o)117 case "prism.reactionBar": FCReactionBar(o: o)118 case "prism.likeButton": FCLikeButton(o: o)119 case "prism.poll": FCPoll(o: o)120 default: UnknownComponent(o: o)121 }122 }123}124125// MARK: Shared plumbing126127typealias FCRow = [String: JSONValue]128129/// The rows a component reads, with the reason when they cannot be read (shown inline instead of a blank view).130@MainActor131struct FCSource {132 var rows: [FCRow] = []133 var schema: TableSchema?134 var outputs: [String] = []135 var problem: String?136137 /// Display format of a column, from the table schema when the column is a stored one.138 func format(_ column: String, override: String? = nil) -> String { override ?? CellFormat.defaultFormat(schema?.column(column)?.type) }139 func title(_ column: String) -> String { schema?.column(column)?.label ?? column.prefix(1).uppercased() + column.dropFirst() }140141 /// The same source with a problem (and no rows) when a condition the validator cannot check does not hold.142 func orProblem(_ condition: Bool, _ message: String) -> FCSource {143 guard problem == nil, condition else { return self }144 return FCSource(schema: schema, outputs: outputs, problem: message)145 }146}147148@MainActor149enum FC {150 /// Rows shown at once by list-like components; the remainder is announced, never silently dropped.151 static let rowCap = 200152153 static func column(_ o: PrismObject, _ prop: String) -> String? {154 guard let s = o.props[prop]?.stringValue, !s.isEmpty else { return nil }155 return s156 }157158 /// Rows of the `query` prop. `columns` are the column names the component reads: a name the query does not produce is reported.159 static func source(_ runtime: AppRuntime, _ o: PrismObject, columns: [String?] = [], sort: DataQuery.Sort? = nil) -> FCSource {160 guard let raw = o.props["query"] else { return FCSource(problem: "This component needs a `query`.") }161 return source(runtime, query: raw, columns: columns, sort: sort)162 }163164 static func source(_ runtime: AppRuntime, query raw: JSONValue, columns: [String?] = [], sort: DataQuery.Sort? = nil) -> FCSource {165 let json = raw["$ref"]?.stringValue.flatMap { runtime.blueprint.object($0)?.props["query"] } ?? raw166 let query: DataQuery167 do { query = try DataQuery(json: json) } catch { return FCSource(problem: "The query is not valid: \(error.localizedDescription)") }168 guard let schema = runtime.schema(query.table) else { return FCSource(problem: "Table “\(query.table)” does not exist.") }169 let outputs = query.outputColumns(schema: schema)170 var out = FCSource(schema: schema, outputs: outputs)171 if let missing = columns.compactMap({ $0 }).first(where: { !outputs.contains($0) }) {172 out.problem = "“\(missing)” is not a column of this query. Available: \(outputs.joined(separator: ", "))."173 return out174 }175 out.rows = runtime.rows(json, sort: sort.flatMap { outputs.contains($0.column) ? $0 : nil })176 return out177 }178179 /// Every row of a table (by id), checking the named columns against its schema.180 static func tableSource(_ runtime: AppRuntime, table: String?, columns: [String?] = [], filter: (column: String, value: JSONValue)? = nil) -> FCSource {181 guard let table, !table.isEmpty else { return FCSource(problem: "This component needs a `table`.") }182 var query: JSONValue = ["table": .string(table)]183 if let filter { query = ["table": .string(table), "filters": [["column": .string(filter.column), "op": "eq", "value": filter.value]]] }184 return source(runtime, query: query, columns: columns + [filter?.column])185 }186187 /// A `{column, descending}` value (usually written by `prism.sortMenu`) as a query sort.188 static func sort(_ runtime: AppRuntime, _ value: JSONValue?) -> DataQuery.Sort? {189 let v = runtime.resolve(value)190 guard let column = v["column"]?.stringValue, !column.isEmpty else { return nil }191 return DataQuery.Sort(column: column, descending: v["descending"]?.isTruthy ?? false)192 }193194 static func number(_ runtime: AppRuntime, _ value: Double?, _ format: String = "number") -> String {195 guard let value else { return "—" }196 return CellFormat.text(.double(value), format: format, runtime: runtime)197 }198199 static func money(_ runtime: AppRuntime, _ value: Double, code: String? = nil) -> String {200 value.formatted(.currency(code: code ?? runtime.currencyCode).locale(runtime.locale))201 }202203 static func toneColor(_ theme: PrismTheme, _ tone: String) -> Color { tone.isEmpty || tone == "neutral" ? theme.accent : theme.color(tone) }204205 static let defaultPalette: [Color] = [.blue, .green, .orange, .purple, .pink, .teal, .indigo, .red, .brown, .cyan]206 static func palette(_ theme: PrismTheme) -> [Color] { theme.chartColors.isEmpty ? defaultPalette : theme.chartColors }207208 static func label(_ value: JSONValue?) -> String {209 let s = value?.displayString ?? ""210 return s.isEmpty ? "(none)" : s211 }212}213214/// The titled surface shared by family C: shows the problem or an honest empty state instead of the content when there is nothing to draw.215struct FCPanel<Content: View>: View {216 var title: String = ""217 var fallbackLabel: String218 var problem: String?219 var isEmpty = false220 var emptyTitle = "No data yet"221 var emptyMessage = "This fills in as records are added."222 var emptySymbol = "tray"223 var chart = false224 var summary: String = ""225 var trailing: String = ""226 @ViewBuilder var content: Content227228 var body: some View {229 VStack(alignment: .leading, spacing: 8) {230 if !title.isEmpty || !trailing.isEmpty {231 HStack(alignment: .firstTextBaseline) {232 if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }233 Spacer(minLength: 0)234 if !trailing.isEmpty { Text(trailing).font(.caption).foregroundStyle(.secondary).monospacedDigit() }235 }236 }237 if let problem {238 Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout).fixedSize(horizontal: false, vertical: true)239 } else if isEmpty {240 if chart {241 ContentUnavailableView(emptyTitle, systemImage: emptySymbol, description: Text(emptyMessage)).frame(maxWidth: .infinity, minHeight: 140)242 } else {243 VStack(alignment: .leading, spacing: 2) {244 Label(emptyTitle, systemImage: emptySymbol).foregroundStyle(.secondary)245 if !emptyMessage.isEmpty { Text(emptyMessage).font(.caption).foregroundStyle(.tertiary) }246 }247 .padding(.vertical, 6)248 }249 } else {250 content251 }252 }253 .padding(14)254 .frame(maxWidth: .infinity, alignment: .leading)255 .prismSurface()256 .accessibilityElement(children: .contain)257 .accessibilityLabel(title.isEmpty ? fallbackLabel : title)258 .accessibilityValue(problem ?? (isEmpty ? emptyTitle : summary))259 }260}261262/// A horizontal bar filled to a fraction. Drawn in a Canvas, so it never takes part in layout negotiation.263struct FCBar: View {264 let fraction: Double265 let color: Color266 var height: CGFloat = 8267268 var body: some View {269 Canvas { context, size in270 let track = Path(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: size.height / 2)271 context.fill(track, with: .color(.secondary.opacity(0.18)))272 let f = min(max(fraction, 0), 1)273 if f > 0 {274 let width = max(size.height, size.width * CGFloat(f))275 context.fill(Path(roundedRect: CGRect(x: 0, y: 0, width: width, height: size.height), cornerRadius: size.height / 2), with: .color(color))276 }277 }278 .frame(height: height)279 .frame(minWidth: 40, maxWidth: .infinity)280 .accessibilityHidden(true)281 }282}283284/// Round avatar with initials or a symbol.285struct FCAvatar: View {286 let name: String287 var symbol: String? = nil288 var color: Color289 var size: CGFloat = 36290291 var body: some View {292 ZStack {293 Circle().fill(color.opacity(0.18))294 if let symbol, !symbol.isEmpty {295 Image(systemName: SymbolName.safe(symbol, fallback: "square.grid.2x2")).font(.system(size: size * 0.42, weight: .medium)).foregroundStyle(color)296 } else {297 Text(FamilyCMath.initials(name)).font(.system(size: size * 0.38, weight: .semibold, design: .rounded)).foregroundStyle(color)298 }299 }300 .frame(width: size, height: size)301 .accessibilityHidden(true)302 }303}304305/// "Showing the first N of M" under a capped list.306struct FCMoreFooter: View {307 let shown: Int308 let total: Int309 var body: some View {310 if total > shown { Text("Showing the first \(shown) of \(total).").font(.caption).foregroundStyle(.secondary) }311 }312}313314/// Row selection shared by the list-like components: optional state binding plus the `select` event.315@MainActor316struct FCSelection {317 let runtime: AppRuntime318 let o: PrismObject319 let local: Binding<Int?>320321 var current: Int? {322 runtime.bindingPath(o.props["selection"]) != nil ? runtime.resolve(o.props["selection"]).intValue : local.wrappedValue323 }324325 func isSelected(_ row: FCRow) -> Bool { row["id"]?.intValue.map { $0 == current } ?? false }326327 func select(_ row: FCRow) {328 let id = row["id"]?.intValue329 local.wrappedValue = id330 if let path = runtime.bindingPath(o.props["selection"]) { runtime.setState(path, id.map(JSONValue.int) ?? .null) }331 runtime.fire("select", on: o.id, value: id.map(JSONValue.int) ?? .null, row: .object(row))332 }333}334335/// A full-width plain button row with a selection highlight.336struct FCRowButton<Label: View>: View {337 @Environment(\.prismTheme) private var theme338 let selected: Bool339 let accessibility: String340 let action: () -> Void341 @ViewBuilder var label: Label342343 var body: some View {344 Button(action: action) {345 label346 .frame(maxWidth: .infinity, alignment: .leading)347 .padding(.horizontal, 10).padding(.vertical, 7)348 .background(selected ? theme.accent.opacity(0.16) : Color.clear, in: RoundedRectangle(cornerRadius: 7, style: .continuous))349 .contentShape(Rectangle())350 }351 .buttonStyle(.plain)352 .accessibilityLabel(accessibility)353 .accessibilityAddTraits(selected ? [.isSelected] : [])354 }355}356