Repository Public License
1import PrismCore2import PrismLogicRuntime3import PrismObjectModel4import SwiftUI56/// Routes the layout components of family A.7struct FamilyALayout: View {8 static let types: Set<String> = [9 "prism.spacer", "prism.box", "prism.center", "prism.overlay", "prism.wrap", "prism.accordion", "prism.disclosure", "prism.carousel",10 "prism.aspect", "prism.columns", "prism.listGroup", "prism.section", "prism.hero", "prism.footerBar", "prism.popover", "prism.tooltip",11 "prism.ribbon",12 ]13 let o: PrismObject1415 var body: some View {16 switch o.type {17 case "prism.spacer": Spacer(minLength: CGFloat(max(o.props["minLength"]?.doubleValue ?? 0, 0)))18 case "prism.box": BoxComponent(o: o)19 case "prism.center": CenterComponent(o: o)20 case "prism.overlay": OverlayComponent(o: o)21 case "prism.wrap": WrapComponent(o: o)22 case "prism.accordion": AccordionComponent(o: o)23 case "prism.disclosure": DisclosureComponent(o: o)24 case "prism.carousel": CarouselComponent(o: o)25 case "prism.aspect": AspectComponent(o: o)26 case "prism.columns": ColumnsComponent(o: o)27 case "prism.listGroup": ListGroupComponent(o: o)28 case "prism.section": SectionComponent(o: o)29 case "prism.hero": HeroComponent(o: o)30 case "prism.footerBar": FooterBarComponent(o: o)31 case "prism.popover": PopoverComponent(o: o)32 case "prism.tooltip": TooltipComponent(o: o)33 default: RibbonComponent(o: o)34 }35 }36}3738/// A container with a background, inner padding and an optional border.39struct BoxComponent: View {40 @Environment(AppRuntime.self) private var runtime41 @Environment(\.prismTheme) private var theme42 let o: PrismObject4344 var body: some View {45 let tint = theme.tint(FA.tone(runtime, o))46 let radius = CGFloat(o.props["cornerRadius"]?.doubleValue ?? Double(theme.radius))47 let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)48 let content = VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }49 .padding(CGFloat(max(o.props["inset"]?.doubleValue ?? 12, 0)))50 // A box that grows fills its frame, so the background covers the whole area.51 .frame(maxWidth: .infinity, maxHeight: o.props["grow"]?.boolValue == true ? .infinity : nil, alignment: .topLeading)52 Group {53 switch o.props["fill"]?.stringValue ?? "tinted" {54 case "none": content55 case "surface": content.prismSurface(radius: radius)56 case "solid": content.foregroundStyle(.white).background(tint, in: shape)57 default: content.background(tint.opacity(0.12), in: shape)58 }59 }60 .overlay { if o.props["border"]?.boolValue == true { shape.strokeBorder(tint.opacity(0.55)).allowsHitTesting(false) } }61 }62}6364/// Centers its children in the space it is given.65struct CenterComponent: View {66 @Environment(\.prismTheme) private var theme67 let o: PrismObject6869 var body: some View {70 let axis = o.props["axis"]?.stringValue ?? "both"71 VStack(spacing: theme.spacing) { ChildrenView(ids: o.children) }72 .frame(maxWidth: axis == "vertical" ? nil : .infinity, maxHeight: axis == "horizontal" ? nil : .infinity, alignment: .center)73 }74}7576/// Stacks its children on top of each other.77struct OverlayComponent: View {78 let o: PrismObject7980 var body: some View {81 ZStack(alignment: FA.alignment(o.props["align"]?.stringValue)) { ChildrenView(ids: o.children) }82 }83}8485/// Places subviews left to right and starts a new line when the width runs out.86struct FlowLayout: Layout {87 var spacing: CGFloat = 888 var lineSpacing: CGFloat = 889 var align: String = "leading"9091 private struct Row {92 var items: [(index: Int, size: CGSize)] = []93 var width: CGFloat = 094 var height: CGFloat = 095 }9697 private func rows(_ subviews: Subviews, maxWidth: CGFloat) -> [Row] {98 var rows: [Row] = [], row = Row()99 for (index, subview) in subviews.enumerated() {100 var size = subview.sizeThatFits(.unspecified)101 if size.width > maxWidth { size = subview.sizeThatFits(ProposedViewSize(width: maxWidth, height: nil)) }102 if !row.items.isEmpty, row.width + spacing + size.width > maxWidth {103 rows.append(row)104 row = Row()105 }106 row.width += (row.items.isEmpty ? 0 : spacing) + size.width107 row.height = max(row.height, size.height)108 row.items.append((index, size))109 }110 if !row.items.isEmpty { rows.append(row) }111 return rows112 }113114 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {115 let rows = rows(subviews, maxWidth: proposal.width ?? .infinity)116 let height = rows.map(\.height).reduce(0, +) + lineSpacing * CGFloat(max(rows.count - 1, 0))117 return CGSize(width: rows.map(\.width).max() ?? 0, height: height)118 }119120 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {121 var y = bounds.minY122 for row in rows(subviews, maxWidth: bounds.width) {123 let free = max(bounds.width - row.width, 0)124 var x = bounds.minX + (align == "center" ? free / 2 : align == "trailing" ? free : 0)125 for item in row.items {126 subviews[item.index].place(at: CGPoint(x: x, y: y + (row.height - item.size.height) / 2), anchor: .topLeading, proposal: ProposedViewSize(item.size))127 x += item.size.width + spacing128 }129 y += row.height + lineSpacing130 }131 }132}133134/// A flow layout: children wrap onto new lines.135struct WrapComponent: View {136 @Environment(\.prismTheme) private var theme137 let o: PrismObject138139 var body: some View {140 let spacing = CGFloat(max(o.props["spacing"]?.doubleValue ?? 8, 0))141 FlowLayout(spacing: spacing, lineSpacing: CGFloat(max(o.props["lineSpacing"]?.doubleValue ?? Double(spacing), 0)), align: o.props["align"]?.stringValue ?? "leading") {142 ChildrenView(ids: o.children)143 }144 }145}146147/// The clickable title row shared by the accordion and the disclosure.148struct CollapsibleHeader: View {149 @Environment(\.accessibilityReduceMotion) private var reduceMotion150 let title: String151 let isOpen: Bool152 let action: () -> Void153154 var body: some View {155 Button(action: action) {156 HStack(spacing: 8) {157 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(.secondary)158 .rotationEffect(.degrees(isOpen ? 90 : 0))159 .animation(reduceMotion ? nil : .snappy(duration: 0.18), value: isOpen)160 .accessibilityHidden(true)161 Text(title).font(.headline)162 Spacer(minLength: 0)163 }164 .contentShape(Rectangle())165 }166 .buttonStyle(.plain)167 .accessibilityLabel(title)168 .accessibilityValue(isOpen ? "Expanded" : "Collapsed")169 .accessibilityHint(isOpen ? "Collapses the section" : "Expands the section")170 }171}172173/// Collapsible panels, one per child, with at most one open.174struct AccordionComponent: View {175 @Environment(AppRuntime.self) private var runtime176 let o: PrismObject177 /// The panel opened by hand when `open` is not bound to state; nil until the user clicks.178 @State private var local: String?179180 private var current: String {181 if runtime.bindingPath(o.props["open"]) != nil { return runtime.resolve(o.props["open"]).displayString }182 return local ?? o.props["open"]?.stringValue ?? o.children.first ?? ""183 }184185 var body: some View {186 let current = current187 VStack(alignment: .leading, spacing: 0) {188 ForEach(Array(o.children.enumerated()), id: \.element) { index, id in189 if index > 0 { Divider() }190 CollapsibleHeader(title: FA.childTitle(runtime, id), isOpen: id == current) { toggle(id, wasOpen: id == current) }191 .padding(.horizontal, 12).padding(.vertical, 10)192 if id == current {193 NodeView(id: id).padding(.horizontal, 12).padding(.bottom, 12).frame(maxWidth: .infinity, alignment: .leading)194 }195 }196 }197 .prismSurface()198 }199200 private func toggle(_ id: String, wasOpen: Bool) {201 let next = wasOpen ? "" : id202 local = next203 if let path = runtime.bindingPath(o.props["open"]) { runtime.setState(path, .string(next)) }204 runtime.fire(wasOpen ? "collapse" : "expand", on: o.id, value: .string(id))205 }206}207208/// One collapsible section with a title.209struct DisclosureComponent: View {210 @Environment(AppRuntime.self) private var runtime211 @Environment(\.prismTheme) private var theme212 let o: PrismObject213 @State private var local: Bool?214215 private var isOpen: Bool {216 if runtime.bindingPath(o.props["expanded"]) != nil { return runtime.resolve(o.props["expanded"]).isTruthy }217 return local ?? o.props["expanded"]?.boolValue ?? false218 }219220 var body: some View {221 let isOpen = isOpen222 VStack(alignment: .leading, spacing: theme.spacing) {223 CollapsibleHeader(title: runtime.string(o.props["title"]), isOpen: isOpen) {224 local = !isOpen225 if let path = runtime.bindingPath(o.props["expanded"]) { runtime.setState(path, .bool(!isOpen)) }226 runtime.fire("toggle", on: o.id, value: .bool(!isOpen))227 }228 if isOpen {229 VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }.padding(.leading, 20)230 }231 }232 .frame(maxWidth: .infinity, alignment: .leading)233 }234}235236/// Shows one child at a time with previous/next arrows and page dots.237struct CarouselComponent: View {238 @Environment(AppRuntime.self) private var runtime239 @Environment(\.prismTheme) private var theme240 @Environment(\.accessibilityReduceMotion) private var reduceMotion241 let o: PrismObject242 @State private var local: Int?243244 private var index: Int {245 let raw = runtime.bindingPath(o.props["page"]) != nil ? Int(runtime.number(o.props["page"]) ?? 0) : local ?? o.props["page"]?.intValue ?? 0246 return min(max(raw, 0), max(o.children.count - 1, 0))247 }248249 var body: some View {250 let count = o.children.count, index = index251 let loop = o.props["loop"]?.boolValue == true252 let arrows = o.props["showArrows"]?.boolValue != false253 VStack(spacing: 10) {254 HStack(spacing: 8) {255 if arrows { arrow("chevron.left", "Previous page", enabled: count > 1 && (loop || index > 0)) { go(index == 0 ? count - 1 : index - 1) } }256 Group {257 if count > 0 { NodeView(id: o.children[index]).id(index).transition(.opacity) }258 }259 .frame(maxWidth: .infinity, alignment: .center)260 if arrows { arrow("chevron.right", "Next page", enabled: count > 1 && (loop || index < count - 1)) { go(index == count - 1 ? 0 : index + 1) } }261 }262 if o.props["showDots"]?.boolValue != false, count > 1 {263 HStack(spacing: 6) {264 ForEach(0..<count, id: \.self) { i in265 Button { go(i) } label: {266 Circle().fill(i == index ? AnyShapeStyle(theme.accent) : AnyShapeStyle(.tertiary)).frame(width: 8, height: 8)267 .padding(3).contentShape(Rectangle())268 }269 .buttonStyle(.plain)270 .accessibilityLabel("Page \(i + 1) of \(count)")271 .accessibilityAddTraits(i == index ? .isSelected : [])272 }273 }274 }275 }276 .animation(reduceMotion ? nil : .easeInOut(duration: 0.2), value: index)277 }278279 private func arrow(_ symbol: String, _ label: String, enabled: Bool, action: @escaping () -> Void) -> some View {280 Button(action: action) { Image(systemName: symbol).font(.body.weight(.semibold)).frame(width: 22, height: 22) }281 .buttonStyle(.bordered).buttonBorderShape(.circle).disabled(!enabled).accessibilityLabel(label)282 }283284 private func go(_ page: Int) {285 local = page286 if let path = runtime.bindingPath(o.props["page"]) { runtime.setState(path, .int(page)) }287 runtime.fire("page", on: o.id, value: .int(page))288 }289}290291/// Keeps its child in a frame of a fixed width-to-height ratio.292struct AspectComponent: View {293 let o: PrismObject294295 var body: some View {296 let ratio = o.props["ratio"]?.doubleValue ?? 16.0 / 9.0297 Color.clear298 .aspectRatio(CGFloat(ratio.isFinite && ratio > 0.05 ? min(ratio, 20) : 1), contentMode: .fit)299 .overlay { ZStack { ChildrenView(ids: o.children) }.frame(maxWidth: .infinity, maxHeight: .infinity) }300 .clipped()301 }302}303304/// Columns whose widths share the available width in proportion to their weights.305struct WeightedColumnsLayout: Layout {306 var weights: [Double] = []307 var spacing: CGFloat = 12308 var align: String = "top"309310 private func widths(total: CGFloat, count: Int) -> [CGFloat] {311 let w = (0..<count).map { i in i < weights.count && weights[i].isFinite && weights[i] > 0 ? weights[i] : 1 }312 let sum = w.reduce(0, +), available = max(total - spacing * CGFloat(count - 1), 0)313 return w.map { CGFloat($0 / sum) * available }314 }315316 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {317 guard !subviews.isEmpty else { return .zero }318 var total = proposal.width ?? .infinity319 if !total.isFinite { total = subviews.map { $0.sizeThatFits(.unspecified).width }.reduce(0, +) + spacing * CGFloat(subviews.count - 1) }320 let widths = widths(total: total, count: subviews.count)321 let height = zip(subviews, widths).map { $0.sizeThatFits(ProposedViewSize(width: $1, height: nil)).height }.max() ?? 0322 return CGSize(width: total, height: height)323 }324325 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {326 guard !subviews.isEmpty else { return }327 var x = bounds.minX328 for (subview, width) in zip(subviews, widths(total: bounds.width, count: subviews.count)) {329 let size = ProposedViewSize(width: width, height: nil)330 switch align {331 case "center": subview.place(at: CGPoint(x: x, y: bounds.midY), anchor: .leading, proposal: size)332 case "bottom": subview.place(at: CGPoint(x: x, y: bounds.maxY), anchor: .bottomLeading, proposal: size)333 default: subview.place(at: CGPoint(x: x, y: bounds.minY), anchor: .topLeading, proposal: size)334 }335 x += width + spacing336 }337 }338}339340/// Children side by side in weighted columns.341struct ColumnsComponent: View {342 @Environment(\.prismTheme) private var theme343 let o: PrismObject344345 var body: some View {346 WeightedColumnsLayout(347 weights: (o.props["weights"]?.arrayValue ?? []).map { $0.doubleValue ?? 1 },348 spacing: CGFloat(max(o.props["spacing"]?.doubleValue ?? Double(theme.spacing), 0)), align: o.props["align"]?.stringValue ?? "top"349 ) {350 ForEach(o.children, id: \.self) { NodeView(id: $0).frame(maxWidth: .infinity, alignment: .leading) }351 }352 }353}354355/// Children as rows of one grouped panel, separated by hairlines.356struct ListGroupComponent: View {357 @Environment(AppRuntime.self) private var runtime358 let o: PrismObject359360 var body: some View {361 let title = runtime.string(o.props["title"])362 VStack(alignment: .leading, spacing: 6) {363 if !title.isEmpty { Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary).padding(.leading, 12).accessibilityAddTraits(.isHeader) }364 VStack(alignment: .leading, spacing: 0) {365 ForEach(Array(o.children.enumerated()), id: \.element) { index, id in366 if index > 0, o.props["separators"]?.boolValue != false { Divider().padding(.leading, 12) }367 NodeView(id: id).padding(.horizontal, 12).padding(.vertical, 9).frame(maxWidth: .infinity, alignment: .leading)368 }369 }370 .prismSurface()371 }372 }373}374375/// A titled section with an optional subtitle and footer.376struct SectionComponent: View {377 @Environment(AppRuntime.self) private var runtime378 @Environment(\.prismTheme) private var theme379 let o: PrismObject380381 var body: some View {382 let subtitle = runtime.string(o.props["subtitle"]), footer = runtime.string(o.props["footer"])383 VStack(alignment: .leading, spacing: theme.spacing) {384 VStack(alignment: .leading, spacing: 2) {385 Text(runtime.string(o.props["title"])).font(theme.headingFont(.title3)).fontDesign(theme.headingDesign ?? theme.fontDesign).accessibilityAddTraits(.isHeader)386 if !subtitle.isEmpty { Text(subtitle).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }387 }388 ChildrenView(ids: o.children)389 if !footer.isEmpty { Text(footer).font(.footnote).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }390 }391 .frame(maxWidth: .infinity, alignment: .leading)392 }393}394395/// A header band with a large title, a subtitle and a symbol.396struct HeroComponent: View {397 @Environment(AppRuntime.self) private var runtime398 @Environment(\.prismTheme) private var theme399 let o: PrismObject400401 var body: some View {402 let tint = theme.mark(FA.tone(runtime, o, default: "accent"))403 let centered = o.props["align"]?.stringValue == "center"404 let subtitle = runtime.string(o.props["subtitle"])405 let symbol = runtime.string(o.props["symbol"])406 VStack(alignment: centered ? .center : .leading, spacing: 10) {407 if !symbol.isEmpty {408 Image(systemName: SymbolName.safe(symbol)).font(.system(size: 34, weight: .semibold)).foregroundStyle(tint).accessibilityHidden(true)409 }410 Text(runtime.string(o.props["title"])).font(theme.headingFont(.largeTitle)).fontDesign(theme.headingDesign ?? theme.fontDesign)411 .multilineTextAlignment(centered ? .center : .leading).fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)412 if !subtitle.isEmpty {413 Text(subtitle).font(.title3).foregroundStyle(.secondary).multilineTextAlignment(centered ? .center : .leading).fixedSize(horizontal: false, vertical: true)414 }415 if !o.children.isEmpty { HStack(spacing: theme.spacing) { ChildrenView(ids: o.children) }.padding(.top, 4) }416 }417 .padding(24)418 .frame(maxWidth: .infinity, alignment: centered ? .center : .leading)419 .background(LinearGradient(colors: [tint.opacity(0.24), tint.opacity(0.06)], startPoint: .topLeading, endPoint: .bottomTrailing), in: RoundedRectangle(cornerRadius: theme.radius, style: .continuous))420 }421}422423/// A bar for the bottom of a page: a caption and controls.424struct FooterBarComponent: View {425 @Environment(AppRuntime.self) private var runtime426 @Environment(\.prismTheme) private var theme427 let o: PrismObject428429 var body: some View {430 let text = runtime.string(o.props["text"])431 let align = o.props["align"]?.stringValue ?? "trailing"432 HStack(alignment: .center, spacing: theme.spacing) {433 if !text.isEmpty { Text(text).font(.callout).foregroundStyle(.secondary) }434 if align != "leading" { Spacer(minLength: 0) }435 ChildrenView(ids: o.children)436 if align != "trailing" { Spacer(minLength: 0) }437 }438 .fixedSize(horizontal: false, vertical: true)439 .padding(.horizontal, 12).padding(.vertical, 8)440 .frame(maxWidth: .infinity)441 .background(.bar, in: RoundedRectangle(cornerRadius: theme.radius))442 .overlay(RoundedRectangle(cornerRadius: theme.radius).strokeBorder(.separator.opacity(0.6)))443 }444}445446/// A button that shows its children in a popover.447struct PopoverComponent: View {448 @Environment(AppRuntime.self) private var runtime449 @Environment(\.prismTheme) private var theme450 @Environment(\.prismDesign) private var design451 let o: PrismObject452 @State private var shown = false453454 var body: some View {455 let title = runtime.string(o.props["title"])456 let icon = runtime.string(o.props["icon"])457 if design != nil {458 // In Design mode the content is laid out inline so it can be selected.459 GroupBox("Popover: \(title)") { content }460 } else {461 Button { shown.toggle() } label: {462 if !icon.isEmpty, !title.isEmpty { Label(title, systemImage: SymbolName.safe(icon)) }463 else if !icon.isEmpty { Image(systemName: SymbolName.safe(icon)) }464 else { Text(title.isEmpty ? "Show" : title) }465 }466 .disabled(o.children.isEmpty)467 .help(o.children.isEmpty ? "This popover has no content yet." : "")468 .accessibilityLabel(title.isEmpty ? "Show details" : title)469 .popover(isPresented: $shown, arrowEdge: edge) {470 content.padding(16).frame(minWidth: 220, alignment: .leading)471 .environment(runtime).environment(\.prismTheme, theme)472 }473 .onChange(of: shown) { _, now in runtime.fire(now ? "open" : "close", on: o.id) }474 }475 }476477 private var content: some View {478 VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }479 }480481 private var edge: Edge {482 switch o.props["edge"]?.stringValue {483 case "top": .top484 case "leading": .leading485 case "trailing": .trailing486 default: .bottom487 }488 }489}490491/// Wraps its children and shows a help text on hover.492struct TooltipComponent: View {493 @Environment(AppRuntime.self) private var runtime494 @Environment(\.prismTheme) private var theme495 let o: PrismObject496497 var body: some View {498 let text = runtime.string(o.props["text"])499 VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }500 .help(text)501 .accessibilityHint(text)502 }503}504505/// A ribbon label across a corner, or along an edge, of its children.506struct RibbonComponent: View {507 @Environment(AppRuntime.self) private var runtime508 @Environment(\.prismTheme) private var theme509 let o: PrismObject510511 var body: some View {512 let position = o.props["position"]?.stringValue ?? "topTrailing"513 let shape = RoundedRectangle(cornerRadius: theme.radius, style: .continuous)514 let content = VStack(alignment: .leading, spacing: theme.spacing) { ChildrenView(ids: o.children) }.frame(maxWidth: .infinity, alignment: .leading)515 switch position {516 case "top": VStack(spacing: 0) { band.frame(maxWidth: .infinity).background(tint); content }.clipShape(shape)517 case "bottom": VStack(spacing: 0) { content; band.frame(maxWidth: .infinity).background(tint) }.clipShape(shape)518 default:519 let leading = position == "topLeading"520 content521 .frame(minHeight: 72, alignment: .topLeading)522 .overlay(alignment: leading ? .topLeading : .topTrailing) {523 band.frame(width: 150).background(tint)524 .rotationEffect(.degrees(leading ? -45 : 45))525 .offset(x: leading ? -40 : 40, y: 24)526 .shadow(color: .black.opacity(0.18), radius: 2, y: 1)527 }528 .clipShape(shape)529 }530 }531532 private var tint: Color { theme.mark(FA.tone(runtime, o, default: "accent")) }533534 private var band: some View {535 Text(runtime.string(o.props["text"])).font(.caption.weight(.bold)).foregroundStyle(.white).lineLimit(1).padding(.vertical, 4).padding(.horizontal, 8)536 }537}538