Repository Public License
1import PrismCore2import PrismIconKit3import PrismLogicRuntime4import PrismObjectModel5import SwiftUI67/// Routes the display components of family A.8struct FamilyADisplay: View {9 static let types: Set<String> = [10 "prism.avatar", "prism.avatarGroup", "prism.keyValue", "prism.descriptionList", "prism.trend", "prism.tagList", "prism.chip",11 "prism.ratingDisplay", "prism.timeline", "prism.steps", "prism.statusDot", "prism.counterBadge", "prism.ring", "prism.gauge",12 "prism.meter", "prism.colorSwatch", "prism.qrCode", "prism.featureList", "prism.pricingCard", "prism.symbolTile", "prism.legend",13 ]14 let o: PrismObject1516 var body: some View {17 switch o.type {18 case "prism.avatar": AvatarComponent(o: o)19 case "prism.avatarGroup": AvatarGroupComponent(o: o)20 case "prism.keyValue": KeyValueComponent(o: o)21 case "prism.descriptionList": DescriptionListComponent(o: o)22 case "prism.trend": TrendComponent(o: o)23 case "prism.tagList": TagListComponent(o: o)24 case "prism.chip": ChipComponent(o: o)25 case "prism.ratingDisplay": RatingDisplayComponent(o: o)26 case "prism.timeline": TimelineComponent(o: o)27 case "prism.steps": StepsComponent(o: o)28 case "prism.statusDot": StatusDotComponent(o: o)29 case "prism.counterBadge": CounterBadgeComponent(o: o)30 case "prism.ring": RingComponent(o: o)31 case "prism.gauge": GaugeComponent(o: o)32 case "prism.meter": MeterComponent(o: o)33 case "prism.colorSwatch": ColorSwatchComponent(o: o)34 case "prism.qrCode": QRCodeComponent(o: o)35 case "prism.featureList": FeatureListComponent(o: o)36 case "prism.pricingCard": PricingCardComponent(o: o)37 case "prism.symbolTile": SymbolTileComponent(o: o)38 default: LegendComponent(o: o)39 }40 }41}4243/// A circle holding initials or a symbol.44struct AvatarCircle: View {45 @Environment(\.prismTheme) private var theme46 let name: String47 var symbol: String = ""48 let size: CGFloat49 let tone: String5051 var body: some View {52 let tint = theme.mark(tone)53 let initials = FamilyAFormat.initials(name)54 ZStack {55 Circle().fill(tint.opacity(0.2))56 if !symbol.isEmpty || initials.isEmpty {57 Image(systemName: SymbolName.safe(symbol, fallback: "person.fill")).font(.system(size: size * 0.44, weight: .medium))58 } else {59 Text(initials).font(.system(size: size * 0.38, weight: .semibold, design: .rounded)).lineLimit(1)60 }61 }62 .foregroundStyle(tint)63 .frame(width: size, height: size)64 .accessibilityElement(children: .ignore)65 .accessibilityLabel(name.isEmpty ? "Avatar" : name)66 }67}6869/// One person or thing as initials or a symbol in a circle.70struct AvatarComponent: View {71 @Environment(AppRuntime.self) private var runtime72 let o: PrismObject7374 var body: some View {75 AvatarCircle(name: runtime.string(o.props["name"]), symbol: runtime.string(o.props["symbol"]),76 size: CGFloat(min(max(o.props["size"]?.doubleValue ?? 40, 16), 256)), tone: FA.tone(runtime, o, default: "accent"))77 }78}7980/// Overlapping avatars for a list of names, with a "+N" for the rest.81struct AvatarGroupComponent: View {82 @Environment(AppRuntime.self) private var runtime83 @Environment(\.prismTheme) private var theme84 let o: PrismObject8586 var body: some View {87 let names = FA.list(runtime, o.props["names"]).map(\.displayString)88 let limit = max(o.props["max"]?.intValue ?? 4, 1)89 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 32, 16), 128))90 let tone = FA.tone(runtime, o, default: "accent")91 let ring = Color(nsColor: .windowBackgroundColor)92 HStack(spacing: -size * 0.2) {93 ForEach(Array(names.prefix(limit).enumerated()), id: \.offset) { _, name in94 AvatarCircle(name: name, size: size, tone: tone).background(ring, in: Circle()).overlay(Circle().strokeBorder(ring, lineWidth: 2))95 }96 if names.count > limit {97 Text("+\(names.count - limit)").font(.system(size: size * 0.34, weight: .semibold, design: .rounded)).foregroundStyle(.secondary)98 .frame(width: size, height: size).background(.quaternary, in: Circle()).background(ring, in: Circle())99 .overlay(Circle().strokeBorder(ring, lineWidth: 2))100 }101 }102 .accessibilityElement(children: .ignore)103 .accessibilityLabel(names.isEmpty ? "No one" : names.joined(separator: ", "))104 }105}106107/// A label with its value, on one row or stacked.108struct KeyValueComponent: View {109 @Environment(AppRuntime.self) private var runtime110 @Environment(\.prismTheme) private var theme111 let o: PrismObject112113 var body: some View {114 let label = Text(runtime.string(o.props["label"])).foregroundStyle(.secondary)115 let value = Text(runtime.string(o.props["value"])).foregroundStyle(theme.color(FA.tone(runtime, o))).textSelection(.enabled)116 Group {117 if o.props["layout"]?.stringValue == "stacked" {118 VStack(alignment: .leading, spacing: 2) { label.font(.caption); value.font(.body.weight(.medium)) }119 } else {120 HStack(alignment: .firstTextBaseline, spacing: 12) { label; Spacer(minLength: 12); value.multilineTextAlignment(.trailing) }121 }122 }123 .accessibilityElement(children: .combine)124 }125}126127/// A list of terms and their values, aligned in two columns or stacked.128struct DescriptionListComponent: View {129 @Environment(AppRuntime.self) private var runtime130 let o: PrismObject131132 var body: some View {133 let items = FA.list(runtime, o.props["items"])134 if o.props["layout"]?.stringValue == "stacked" {135 VStack(alignment: .leading, spacing: 10) {136 ForEach(Array(items.enumerated()), id: \.offset) { _, item in137 VStack(alignment: .leading, spacing: 2) {138 Text(FA.field(runtime, item, "term")).font(.caption).foregroundStyle(.secondary)139 Text(FA.field(runtime, item, "value")).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)140 }141 .accessibilityElement(children: .combine)142 }143 }144 } else {145 Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 20, verticalSpacing: 8) {146 ForEach(Array(items.enumerated()), id: \.offset) { _, item in147 GridRow {148 Text(FA.field(runtime, item, "term")).foregroundStyle(.secondary).gridColumnAlignment(.leading)149 Text(FA.field(runtime, item, "value")).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)150 }151 .accessibilityElement(children: .combine)152 }153 }154 }155 }156}157158/// A headline value with the change since a reference, colored by its direction.159struct TrendComponent: View {160 @Environment(AppRuntime.self) private var runtime161 @Environment(\.prismTheme) private var theme162 let o: PrismObject163164 var body: some View {165 let label = runtime.string(o.props["label"])166 let delta = runtime.number(o.props["delta"])167 VStack(alignment: .leading, spacing: 4) {168 if !label.isEmpty { Text(label).font(.callout).foregroundStyle(.secondary) }169 HStack(alignment: .firstTextBaseline, spacing: 8) {170 Text(runtime.string(o.props["value"])).font(.title2.weight(.semibold)).monospacedDigit()171 if let delta {172 let chosen = FA.tone(runtime, o, default: "auto")173 let tone = chosen == "auto" ? FamilyAFormat.trendTone(delta: delta, positiveIsGood: o.props["positiveIsGood"]?.boolValue != false) : chosen174 Label(FamilyAFormat.delta(delta, percent: o.props["deltaFormat"]?.stringValue != "number", locale: runtime.locale),175 systemImage: delta > 0 ? "arrow.up.right" : delta < 0 ? "arrow.down.right" : "minus")176 .font(.callout.weight(.medium)).monospacedDigit().labelStyle(.titleAndIcon).lineLimit(1).fixedSize()177 .padding(.horizontal, 7).padding(.vertical, 2)178 .foregroundStyle(theme.tint(tone)).background(theme.tint(tone).opacity(0.14), in: Capsule())179 .accessibilityLabel(delta > 0 ? "Up" : delta < 0 ? "Down" : "Unchanged")180 .accessibilityValue(FamilyAFormat.delta(abs(delta), percent: o.props["deltaFormat"]?.stringValue != "number", locale: runtime.locale))181 }182 }183 }184 .accessibilityElement(children: .combine)185 }186}187188/// The capsule drawn by chips and tag lists.189struct ChipLabel: View {190 @Environment(\.prismTheme) private var theme191 let text: String192 var symbol: String = ""193 let tone: String194 var selected = false195196 var body: some View {197 let tint = theme.tint(tone)198 HStack(spacing: 4) {199 if !symbol.isEmpty { Image(systemName: SymbolName.safe(symbol)).accessibilityHidden(true) }200 Text(text).lineLimit(1)201 }202 .font(.callout)203 .padding(.horizontal, 10).padding(.vertical, 4)204 .foregroundStyle(selected ? AnyShapeStyle(.white) : AnyShapeStyle(tint))205 .background(selected ? AnyShapeStyle(tint) : AnyShapeStyle(tint.opacity(0.14)), in: Capsule())206 .contentShape(Capsule())207 }208}209210/// A list of strings as chips that wrap; clickable when `click` has actions.211struct TagListComponent: View {212 @Environment(AppRuntime.self) private var runtime213 let o: PrismObject214215 var body: some View {216 let tags = FA.list(runtime, o.props["tags"]).map(\.displayString).filter { !$0.isEmpty }217 let tone = FA.tone(runtime, o)218 let clickable = FA.connected(o, "click")219 FlowLayout(spacing: 6, lineSpacing: 6) {220 ForEach(Array(tags.enumerated()), id: \.offset) { _, tag in221 if clickable {222 Button { runtime.fire("click", on: o.id, value: .string(tag)) } label: { ChipLabel(text: tag, tone: tone) }.buttonStyle(.plain)223 } else {224 ChipLabel(text: tag, tone: tone)225 }226 }227 }228 }229}230231/// One chip; a button when `click` has actions or `selected` is bound (it then toggles), a static label otherwise.232struct ChipComponent: View {233 @Environment(AppRuntime.self) private var runtime234 let o: PrismObject235236 var body: some View {237 let selected = runtime.bool(o.props["selected"], default: false)238 let label = ChipLabel(text: runtime.string(o.props["text"]), symbol: runtime.string(o.props["symbol"]), tone: FA.tone(runtime, o), selected: selected)239 let path = runtime.bindingPath(o.props["selected"])240 if FA.connected(o, "click") || path != nil {241 Button {242 if let path { runtime.setState(path, .bool(!selected)) }243 runtime.fire("click", on: o.id, value: .string(runtime.string(o.props["text"])))244 } label: { label }245 .buttonStyle(.plain).accessibilityAddTraits(selected ? .isSelected : [])246 } else {247 label248 }249 }250}251252/// Read-only stars for a number, with half stars.253struct RatingDisplayComponent: View {254 @Environment(AppRuntime.self) private var runtime255 @Environment(\.prismTheme) private var theme256 let o: PrismObject257258 var body: some View {259 let value = runtime.number(o.props["value"]) ?? 0260 let stars = FamilyAFormat.stars(value: value, max: o.props["max"]?.intValue ?? 5)261 let spoken = "\(value.formatted(.number.precision(.fractionLength(0...1)))) of \(stars.count)"262 HStack(spacing: 2) {263 ForEach(Array(stars.enumerated()), id: \.offset) { _, symbol in Image(systemName: symbol) }264 .foregroundStyle(theme.mark(FA.tone(runtime, o, default: "warning")))265 if o.props["showValue"]?.boolValue == true {266 Text(value.formatted(.number.precision(.fractionLength(1)).locale(runtime.locale))).font(.callout).monospacedDigit().foregroundStyle(.secondary).padding(.leading, 4)267 }268 }269 .accessibilityElement(children: .ignore)270 .accessibilityLabel("Rating")271 .accessibilityValue(spoken)272 }273}274275/// A vertical list of events joined by a line.276struct TimelineComponent: View {277 @Environment(AppRuntime.self) private var runtime278 @Environment(\.prismTheme) private var theme279 let o: PrismObject280281 var body: some View {282 let items = FA.list(runtime, o.props["items"])283 VStack(alignment: .leading, spacing: 0) {284 ForEach(Array(items.enumerated()), id: \.offset) { index, item in285 let tint = theme.mark(FA.field(runtime, item, "tone"))286 let subtitle = FA.field(runtime, item, "subtitle")287 HStack(alignment: .top, spacing: 12) {288 VStack(spacing: 2) {289 Image(systemName: SymbolName.safe(FA.field(runtime, item, "symbol"), fallback: "circle.fill"))290 .font(.caption.weight(.semibold)).foregroundStyle(tint)291 .frame(width: 24, height: 24).background(tint.opacity(0.16), in: Circle())292 .accessibilityHidden(true)293 if index < items.count - 1 { Rectangle().fill(.separator).frame(width: 2).frame(maxHeight: .infinity) }294 }295 VStack(alignment: .leading, spacing: 2) {296 Text(FA.field(runtime, item, "title", plainAs: "title")).font(.body.weight(.medium)).fixedSize(horizontal: false, vertical: true)297 if !subtitle.isEmpty { Text(subtitle).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }298 }299 .padding(.top, 3).padding(.bottom, index < items.count - 1 ? 16 : 0)300 }301 .fixedSize(horizontal: false, vertical: true)302 .accessibilityElement(children: .combine)303 }304 }305 }306}307308/// A horizontal step indicator: done, current and upcoming steps.309struct StepsComponent: View {310 @Environment(AppRuntime.self) private var runtime311 @Environment(\.prismTheme) private var theme312 let o: PrismObject313314 var body: some View {315 let steps = FA.list(runtime, o.props["steps"]).map(\.displayString)316 let current = Int(runtime.number(o.props["current"]) ?? 0)317 let tint = theme.mark(FA.tone(runtime, o, default: "accent"))318 HStack(spacing: 8) {319 ForEach(Array(steps.enumerated()), id: \.offset) { index, title in320 HStack(spacing: 6) {321 ZStack {322 Circle().fill(index <= current ? AnyShapeStyle(tint) : AnyShapeStyle(.quaternary))323 if index < current { Image(systemName: "checkmark").font(.caption2.weight(.bold)).foregroundStyle(.white) }324 else { Text("\(index + 1)").font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(index == current ? AnyShapeStyle(.white) : AnyShapeStyle(.secondary)) }325 }326 .frame(width: 22, height: 22)327 Text(title).font(.callout.weight(index == current ? .semibold : .regular)).foregroundStyle(index <= current ? .primary : .secondary).lineLimit(1)328 }329 .accessibilityElement(children: .ignore)330 .accessibilityLabel("Step \(index + 1) of \(steps.count): \(title)")331 .accessibilityValue(index < current ? "Done" : index == current ? "Current" : "Upcoming")332 if index < steps.count - 1 {333 Rectangle().fill(index < current ? AnyShapeStyle(tint) : AnyShapeStyle(.quaternary)).frame(height: 2).frame(minWidth: 12, maxWidth: .infinity)334 .accessibilityHidden(true)335 }336 }337 }338 }339}340341/// A colored dot with a label.342struct StatusDotComponent: View {343 @Environment(AppRuntime.self) private var runtime344 @Environment(\.prismTheme) private var theme345 @Environment(\.accessibilityReduceMotion) private var reduceMotion346 let o: PrismObject347 @State private var swollen = false348349 var body: some View {350 let tint = theme.tint(FA.tone(runtime, o))351 let pulsing = runtime.bool(o.props["pulse"], default: false) && !reduceMotion352 HStack(spacing: 6) {353 Circle().fill(tint).frame(width: 8, height: 8)354 .background { if pulsing { Circle().fill(tint.opacity(0.35)).scaleEffect(swollen ? 2.2 : 1).opacity(swollen ? 0 : 1) } }355 .frame(width: 14, height: 14)356 .accessibilityHidden(true)357 Text(runtime.string(o.props["label"])).font(.callout)358 }359 .task(id: pulsing) {360 swollen = false361 guard pulsing else { return }362 withAnimation(.easeOut(duration: 1.2).repeatForever(autoreverses: false)) { swollen = true }363 }364 .accessibilityElement(children: .combine)365 }366}367368/// A number in a pill, for unread or pending counts.369struct CounterBadgeComponent: View {370 @Environment(AppRuntime.self) private var runtime371 @Environment(\.prismTheme) private var theme372 let o: PrismObject373374 var body: some View {375 let count = Int(runtime.number(o.props["count"]) ?? 0)376 let label = runtime.string(o.props["label"])377 if count != 0 || o.props["hideZero"]?.boolValue == false {378 Text(FamilyAFormat.counter(count, max: o.props["max"]?.intValue ?? 99))379 .font(.caption.weight(.bold)).monospacedDigit().foregroundStyle(.white)380 .padding(.horizontal, 6).padding(.vertical, 2).frame(minWidth: 20)381 .background(theme.mark(FA.tone(runtime, o, default: "danger")), in: Capsule())382 .accessibilityLabel(label.isEmpty ? "Count" : label)383 .accessibilityValue("\(count)")384 }385 }386}387388/// Circular progress from 0 to 1 with a label in the middle.389struct RingComponent: View {390 @Environment(AppRuntime.self) private var runtime391 @Environment(\.prismTheme) private var theme392 let o: PrismObject393394 var body: some View {395 let raw = runtime.number(o.props["value"]) ?? 0396 let value = FamilyAFormat.fraction(raw, min: 0, max: 1)397 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 96, 32), 400))398 let line = CGFloat(min(max(o.props["lineWidth"]?.doubleValue ?? 10, 2), Double(size) / 3))399 let tint = theme.mark(FA.tone(runtime, o))400 let percent = (raw.isFinite ? raw : 0).formatted(.percent.precision(.fractionLength(0)).locale(runtime.locale))401 let label = o.props["label"].map { runtime.string($0) } ?? percent402 let caption = runtime.string(o.props["caption"])403 ZStack {404 Circle().stroke(tint.opacity(0.18), lineWidth: line)405 Circle().trim(from: 0, to: value).stroke(tint, style: StrokeStyle(lineWidth: line, lineCap: .round)).rotationEffect(.degrees(-90))406 VStack(spacing: 0) {407 Text(label).font(.system(size: max(size * 0.2, 10), weight: .semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)408 if !caption.isEmpty { Text(caption).font(.system(size: max(size * 0.11, 9))).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.6) }409 }410 .padding(line + 4)411 }412 .padding(line / 2)413 .frame(width: size, height: size)414 .accessibilityElement(children: .ignore)415 .accessibilityLabel(caption.isEmpty ? "Progress" : caption)416 .accessibilityValue(o.props["label"] == nil ? percent : "\(label), \(percent)")417 }418}419420/// The upper half of a circle, drawn left to right.421struct HalfArc: Shape {422 let lineWidth: CGFloat423424 func path(in rect: CGRect) -> Path {425 var path = Path()426 let radius = max(min(rect.width / 2, rect.height) - lineWidth / 2, 1)427 path.addArc(center: CGPoint(x: rect.midX, y: rect.maxY - lineWidth / 2), radius: radius, startAngle: .degrees(180), endAngle: .degrees(360), clockwise: false)428 return path429 }430}431432/// A half-circle gauge for a value between a minimum and a maximum.433struct GaugeComponent: View {434 @Environment(AppRuntime.self) private var runtime435 @Environment(\.prismTheme) private var theme436 let o: PrismObject437438 var body: some View {439 let lower = runtime.number(o.props["min"]) ?? 0, upper = runtime.number(o.props["max"]) ?? 100440 let raw = runtime.number(o.props["value"]) ?? lower441 let fraction = FamilyAFormat.fraction(raw, min: lower, max: upper)442 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 160, 80), 480))443 let line = max(size * 0.09, 6)444 let tint = theme.mark(FA.tone(runtime, o))445 let label = runtime.string(o.props["label"])446 let text = number(raw) + runtime.string(o.props["unit"])447 VStack(spacing: 2) {448 ZStack(alignment: .bottom) {449 HalfArc(lineWidth: line).stroke(tint.opacity(0.18), style: StrokeStyle(lineWidth: line, lineCap: .round))450 HalfArc(lineWidth: line).trim(from: 0, to: fraction).stroke(tint, style: StrokeStyle(lineWidth: line, lineCap: .round))451 VStack(spacing: 0) {452 Text(text).font(.system(size: size * 0.17, weight: .semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)453 if !label.isEmpty { Text(label).font(.caption).foregroundStyle(.secondary).lineLimit(1) }454 }455 .padding(.horizontal, line * 2)456 }457 .frame(width: size, height: size / 2 + line / 2)458 HStack { Text(number(lower)); Spacer(); Text(number(upper)) }.font(.caption2).monospacedDigit().foregroundStyle(.secondary).frame(width: size)459 }460 .accessibilityElement(children: .ignore)461 .accessibilityLabel(label.isEmpty ? "Gauge" : label)462 .accessibilityValue("\(text), from \(number(lower)) to \(number(upper))")463 }464465 private func number(_ value: Double) -> String { (value.isFinite ? value : 0).formatted(.number.precision(.fractionLength(0...1)).locale(runtime.locale)) }466}467468/// A row of segments lit up to a level.469struct MeterComponent: View {470 @Environment(AppRuntime.self) private var runtime471 @Environment(\.prismTheme) private var theme472 let o: PrismObject473474 var body: some View {475 let segments = min(max(o.props["segments"]?.intValue ?? 10, 2), 40)476 let fraction = FamilyAFormat.fraction(runtime.number(o.props["value"]) ?? 0, min: 0, max: runtime.number(o.props["max"]) ?? 1)477 let lit = Int((fraction * Double(segments)).rounded())478 let tint = theme.mark(FA.tone(runtime, o))479 let label = runtime.string(o.props["label"])480 VStack(alignment: .leading, spacing: 4) {481 if !label.isEmpty { Text(label).font(.callout) }482 HStack(spacing: 3) {483 ForEach(0..<segments, id: \.self) { i in484 RoundedRectangle(cornerRadius: 2).fill(i < lit ? AnyShapeStyle(tint) : AnyShapeStyle(tint.opacity(0.18))).frame(minWidth: 4, maxWidth: 14).frame(height: 14)485 }486 }487 }488 .accessibilityElement(children: .ignore)489 .accessibilityLabel(label.isEmpty ? "Level" : label)490 .accessibilityValue("\(lit) of \(segments)")491 }492}493494/// Color chips from hex values; clicking one selects it.495struct ColorSwatchComponent: View {496 @Environment(AppRuntime.self) private var runtime497 let o: PrismObject498 @State private var local: String?499500 var body: some View {501 let colors = FA.list(runtime, o.props["colors"]).compactMap(\.stringValue).filter { RGBA(hex: $0) != nil }502 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 28, 16), 96))503 let bound = runtime.bindingPath(o.props["selection"]) != nil504 let selected = (bound ? runtime.resolve(o.props["selection"]).displayString : local ?? o.props["selection"]?.stringValue ?? "").lowercased()505 FlowLayout(spacing: 8, lineSpacing: 8) {506 ForEach(Array(colors.enumerated()), id: \.offset) { _, hex in507 let isSelected = hex.lowercased() == selected508 Button { select(hex) } label: {509 Circle().fill(Color(hex: hex) ?? .clear).frame(width: size, height: size)510 .overlay(Circle().strokeBorder(.separator))511 .overlay {512 if isSelected {513 Image(systemName: "checkmark").font(.system(size: size * 0.42, weight: .bold))514 .foregroundStyle((RGBA(hex: hex)?.luminance ?? 0) > 0.5 ? Color.black : Color.white)515 }516 }517 .contentShape(Circle())518 }519 .buttonStyle(.plain)520 .accessibilityLabel("Color \(hex)")521 .accessibilityAddTraits(isSelected ? .isSelected : [])522 }523 }524 }525526 private func select(_ hex: String) {527 local = hex528 if let path = runtime.bindingPath(o.props["selection"]) { runtime.setState(path, .string(hex)) }529 runtime.fire("select", on: o.id, value: .string(hex))530 }531}532533/// A QR code for a text value, always dark on white so scanners can read it.534struct QRCodeComponent: View {535 @Environment(AppRuntime.self) private var runtime536 let o: PrismObject537538 var body: some View {539 let text = runtime.string(o.props["value"])540 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 160, 64), 640))541 Group {542 if let image = FamilyAQR.image(text, correction: o.props["correction"]?.stringValue ?? "M", minimumSide: Int(size * 2)) {543 Image(decorative: image, scale: 1).resizable().padding(size * 0.06)544 } else {545 Image(systemName: "qrcode").font(.system(size: size * 0.4)).foregroundStyle(.gray)546 }547 }548 .frame(width: size, height: size)549 .background(.white, in: RoundedRectangle(cornerRadius: 6))550 .accessibilityElement(children: .ignore)551 .accessibilityLabel(text.isEmpty ? "Empty QR code" : "QR code for \(text)")552 .accessibilityAddTraits(.isImage)553 }554}555556/// A list of features: symbol, title and a line of text each.557struct FeatureListComponent: View {558 @Environment(AppRuntime.self) private var runtime559 @Environment(\.prismTheme) private var theme560 let o: PrismObject561562 var body: some View {563 let items = FA.list(runtime, o.props["items"])564 let columns = min(max(o.props["columns"]?.intValue ?? 1, 1), 4)565 let tint = theme.mark(FA.tone(runtime, o, default: "accent"))566 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 16, alignment: .topLeading), count: columns), alignment: .leading, spacing: 14) {567 ForEach(Array(items.enumerated()), id: \.offset) { _, item in568 let text = FA.field(runtime, item, "text")569 HStack(alignment: .top, spacing: 12) {570 Image(systemName: SymbolName.safe(FA.field(runtime, item, "symbol"), fallback: "checkmark.circle.fill"))571 .font(.title3).foregroundStyle(tint).frame(width: 28).accessibilityHidden(true)572 VStack(alignment: .leading, spacing: 2) {573 Text(FA.field(runtime, item, "title", plainAs: "title")).font(.headline).fixedSize(horizontal: false, vertical: true)574 if !text.isEmpty { Text(text).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }575 }576 }577 .frame(maxWidth: .infinity, alignment: .leading)578 .accessibilityElement(children: .combine)579 }580 }581 }582}583584/// A plan card: title, price, features and a button.585struct PricingCardComponent: View {586 @Environment(AppRuntime.self) private var runtime587 @Environment(\.prismTheme) private var theme588 let o: PrismObject589590 var body: some View {591 let highlighted = runtime.bool(o.props["highlighted"], default: false)592 let badge = runtime.string(o.props["badge"]), period = runtime.string(o.props["period"])593 let connected = FA.connected(o, "click")594 VStack(alignment: .leading, spacing: theme.spacing) {595 HStack {596 Text(runtime.string(o.props["title"])).font(.headline).accessibilityAddTraits(.isHeader)597 Spacer(minLength: 8)598 if !badge.isEmpty { BadgeView(text: badge, tone: "accent") }599 }600 HStack(alignment: .firstTextBaseline, spacing: 4) {601 Text(runtime.string(o.props["price"])).font(.system(.largeTitle, weight: .bold)).monospacedDigit()602 if !period.isEmpty { Text(period).font(.callout).foregroundStyle(.secondary) }603 }604 VStack(alignment: .leading, spacing: 6) {605 ForEach(Array(FA.list(runtime, o.props["features"]).enumerated()), id: \.offset) { _, feature in606 Label { Text(feature.displayString).fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "checkmark").foregroundStyle(theme.accent) }607 .font(.callout)608 }609 }610 let button = Button { runtime.fire("click", on: o.id, value: .string(runtime.string(o.props["title"]))) } label: {611 Text(o.props["buttonTitle"].map { runtime.string($0) } ?? "Choose").frame(maxWidth: .infinity)612 }613 .controlSize(.large).disabled(!connected).help(connected ? "" : "No action is connected to this button yet.")614 if highlighted { button.buttonStyle(.borderedProminent) } else { button.buttonStyle(.bordered) }615 }616 .padding(16)617 .frame(maxWidth: .infinity, alignment: .leading)618 .prismSurface()619 .overlay { if highlighted { RoundedRectangle(cornerRadius: theme.radius, style: .continuous).strokeBorder(theme.accent, lineWidth: 2).allowsHitTesting(false) } }620 }621}622623/// An SF Symbol on a rounded gradient tile, like an app icon.624struct SymbolTileComponent: View {625 @Environment(AppRuntime.self) private var runtime626 @Environment(\.prismTheme) private var theme627 let o: PrismObject628629 var body: some View {630 let size = CGFloat(min(max(o.props["size"]?.doubleValue ?? 56, 20), 320))631 let tone = FA.tone(runtime, o, default: "accent")632 let base = tone == "neutral" ? Color.gray : theme.color(tone)633 Image(systemName: SymbolName.safe(runtime.string(o.props["symbol"])))634 .font(.system(size: size * 0.5, weight: .semibold)).foregroundStyle(.white)635 .frame(width: size, height: size)636 .background(LinearGradient(colors: [base.mix(with: .white, by: 0.28), base.mix(with: .black, by: 0.12)], startPoint: .top, endPoint: .bottom),637 in: RoundedRectangle(cornerRadius: size * 0.24, style: .continuous))638 }639}640641/// Color and label pairs explaining the colors of a figure.642struct LegendComponent: View {643 @Environment(AppRuntime.self) private var runtime644 @Environment(\.prismTheme) private var theme645 let o: PrismObject646647 var body: some View {648 let items = FA.list(runtime, o.props["items"])649 if o.props["direction"]?.stringValue == "vertical" {650 VStack(alignment: .leading, spacing: 6) { entries(items) }651 } else {652 FlowLayout(spacing: 14, lineSpacing: 6) { entries(items) }653 }654 }655656 private func entries(_ items: [JSONValue]) -> some View {657 ForEach(Array(items.enumerated()), id: \.offset) { index, item in658 HStack(spacing: 6) {659 RoundedRectangle(cornerRadius: 3).fill(color(item, index)).frame(width: 12, height: 12).accessibilityHidden(true)660 Text(FA.field(runtime, item, "label", plainAs: "label")).font(.callout).lineLimit(1)661 }662 .accessibilityElement(children: .combine)663 }664 }665666 /// The item's hex `color`, else its `tone`, else the theme's series color for its position.667 private func color(_ item: JSONValue, _ index: Int) -> Color {668 if let hex = item["color"]?.stringValue, let color = Color(hex: hex) { return color }669 let tone = FA.field(runtime, item, "tone")670 if !tone.isEmpty { return theme.tint(tone) }671 let palette = theme.chartColors.isEmpty ? PrismTheme.accentChoices.compactMap { Color(hex: $0.hex) } : theme.chartColors672 return palette.isEmpty ? theme.accent : palette[index % palette.count]673 }674}675