Repository Public License
1import PrismComponentSDK2import PrismCore3import PrismObjectModel4import SwiftUI56/// The running app: the real thing the user operates, in PRISM's preview and in a satellite alike.7public struct AppView: View {8 @Bindable var runtime: AppRuntime9 private var theme: PrismTheme { PrismTheme(runtime.blueprint.theme) }1011 public init(runtime: AppRuntime) { self.runtime = runtime }1213 private var navigablePages: [PrismObject] {14 runtime.blueprint.pages.filter { $0.props["showInNavigation"]?.boolValue != false }15 }1617 public var body: some View {18 Group {19 if navigablePages.count > 1 {20 NavigationSplitView {21 List(navigablePages, selection: Binding(get: { Optional(runtime.currentPage) }, set: { if let p = $0 { runtime.currentPage = p } })) { page in22 Label(page.name.isEmpty ? page.id : page.name, systemImage: SymbolName.safe(page.props["icon"]?.stringValue, fallback: "doc"))23 .tag(page.id)24 }25 .navigationSplitViewColumnWidth(min: 160, ideal: 190, max: 260)26 .accessibilityLabel("Pages")27 } detail: {28 PageView(pageID: runtime.currentPage)29 }30 } else {31 PageView(pageID: runtime.currentPage)32 }33 }34 .overlay(alignment: .top) { ToastView(runtime: runtime) }35 .environment(runtime)36 .environment(\.prismTheme, theme)37 .fontDesign(theme.fontDesign)38 .modifier(ThemeText(color: theme.text))39 .tint(theme.accent)40 .preferredColorScheme(theme.colorScheme)41 }42}4344struct PageView: View {45 @Environment(AppRuntime.self) private var runtime46 @Environment(\.prismTheme) private var theme47 let pageID: String4849 var body: some View {50 if let page = runtime.blueprint.object(pageID), page.isPage {51 // The page is size-isolated: whatever layout a blueprint describes, it can never drive the window's constraints.52 SizeIsolated {53 Group {54 if let root = page.children.first {55 NodeView(id: root)56 } else {57 ContentUnavailableView("Empty page", systemImage: "rectangle.dashed", description: Text("This page has no content yet."))58 }59 }60 .padding(CGFloat(page.props["padding"]?.doubleValue ?? Double(theme.pagePadding)))61 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)62 }63 .background { ThemeBackground(theme: theme).ignoresSafeArea() }64 .navigationTitle(page.name.isEmpty ? runtime.blueprint.name : page.name)65 } else {66 ContentUnavailableView("Page not found", systemImage: "questionmark.folder", description: Text("“\(pageID)” is not a page of this app."))67 }68 }69}7071/// The most recent notice, shown briefly at the top of the window.72struct ToastView: View {73 let runtime: AppRuntime74 @Environment(\.prismTheme) private var theme75 @Environment(\.accessibilityReduceMotion) private var reduceMotion76 @State private var shownID: Int?7778 var body: some View {79 let latest = runtime.notices.last80 Group {81 if let notice = latest, notice.id == shownID {82 HStack(spacing: 8) {83 Image(systemName: notice.tone == "danger" ? "xmark.octagon.fill" : notice.tone == "warning" ? "exclamationmark.triangle.fill" : notice.tone == "success" ? "checkmark.circle.fill" : "info.circle.fill")84 .foregroundStyle(theme.tint(notice.tone))85 Text(notice.message).lineLimit(3)86 Button { shownID = nil } label: { Image(systemName: "xmark") }87 .buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel("Dismiss message")88 }89 .font(.callout)90 .padding(.horizontal, 14).padding(.vertical, 9)91 .background(.regularMaterial, in: Capsule())92 .overlay(Capsule().strokeBorder(.separator))93 .shadow(color: .black.opacity(0.12), radius: 8, y: 3)94 .padding(.top, 10)95 .transition(reduceMotion ? .opacity : .move(edge: .top).combined(with: .opacity))96 .accessibilityElement(children: .combine)97 .accessibilityAddTraits(.updatesFrequently)98 }99 }100 .animation(reduceMotion ? nil : .snappy(duration: 0.25), value: shownID)101 .onChange(of: latest?.id) { _, id in102 shownID = id103 guard let id else { return }104 Task {105 try? await Task.sleep(for: .seconds(5))106 if shownID == id { shownID = nil }107 }108 }109 }110}111112/// Applies the theme's text color; `.primary` and `.secondary` then derive from it.113struct ThemeText: ViewModifier {114 let color: Color?115 func body(content: Content) -> some View {116 if let color { content.foregroundStyle(color) } else { content }117 }118}119120enum SymbolName {121 /// Returns the name if the system has that SF Symbol, otherwise the fallback, so a bad name never renders blank.122 static func safe(_ name: String?, fallback: String = "questionmark.square.dashed") -> String {123 guard let name, !name.isEmpty, NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil else { return fallback }124 return name125 }126}127128/// Renders one blueprint object by looking up its component, and applies the props every component shares.129public struct NodeView: View {130 @Environment(AppRuntime.self) private var runtime131 @Environment(\.prismDesign) private var design132 @Environment(\.prismTheme) private var theme133 let id: String134 var extra: [String: JSONValue] = [:]135136 public init(id: String) { self.id = id }137138 public var body: some View {139 if let object = runtime.blueprint.object(id) {140 let p = object.props141 if design != nil || runtime.bool(p["visible"], default: true, extra) {142 content(object)143 .modifier(CommonProps(object: object, runtime: runtime))144 .opacity(design != nil && !runtime.bool(p["visible"], default: true, extra) ? 0.35 : 1)145 .modifier(DesignSelection(id: id, name: object.name.isEmpty ? object.type : object.name, isContainer: !object.children.isEmpty))146 }147 } else {148 Label("Missing component “\(id)”", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)149 }150 }151152 @ViewBuilder153 private func content(_ o: PrismObject) -> some View {154 switch o.type {155 case "prism.text": TextComponent(o: o)156 case "prism.heading": HeadingComponent(o: o)157 case "prism.icon": IconComponent(o: o)158 case "prism.button": ButtonComponent(o: o)159 case "prism.badge": BadgeView(text: runtime.string(o.props["text"]), tone: runtime.string(o.props["tone"]))160 case "prism.card": CardComponent(o: o)161 case "prism.divider": Divider()162 case "prism.progress": ProgressComponent(o: o)163 case "prism.toggle": ToggleComponent(o: o)164 case "prism.stack": StackComponent(o: o)165 case "prism.grid": GridComponent(o: o)166 case "prism.scroll": ScrollComponent(o: o)167 case "prism.split": SplitComponent(o: o)168 case "prism.tabs": TabsComponent(o: o)169 case "prism.toolbar": ToolbarComponent(o: o)170 case "prism.modal": ModalComponent(o: o)171 case "prism.alert": AlertComponent(o: o)172 case "prism.notification": NotificationComponent(o: o)173 case "prism.menu": MenuComponent(o: o)174 case "prism.textField": TextFieldComponent(o: o)175 case "prism.numberField": NumberFieldComponent(o: o, currency: false)176 case "prism.currencyField": NumberFieldComponent(o: o, currency: true)177 case "prism.datePicker": DatePickerComponent(o: o)178 case "prism.dropdown": DropdownComponent(o: o)179 case "prism.search": SearchComponent(o: o)180 case "prism.segmented": SegmentedComponent(o: o)181 case "prism.formSection": FormSectionComponent(o: o)182 case "prism.validationSummary": ValidationSummaryComponent(o: o)183 case "prism.filePicker": FilePickerComponent(o: o)184 case "prism.table": TableComponent(o: o)185 case "prism.csvImport": CSVImportComponent(o: o)186 case "prism.csvExport": CSVExportComponent(o: o)187 case "prism.crud": CrudComponent(o: o)188 case "prism.recordEditor": RecordEditorComponent(o: o)189 case "prism.aggregation": AggregationComponent(o: o)190 case "prism.chart.line": ChartComponent(o: o, kind: .line)191 case "prism.chart.bar": ChartComponent(o: o, kind: .bar)192 case "prism.chart.pie": PieChartComponent(o: o)193 case "prism.sidebar": SidebarComponent(o: o)194 case "prism.inspector": InspectorComponent(o: o)195 case "prism.timer": TimerComponent(o: o)196 default:197 if o.isCustomInstance { CustomComponentView(o: o) } else { ExtendedComponents(o: o) }198 }199 }200}201202/// Shown for a component type this runtime does not know.203struct UnknownComponent: View {204 let o: PrismObject205 var body: some View {206 Group {207 Label("Unknown component “\(o.type)”", systemImage: "puzzlepiece.extension")208 .foregroundStyle(.orange)209 .padding(8)210 .background(.orange.opacity(0.1), in: RoundedRectangle(cornerRadius: 6))211 .accessibilityLabel("Unknown component \(o.type)")212 }213 }214}215216/// Renders the children of a container in order.217struct ChildrenView: View {218 let ids: [String]219 var body: some View { ForEach(ids, id: \.self) { NodeView(id: $0) } }220}221222private struct CommonProps: ViewModifier {223 let object: PrismObject224 let runtime: AppRuntime225226 func body(content: Content) -> some View {227 let p = object.props228 let grow = p["grow"]?.boolValue == true229 let label = runtime.string(p["accessibilityLabel"])230 let help = runtime.string(p["help"])231 content232 .frame(width: p["width"]?.doubleValue.map { CGFloat($0) }, height: p["height"]?.doubleValue.map { CGFloat($0) })233 .frame(maxWidth: grow ? .infinity : nil, maxHeight: grow ? .infinity : nil, alignment: .topLeading)234 .padding(CGFloat(p["padding"]?.doubleValue ?? 0))235 .modifier(OptionalAccessibilityLabel(label: label))236 .help(help)237 }238}239240private struct OptionalAccessibilityLabel: ViewModifier {241 let label: String242 func body(content: Content) -> some View {243 if label.isEmpty { content } else { content.accessibilityLabel(label) }244 }245}246247private struct DesignSelection: ViewModifier {248 @Environment(\.prismDesign) private var design249 let id: String250 let name: String251 let isContainer: Bool252253 func body(content: Content) -> some View {254 if let design {255 // Leaves stop receiving clicks so a button is selected instead of pressed; containers let their children win.256 content257 .allowsHitTesting(isContainer)258 .overlay {259 RoundedRectangle(cornerRadius: 4)260 .strokeBorder(Color.accentColor, style: StrokeStyle(lineWidth: design.selectedID == id ? 2 : 0))261 .allowsHitTesting(false)262 }263 .contentShape(Rectangle())264 .onTapGesture { design.select(id) }265 .accessibilityAction(named: "Select \(name)") { design.select(id) }266 } else {267 content268 }269 }270}271