Repository Public License
1import PrismCore2import PrismDataRuntime3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67// MARK: Commerce89struct FCPriceTag: View {10 @Environment(AppRuntime.self) private var runtime11 @Environment(\.prismTheme) private var theme12 let o: PrismObject1314 var body: some View {15 let amount = runtime.number(o.props["amount"]) ?? 016 let original = runtime.number(o.props["originalAmount"])17 let code = o.props["currencyCode"]?.stringValue18 let label = runtime.string(o.props["label"])19 let discount = o.props["showDiscount"]?.boolValue != false ? FamilyCMath.discountPercent(amount: amount, original: original) : nil20 let wasShown = original.map { $0 > amount } ?? false21 VStack(alignment: .leading, spacing: 1) {22 if !label.isEmpty { Text(label).font(.caption).foregroundStyle(.secondary) }23 HStack(alignment: .firstTextBaseline, spacing: 8) {24 Text(FC.money(runtime, amount, code: code)).font(.title2.weight(.bold)).monospacedDigit().foregroundStyle(theme.color(runtime.string(o.props["tone"])))25 if wasShown, let original { Text(FC.money(runtime, original, code: code)).strikethrough().foregroundStyle(.secondary).monospacedDigit() }26 if let discount { BadgeView(text: "−\(discount)%", tone: "danger") }27 }28 }29 .accessibilityElement(children: .ignore)30 .accessibilityLabel(label.isEmpty ? "Price" : label)31 .accessibilityValue(FC.money(runtime, amount, code: code) + (wasShown ? ", was \(FC.money(runtime, original ?? 0, code: code))" : "") + (discount.map { ", \($0) percent off" } ?? ""))32 }33}3435/// Label on the left, amount on the right: the lines of a cart, an invoice footer.36private struct FCAmountLine: View {37 let label: String38 let amount: String39 var strong = false4041 var body: some View {42 HStack {43 Text(label).foregroundStyle(strong ? AnyShapeStyle(.primary) : AnyShapeStyle(.secondary))44 Spacer(minLength: 12)45 Text(amount).monospacedDigit()46 }47 .font(strong ? .headline : .body)48 .accessibilityElement(children: .combine)49 }50}5152struct FCCartSummary: View {53 @Environment(AppRuntime.self) private var runtime54 let o: PrismObject5556 var body: some View {57 let price = FC.column(o, "priceColumn"), quantity = FC.column(o, "quantityColumn")58 let source = FC.tableSource(runtime, table: FC.column(o, "table"), columns: [price, quantity]).orProblem(price == nil, "Set `priceColumn` to a column of the table.")59 let rate = max(runtime.number(o.props["taxRate"]) ?? 0, 0)60 let totals = FamilyCMath.totals(lines: FamilyCMath.lines(source.rows, price: price ?? "", quantity: quantity), taxRate: rate)61 let taxLabel = o.props["taxLabel"].map { runtime.string($0) } ?? "Tax"62 let button = runtime.string(o.props["buttonTitle"])63 let percent = rate.formatted(.percent.precision(.fractionLength(0...3)).locale(runtime.locale))64 FCPanel(65 title: o.props["title"].map { runtime.string($0) } ?? "Order summary", fallbackLabel: "Cart summary", problem: source.problem, isEmpty: source.rows.isEmpty,66 emptyTitle: "The cart is empty", emptyMessage: "", emptySymbol: "cart",67 summary: "\(FC.number(runtime, totals.itemCount)) items, total \(FC.money(runtime, totals.total))."68 ) {69 VStack(alignment: .leading, spacing: 6) {70 FCAmountLine(label: "Items", amount: FC.number(runtime, totals.itemCount))71 FCAmountLine(label: "Subtotal", amount: FC.money(runtime, totals.subtotal))72 if rate > 0 { FCAmountLine(label: "\(taxLabel) (\(percent))", amount: FC.money(runtime, totals.tax)) }73 Divider()74 FCAmountLine(label: "Total", amount: FC.money(runtime, totals.total), strong: true)75 if !button.isEmpty {76 Button { runtime.fire("click", on: o.id, value: .double(totals.total)) } label: { Text(button).frame(maxWidth: .infinity) }77 .buttonStyle(.borderedProminent).controlSize(.large).padding(.top, 4)78 }79 }80 }81 }82}8384struct FCInvoice: View {85 @Environment(AppRuntime.self) private var runtime86 let o: PrismObject8788 var body: some View {89 let description = FC.column(o, "descriptionColumn"), quantity = FC.column(o, "quantityColumn"), price = FC.column(o, "priceColumn")90 let source = FC.source(runtime, o, columns: [description, quantity, price])91 .orProblem(description == nil || price == nil, "Set `descriptionColumn` and `priceColumn` to columns of the query.")92 let lines = FamilyCMath.lines(source.rows, price: price ?? "", quantity: quantity)93 let rate = max(runtime.number(o.props["taxRate"]) ?? 0, 0)94 let totals = FamilyCMath.totals(lines: lines, taxRate: rate)95 let items = FCItem.list(source.rows)96 let number = runtime.string(o.props["number"]), customer = runtime.string(o.props["customer"]), notes = runtime.string(o.props["notes"])97 let percent = rate.formatted(.percent.precision(.fractionLength(0...3)).locale(runtime.locale))98 FCPanel(99 title: o.props["title"].map { runtime.string($0) } ?? "Invoice", fallbackLabel: "Invoice", problem: source.problem,100 isEmpty: source.rows.isEmpty, emptyTitle: "No line items yet", emptyMessage: customer.isEmpty ? "" : "Billed to \(customer)", emptySymbol: "doc.text",101 summary: "\(source.rows.count) lines. Subtotal \(FC.money(runtime, totals.subtotal)), tax \(FC.money(runtime, totals.tax)), total \(FC.money(runtime, totals.total)).",102 trailing: number.isEmpty ? "" : "No. \(number)"103 ) {104 if !customer.isEmpty { Text("Billed to \(customer)").font(.callout).foregroundStyle(.secondary) }105 Grid(alignment: .trailing, horizontalSpacing: 16, verticalSpacing: 6) {106 GridRow {107 Text("Description").gridColumnAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)108 Text("Qty")109 Text("Unit price")110 Text("Amount")111 }112 .font(.caption.weight(.semibold)).foregroundStyle(.secondary)113 Divider()114 ForEach(items) { item in115 let line = lines[item.index]116 GridRow {117 Text(FC.label(.string(source.text(item.row, description, runtime: runtime)))).lineLimit(2)118 Text(FC.number(runtime, line.quantity))119 Text(FC.money(runtime, line.price))120 Text(FC.money(runtime, FamilyCMath.roundMoney(line.price * line.quantity)))121 }122 .accessibilityElement(children: .combine)123 }124 Divider()125 GridRow { Text("Subtotal").foregroundStyle(.secondary).gridCellColumns(3); Text(FC.money(runtime, totals.subtotal)) }126 if rate > 0 { GridRow { Text("Tax (\(percent))").foregroundStyle(.secondary).gridCellColumns(3); Text(FC.money(runtime, totals.tax)) } }127 GridRow { Text("Total").gridCellColumns(3); Text(FC.money(runtime, totals.total)) }.font(.headline)128 }129 .monospacedDigit()130 FCMoreFooter(shown: items.count, total: source.rows.count)131 if !notes.isEmpty { Text(notes).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }132 }133 }134}135136struct FCReceipt: View {137 @Environment(AppRuntime.self) private var runtime138 let o: PrismObject139140 var body: some View {141 let label = FC.column(o, "labelColumn"), value = FC.column(o, "valueColumn"), quantity = FC.column(o, "quantityColumn")142 let source = FC.source(runtime, o, columns: [label, value, quantity]).orProblem(label == nil || value == nil, "Set `labelColumn` and `valueColumn` to columns of the query.")143 let lines = FamilyCMath.lines(source.rows, price: value ?? "", quantity: quantity)144 let rate = max(runtime.number(o.props["taxRate"]) ?? 0, 0)145 let totals = FamilyCMath.totals(lines: lines, taxRate: rate)146 let title = runtime.string(o.props["title"]), footer = runtime.string(o.props["footer"])147 let money: (Double) -> String = { FC.money(runtime, $0) }148 let entries = zip(source.rows, lines).map { row, line in149 (label: (quantity != nil && line.quantity != 1 ? "\(FC.number(runtime, line.quantity)) x " : "") + FC.label(row[label ?? ""]), amount: money(FamilyCMath.roundMoney(line.price * line.quantity)))150 }151 let text = FamilyCMath.receipt(152 title: title, lines: entries, subtotal: money(totals.subtotal), tax: rate > 0 ? money(totals.tax) : nil, total: money(totals.total), footer: footer153 ).joined(separator: "\n")154 if let problem = source.problem {155 Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)156 } else {157 Text(text)158 .font(.callout.monospaced())159 .fontDesign(.monospaced)160 .textSelection(.enabled)161 .fixedSize()162 .padding(14)163 .prismSurface(radius: 4)164 .accessibilityLabel(title.isEmpty ? "Receipt" : title)165 .accessibilityValue("\(entries.count) lines, total \(money(totals.total)).")166 }167 }168}169170struct FCProductCard: View {171 @Environment(AppRuntime.self) private var runtime172 @Environment(\.prismTheme) private var theme173 let o: PrismObject174175 var body: some View {176 let title = runtime.string(o.props["title"]), subtitle = runtime.string(o.props["subtitle"])177 let price = runtime.number(o.props["price"])178 let rating = runtime.number(o.props["rating"]).map { min(max($0, 0), 5) }179 let button = o.props["buttonTitle"].map { runtime.string($0) } ?? "Add to cart"180 let priceText = price.map { FC.money(runtime, $0, code: o.props["currencyCode"]?.stringValue) } ?? ""181 VStack(alignment: .leading, spacing: 8) {182 ZStack {183 RoundedRectangle(cornerRadius: max(theme.radius - 4, 4), style: .continuous).fill(theme.accent.opacity(0.12))184 Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"]), fallback: "shippingbox")).font(.system(size: 40, weight: .light)).foregroundStyle(theme.accent)185 }186 .frame(height: 96)187 .accessibilityHidden(true)188 Text(title).font(.headline).lineLimit(2).fixedSize(horizontal: false, vertical: true)189 if !subtitle.isEmpty { Text(subtitle).font(.callout).foregroundStyle(.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true) }190 if let rating {191 HStack(spacing: 2) {192 ForEach(1...5, id: \.self) { i in193 Image(systemName: rating >= Double(i) - 0.25 ? "star.fill" : rating >= Double(i) - 0.75 ? "star.leadinghalf.filled" : "star")194 }195 Text(rating.formatted(.number.precision(.fractionLength(1)).locale(runtime.locale))).font(.caption).foregroundStyle(.secondary).padding(.leading, 3)196 }197 .font(.caption).foregroundStyle(.yellow)198 .accessibilityElement(children: .ignore)199 .accessibilityLabel("Rated \(rating.formatted(.number.precision(.fractionLength(1)))) out of 5")200 }201 HStack {202 if !priceText.isEmpty { Text(priceText).font(.title3.weight(.semibold)).monospacedDigit() }203 Spacer(minLength: 8)204 if !button.isEmpty {205 Button(button) { runtime.fire("click", on: o.id, value: price.map(JSONValue.double) ?? .null) }206 .buttonStyle(.borderedProminent)207 .disabled(runtime.bool(o.props["disabled"], default: false))208 .accessibilityLabel("\(button), \(title)")209 }210 }211 }212 .padding(12)213 .frame(minWidth: 180, maxWidth: 280, alignment: .leading)214 .prismSurface()215 }216}217218struct FCQuantity: View {219 @Environment(AppRuntime.self) private var runtime220 let o: PrismObject221222 var body: some View {223 let lower = o.props["min"]?.doubleValue ?? 0, upper = o.props["max"]?.doubleValue224 let step = max(o.props["step"]?.doubleValue ?? 1, .leastNonzeroMagnitude)225 let current = runtime.resolve(o.props["value"]).numericValue ?? lower226 let label = runtime.string(o.props["label"])227 Labeled(label: label) {228 HStack(spacing: 0) {229 Button { set(FamilyCMath.clampedStep(current, by: -step, min: lower, max: upper)) } label: { Image(systemName: "minus").frame(width: 28, height: 24).contentShape(Rectangle()) }230 .buttonStyle(.plain).disabled(current <= lower).accessibilityLabel("Decrease \(label.isEmpty ? "quantity" : label)")231 Divider().frame(height: 18)232 Text(FC.number(runtime, current)).monospacedDigit().fontWeight(.medium).frame(minWidth: 40).padding(.horizontal, 4)233 .accessibilityLabel(label.isEmpty ? "Quantity" : label).accessibilityValue(FC.number(runtime, current))234 Divider().frame(height: 18)235 Button { set(FamilyCMath.clampedStep(current, by: step, min: lower, max: upper)) } label: { Image(systemName: "plus").frame(width: 28, height: 24).contentShape(Rectangle()) }236 .buttonStyle(.plain).disabled(upper.map { current >= $0 } ?? false).accessibilityLabel("Increase \(label.isEmpty ? "quantity" : label)")237 }238 .background(.background.secondary, in: RoundedRectangle(cornerRadius: 7, style: .continuous))239 .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(.separator))240 .fixedSize()241 }242 }243244 private func set(_ v: Double) {245 let value: JSONValue = v.rounded() == v && abs(v) < 9e15 ? .int(Int(v)) : .double(v)246 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, value) }247 runtime.fire("change", on: o.id, value: value)248 }249}250251/// Two fields linked by a fixed rate: editing either one recomputes the other.252struct FCConverter: View {253 @Environment(AppRuntime.self) private var runtime254 let o: PrismObject255 @State private var localFrom = 1.0256257 var body: some View {258 let rate = runtime.number(o.props["rate"]) ?? 0259 let decimals = min(max(o.props["decimals"]?.intValue ?? 2, 0), 8)260 let fromLabel = o.props["fromLabel"].map { runtime.string($0) } ?? "From", toLabel = o.props["toLabel"].map { runtime.string($0) } ?? "To"261 let from = runtime.bindingPath(o.props["value"]) != nil ? (runtime.resolve(o.props["value"]).numericValue ?? 0) : localFrom262 let format = FloatingPointFormatStyle<Double>.number.precision(.fractionLength(0...decimals)).locale(runtime.locale)263 VStack(alignment: .leading, spacing: 6) {264 if rate == 0 || !rate.isFinite {265 Label("`rate` must be a number other than zero.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout)266 } else {267 HStack(alignment: .bottom, spacing: 10) {268 Labeled(label: fromLabel) {269 TextField(fromLabel, value: Binding(get: { from }, set: { update(from: $0, rate: rate, decimals: decimals) }), format: format)270 .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(minWidth: 90, maxWidth: 160)271 }272 Image(systemName: "arrow.left.arrow.right").foregroundStyle(.secondary).padding(.bottom, 5).accessibilityHidden(true)273 Labeled(label: toLabel) {274 TextField(toLabel, value: Binding(275 get: { FamilyCMath.convert(from, rate: rate, forward: true, decimals: decimals) ?? 0 },276 set: { update(from: FamilyCMath.convert($0, rate: rate, forward: false, decimals: 8) ?? 0, rate: rate, decimals: decimals) }277 ), format: format)278 .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(minWidth: 90, maxWidth: 160)279 }280 }281 Text("1 \(fromLabel) = \(rate.formatted(.number.precision(.fractionLength(0...6)).locale(runtime.locale))) \(toLabel)").font(.caption).foregroundStyle(.secondary)282 }283 }284 }285286 private func update(from new: Double, rate: Double, decimals: Int) {287 let from = new.isFinite ? new : 0288 let to = FamilyCMath.convert(from, rate: rate, forward: true, decimals: decimals) ?? 0289 localFrom = from290 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .double(from)) }291 if let path = runtime.bindingPath(o.props["result"]) { runtime.setState(path, .double(to)) }292 runtime.fire("change", on: o.id, value: ["from": .double(from), "to": .double(to)])293 }294}295296// MARK: Social297298struct FCProfileCard: View {299 @Environment(AppRuntime.self) private var runtime300 @Environment(\.prismTheme) private var theme301 let o: PrismObject302303 var body: some View {304 let name = runtime.string(o.props["name"]), role = runtime.string(o.props["role"])305 let stats = (o.props["stats"]?.arrayValue ?? []).map { (label: runtime.string($0["label"]), value: runtime.string($0["value"])) }306 let button = runtime.string(o.props["buttonTitle"])307 let color = FC.toneColor(theme, runtime.string(o.props["tone"]))308 VStack(spacing: 10) {309 FCAvatar(name: name, color: color, size: 64)310 VStack(spacing: 2) {311 Text(name).font(.title3.weight(.semibold)).lineLimit(1)312 if !role.isEmpty { Text(role).font(.callout).foregroundStyle(.secondary).lineLimit(2).multilineTextAlignment(.center) }313 }314 if !stats.isEmpty {315 HStack(alignment: .top, spacing: 0) {316 ForEach(stats.indices, id: \.self) { i in317 if i > 0 { Divider().frame(height: 28) }318 VStack(spacing: 1) {319 Text(stats[i].value).font(.headline).monospacedDigit().lineLimit(1)320 Text(stats[i].label).font(.caption).foregroundStyle(.secondary).lineLimit(1)321 }322 .frame(maxWidth: .infinity)323 .accessibilityElement(children: .ignore)324 .accessibilityLabel(stats[i].label)325 .accessibilityValue(stats[i].value)326 }327 }328 }329 if !button.isEmpty {330 Button { runtime.fire("click", on: o.id, value: .string(name)) } label: { Text(button).frame(maxWidth: .infinity) }.buttonStyle(.borderedProminent)331 }332 }333 .padding(16)334 .frame(minWidth: 200, maxWidth: 300)335 .prismSurface()336 .accessibilityElement(children: .contain)337 .accessibilityLabel(role.isEmpty ? name : "\(name), \(role)")338 }339}340341struct FCReactionBar: View {342 @Environment(AppRuntime.self) private var runtime343 @Environment(\.prismTheme) private var theme344 let o: PrismObject345346 var body: some View {347 let reactions = (runtime.resolve(o.props["reactions"]).arrayValue ?? ["👍", "❤️", "🎉", "😄"]).map(\.displayString).filter { !$0.isEmpty }348 let state = runtime.resolve(o.props["value"])349 HStack(spacing: 6) {350 ForEach(reactions, id: \.self) { reaction in351 let count = Int(state[reaction]?.numericValue ?? 0)352 Button {353 let next = FamilyCMath.react(state, with: reaction)354 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, next) }355 runtime.fire("change", on: o.id, value: next)356 } label: {357 HStack(spacing: 4) {358 Text(reaction)359 if count > 0 { Text("\(count)").font(.callout.weight(.medium)).monospacedDigit() }360 }361 .padding(.horizontal, 9).padding(.vertical, 4)362 .background(count > 0 ? theme.accent.opacity(0.16) : Color.secondary.opacity(0.12), in: Capsule())363 .overlay(Capsule().strokeBorder(count > 0 ? theme.accent.opacity(0.5) : Color.clear))364 .contentShape(Capsule())365 }366 .buttonStyle(.plain)367 .accessibilityLabel("React with \(reaction)")368 .accessibilityValue("\(count)")369 }370 }371 }372}373374struct FCLikeButton: View {375 @Environment(AppRuntime.self) private var runtime376 @Environment(\.prismTheme) private var theme377 let o: PrismObject378379 var body: some View {380 let liked = runtime.resolve(o.props["value"]).isTruthy381 let count = o.props["count"].flatMap { runtime.number($0) }382 let label = runtime.string(o.props["label"])383 Button {384 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, .bool(!liked)) }385 if let path = runtime.bindingPath(o.props["count"]) { runtime.setState(path, .int(max(0, Int(count ?? 0) + (liked ? -1 : 1)))) }386 runtime.fire("toggle", on: o.id, value: .bool(!liked))387 } label: {388 HStack(spacing: 5) {389 Image(systemName: liked ? "heart.fill" : "heart").foregroundStyle(liked ? theme.color("danger") : Color.secondary)390 if !label.isEmpty { Text(label) }391 if let count { Text(FC.number(runtime, count)).monospacedDigit().foregroundStyle(.secondary) }392 }393 .padding(.horizontal, 10).padding(.vertical, 5)394 .background(liked ? theme.color("danger").opacity(0.12) : Color.secondary.opacity(0.12), in: Capsule())395 .contentShape(Capsule())396 }397 .buttonStyle(.plain)398 .accessibilityLabel(label.isEmpty ? "Like" : label)399 .accessibilityValue((liked ? "Liked" : "Not liked") + (count.map { ", \(Int($0))" } ?? ""))400 .accessibilityAddTraits(liked ? [.isSelected] : [])401 }402}403404struct FCPoll: View {405 @Environment(AppRuntime.self) private var runtime406 @Environment(\.prismTheme) private var theme407 let o: PrismObject408409 var body: some View {410 let options = (runtime.resolve(o.props["options"]).arrayValue ?? []).map(\.displayString).filter { !$0.isEmpty }411 let state = runtime.resolve(o.props["value"])412 let choice = state["choice"]?.stringValue ?? ""413 let votes = options.map { state["votes"]?[$0]?.numericValue ?? 0 }414 let percentages = FamilyCMath.pollPercentages(votes)415 let total = Int(votes.reduce(0, +))416 let showResults = !choice.isEmpty || o.props["alwaysShowResults"]?.boolValue == true417 let question = runtime.string(o.props["question"])418 VStack(alignment: .leading, spacing: 8) {419 if !question.isEmpty { Text(question).font(.headline).fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader) }420 if options.isEmpty { Label("Add `options` to vote on.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange).font(.callout) }421 ForEach(options.indices, id: \.self) { i in422 let chosen = options[i] == choice423 Button {424 let next = FamilyCMath.vote(state, for: options[i])425 if let path = runtime.bindingPath(o.props["value"]) { runtime.setState(path, next) }426 runtime.fire("change", on: o.id, value: next)427 } label: {428 VStack(alignment: .leading, spacing: 4) {429 HStack {430 Image(systemName: chosen ? "checkmark.circle.fill" : "circle").foregroundStyle(chosen ? theme.accent : Color.secondary)431 Text(options[i]).fontWeight(chosen ? .semibold : .regular)432 Spacer(minLength: 8)433 if showResults { Text("\(percentages[i])%").monospacedDigit().foregroundStyle(.secondary) }434 }435 if showResults { FCBar(fraction: Double(percentages[i]) / 100, color: chosen ? theme.accent : Color.secondary.opacity(0.6), height: 6) }436 }437 .padding(.horizontal, 10).padding(.vertical, 7)438 .frame(maxWidth: .infinity, alignment: .leading)439 .background(Color.secondary.opacity(chosen ? 0.14 : 0.07), in: RoundedRectangle(cornerRadius: 8, style: .continuous))440 .contentShape(Rectangle())441 }442 .buttonStyle(.plain)443 .accessibilityLabel(options[i])444 .accessibilityValue(showResults ? "\(percentages[i]) percent, \(Int(votes[i])) votes\(chosen ? ", your vote" : "")" : "Not voted")445 .accessibilityAddTraits(chosen ? [.isSelected] : [])446 }447 Text(showResults ? "\(total) vote\(total == 1 ? "" : "s")" : "Vote to see the results").font(.caption).foregroundStyle(.secondary)448 }449 .padding(14)450 .frame(maxWidth: .infinity, alignment: .leading)451 .prismSurface()452 }453}454