Repository Public License
1import AppKit2import Foundation3import SwiftUI4import Testing5import PrismComponentCatalog6import PrismComponentSDK7import PrismCore8import PrismObjectModel9@testable import PrismRenderer1011/// Behaviour of the family A components (layout, display, text, feedback) beyond "the fixture renders".12@MainActor13@Suite(.serialized) struct FamilyATests {14 static let familyTypes: [String] = [15 "prism.spacer", "prism.box", "prism.center", "prism.overlay", "prism.wrap", "prism.accordion", "prism.disclosure", "prism.carousel", "prism.aspect",16 "prism.columns", "prism.listGroup", "prism.section", "prism.hero", "prism.footerBar", "prism.avatar", "prism.avatarGroup", "prism.keyValue",17 "prism.descriptionList", "prism.trend", "prism.tagList", "prism.chip", "prism.ratingDisplay", "prism.timeline", "prism.steps", "prism.breadcrumb",18 "prism.codeBlock", "prism.quote", "prism.callout", "prism.markdown", "prism.link", "prism.shortcut", "prism.emptyState", "prism.skeleton", "prism.banner",19 "prism.statusDot", "prism.counterBadge", "prism.ring", "prism.gauge", "prism.meter", "prism.colorSwatch", "prism.qrCode", "prism.clock", "prism.countdown",20 "prism.spinner", "prism.confirm", "prism.popover", "prism.tooltip", "prism.loadingOverlay", "prism.featureList", "prism.pricingCard", "prism.symbolTile",21 "prism.label", "prism.ribbon", "prism.legend",22 ]2324 /// A one-page app holding the given components in a stack.25 func app(_ objects: [PrismObject], state: [String: JSONValue] = [:]) throws -> AppRuntime {26 var bp = AppBlueprint(id: "app_family_a", name: "Family A", entrypoint: "home")27 bp.state = state28 let childIDs = Set(objects.flatMap(\.children))29 bp.objects = [30 PrismObject(id: "home", type: ObjectType.page, name: "Home", children: ["root"]),31 PrismObject(id: "root", type: "prism.stack", children: objects.map(\.id).filter { !childIDs.contains($0) }),32 ] + objects33 let issues = BlueprintValidator.validate(bp, registry: Catalog.registry)34 #expect(issues.errors.isEmpty, "\(issues.errors)")35 return try makeRuntime(bp)36 }3738 // MARK: Catalog coverage3940 @Test func rendererCoversExactlyTheFamilyAManifests() {41 #expect(Self.familyTypes.count == 54 && Set(Self.familyTypes).count == 54)42 #expect(FamilyAComponents.types == Set(Self.familyTypes))43 let declared = Set(Catalog.manifests.map(\.type))44 #expect(FamilyAComponents.types.isSubset(of: declared), "missing manifests: \(FamilyAComponents.types.subtracting(declared).sorted())")45 // No family A type is also drawn by the core switch or another family.46 #expect(FamilyAComponents.types.isDisjoint(with: FamilyBComponents.types) && FamilyAComponents.types.isDisjoint(with: FamilyCComponents.types))47 }4849 @Test func manifestsUseTheAgreedCategoriesAndKnownEvents() throws {50 let allowed: Set<String> = ["layout", "display", "text", "feedback", "time", "foundation"]51 for type in Self.familyTypes {52 let m = try #require(Catalog.registry.manifest(type), "\(type) is not in the registry")53 #expect(allowed.contains(m.category), "\(type): \(m.category)")54 #expect(m.keywords.count >= 4, "\(type) needs four keywords")55 #expect(m.events.allSatisfy(ComponentManifest.knownEvents.contains), "\(type)")56 #expect(m.props.allSatisfy { p in !CommonProps.all.contains { $0.name == p.name } }, "\(type) redeclares a common prop")57 // The Library builds a new object from the first fixture object: it must be the component itself.58 #expect(m.fixture["objects"]?[0]?["type"]?.stringValue == type, "\(type)")59 }60 }6162 // MARK: Link6364 @Test func linkAcceptsOnlyWebAddresses() {65 #expect(FamilyALink.sanitized("https://example.com/docs?q=1")?.absoluteString == "https://example.com/docs?q=1")66 #expect(FamilyALink.sanitized(" HTTP://example.com ")?.host == "example.com")67 for refused in ["file:///etc/passwd", "javascript:alert(1)", "mailto:a@example.com", "ftp://example.com/x", "x-apple.systempreferences:com.apple.preference",68 "example.com", "//example.com", "https://", "https:///path", "https://user:secret@example.com", "data:text/html,hi", "tel:5551234", "", " "] {69 #expect(FamilyALink.sanitized(refused) == nil, "\(refused) must be refused")70 }71 }7273 @Test func linkNeverCallsTheOpenerForARefusedAddress() {74 var opened: [URL] = []75 #expect(FamilyALink.open("file:///Applications", with: { opened.append($0); return true }) == false)76 #expect(FamilyALink.open("javascript:alert(1)", with: { opened.append($0); return true }) == false)77 #expect(opened.isEmpty)78 #expect(FamilyALink.open("https://example.com/a", with: { opened.append($0); return true }))79 #expect(opened.map(\.absoluteString) == ["https://example.com/a"])80 // The opener's own failure is reported, not hidden.81 #expect(FamilyALink.open("https://example.com/a", with: { _ in false }) == false)82 }8384 // MARK: Countdown and clock8586 @Test func countdownParsesDatesAndDateTimes() throws {87 let utc = try #require(TimeZone(identifier: "UTC")), toronto = try #require(TimeZone(identifier: "America/Toronto"))88 #expect(FamilyATime.target("2027-01-01", timeZone: utc) == Date(timeIntervalSince1970: 1_798_761_600))89 // A plain date is local midnight: five hours later in Toronto (EST) than in UTC.90 #expect(FamilyATime.target("2027-01-01", timeZone: toronto) == Date(timeIntervalSince1970: 1_798_761_600 + 5 * 3_600))91 #expect(FamilyATime.target("2027-01-01T18:30", timeZone: utc) == Date(timeIntervalSince1970: 1_798_761_600 + 18 * 3_600 + 30 * 60))92 #expect(FamilyATime.target("2027-01-01 18:30:15", timeZone: utc) == Date(timeIntervalSince1970: 1_798_761_600 + 18 * 3_600 + 30 * 60 + 15))93 // An explicit zone wins over the local one.94 #expect(FamilyATime.target("2027-01-01T00:00:00Z", timeZone: toronto) == Date(timeIntervalSince1970: 1_798_761_600))95 #expect(FamilyATime.target("2027-01-01T02:00:00+02:00", timeZone: toronto) == Date(timeIntervalSince1970: 1_798_761_600))96 for bad in ["", "tomorrow", "2027-13-01", "2027-02-30", "27-01-01", "2027/01/01", "2027-01-01T25:00", "2027-01-01T10", "20270101"] {97 #expect(FamilyATime.target(bad, timeZone: utc) == nil, "\(bad) is not a date")98 }99 }100101 @Test func countdownMaths() {102 let now = Date(timeIntervalSince1970: 1_000_000)103 func left(_ seconds: TimeInterval) -> FamilyATime.Remaining { FamilyATime.remaining(from: now, to: now.addingTimeInterval(seconds)) }104 #expect(left(2 * 86_400 + 3 * 3_600 + 4 * 60 + 5) == .init(days: 2, hours: 3, minutes: 4, seconds: 5))105 #expect(left(59) == .init(days: 0, hours: 0, minutes: 0, seconds: 59))106 #expect(left(3_600) == .init(days: 0, hours: 1, minutes: 0, seconds: 0))107 // A started second still counts, so the display never shows zero early.108 #expect(left(0.2) == .init(days: 0, hours: 0, minutes: 0, seconds: 1) && !left(0.2).isOver)109 #expect(left(0).isOver && left(-500).isOver)110 #expect(left(-500) == .init(days: 0, hours: 0, minutes: 0, seconds: 0))111 }112113 @Test func clockFormatsFollowTheZone() throws {114 let date = Date(timeIntervalSince1970: 1_798_761_600 + 13 * 3_600 + 5 * 60 + 9) // 2027-01-01 13:05:09 UTC115 let utc = try #require(TimeZone(identifier: "UTC")), paris = try #require(TimeZone(identifier: "Europe/Paris"))116 let us = Locale(identifier: "en_US")117 let narrow = "\u{202F}"118 #expect(FamilyATime.clock(date, format: "time", timeZone: utc, locale: us).replacingOccurrences(of: narrow, with: " ") == "1:05 PM")119 #expect(FamilyATime.clock(date, format: "timeWithSeconds", timeZone: paris, locale: us).replacingOccurrences(of: narrow, with: " ") == "2:05:09 PM")120 #expect(FamilyATime.clock(date, format: "date", timeZone: utc, locale: us) == "Friday, January 1, 2027")121 #expect(FamilyATime.clock(date, format: "dateTime", timeZone: utc, locale: us).contains("Jan 1, 2027"))122 }123124 // MARK: QR code125126 @Test func qrCodeProducesASquareImageThatDependsOnTheText() throws {127 let short = try #require(FamilyAQR.image("https://example.com"))128 #expect(short.width == short.height && short.width >= 21)129 let long = try #require(FamilyAQR.image(String(repeating: "PRISM builds apps from verified components. ", count: 8)))130 #expect(long.width > short.width, "more data needs more modules")131 let sturdy = try #require(FamilyAQR.image("https://example.com", correction: "H"))132 #expect(sturdy.width >= short.width)133 #expect(FamilyAQR.image("") == nil)134 // Enlarging keeps whole modules: the side is a multiple of the module count and reaches the requested size.135 let large = try #require(FamilyAQR.image("https://example.com", minimumSide: 400))136 #expect(large.width == large.height && large.width >= 400 && large.width % short.width == 0)137 // The bitmap really holds dark and light modules.138 let rep = NSBitmapImageRep(cgImage: short)139 var dark = 0, light = 0140 for x in 0..<rep.pixelsWide { for y in 0..<rep.pixelsHigh { if (rep.colorAt(x: x, y: y)?.usingColorSpace(.sRGB)?.brightnessComponent ?? 1) < 0.5 { dark += 1 } else { light += 1 } } }141 #expect(dark > 50 && light > 50)142 }143144 // MARK: Formatting helpers145146 @Test func formattingHelpers() {147 let us = Locale(identifier: "en_US")148 #expect(FamilyAFormat.initials("Ada Lovelace") == "AL")149 #expect(FamilyAFormat.initials(" grace brewster murray hopper ") == "GB")150 #expect(FamilyAFormat.initials("Zoë") == "Z" && FamilyAFormat.initials("") == "")151 #expect(FamilyAFormat.delta(0.124, percent: true, locale: us) == "+12.4%")152 #expect(FamilyAFormat.delta(-0.05, percent: true, locale: us) == "-5%")153 #expect(FamilyAFormat.delta(3, percent: false, locale: us) == "+3" && FamilyAFormat.delta(0, percent: false, locale: us) == "0")154 #expect(FamilyAFormat.trendTone(delta: 0.1, positiveIsGood: true) == "success" && FamilyAFormat.trendTone(delta: 0.1, positiveIsGood: false) == "danger")155 #expect(FamilyAFormat.trendTone(delta: -2, positiveIsGood: false) == "success" && FamilyAFormat.trendTone(delta: 0, positiveIsGood: true) == "neutral")156 #expect(FamilyAFormat.stars(value: 3.5, max: 5) == ["star.fill", "star.fill", "star.fill", "star.leadinghalf.filled", "star"])157 #expect(FamilyAFormat.stars(value: 9, max: 3) == ["star.fill", "star.fill", "star.fill"] && FamilyAFormat.stars(value: -1, max: 2) == ["star", "star"])158 #expect(FamilyAFormat.counter(7, max: 99) == "7" && FamilyAFormat.counter(128, max: 99) == "99+" && FamilyAFormat.counter(100, max: 0) == "100")159 #expect(FamilyAFormat.fraction(68, min: 0, max: 100) == 0.68 && FamilyAFormat.fraction(150, min: 0, max: 100) == 1 && FamilyAFormat.fraction(-3, min: 0, max: 100) == 0)160 #expect(FamilyAFormat.fraction(5, min: 10, max: 10) == 0 && FamilyAFormat.fraction(.nan, min: 0, max: 1) == 0)161 #expect(["cmd", "Shift", "option", "ctrl", "k", "return", "F5"].map(FamilyAFormat.keycap) == ["⌘", "⇧", "⌥", "⌃", "K", "↩", "F5"])162 #expect(FamilyAFormat.keyName("cmd") == "Command" && FamilyAFormat.keyName("k") == "K")163 }164165 @Test func markdownIsInlineAndNeverFails() {166 let rich = FamilyAFormat.markdown("Import a **CSV** file, see the [guide](https://example.com/guide).")167 #expect(String(rich.characters) == "Import a CSV file, see the guide.")168 #expect(rich.runs.contains { $0.link?.absoluteString == "https://example.com/guide" })169 #expect(rich.runs.contains { $0.inlinePresentationIntent == .stronglyEmphasized })170 // Block syntax is not interpreted, and line breaks survive.171 #expect(String(FamilyAFormat.markdown("# Not a heading\nsecond line").characters) == "# Not a heading\nsecond line")172 #expect(String(FamilyAFormat.markdown("**unclosed").characters).contains("unclosed"))173 }174175 // MARK: Layouts176177 @Test func flowLayoutWrapsWhenTheWidthRunsOut() {178 func height(_ width: CGFloat, align: String = "leading") -> CGFloat {179 let view = FlowLayout(spacing: 10, lineSpacing: 10, align: align) { ForEach(0..<6, id: \.self) { _ in Color.red.frame(width: 100, height: 20) } }180 let host = NSHostingView(rootView: view.frame(width: width).fixedSize(horizontal: false, vertical: true))181 return host.fittingSize.height182 }183 #expect(height(700) == 20, "six 100-pt chips fit on one 700-pt line")184 #expect(height(330) == 50, "three per line gives two lines")185 #expect(height(120) == 170, "one per line gives six lines")186 #expect(height(330, align: "center") == 50)187 }188189 @Test func weightedColumnsShareTheWidth() {190 let layout = WeightedColumnsLayout(weights: [2, 1], spacing: 20, align: "top")191 let view = layout { Color.red.frame(height: 30); Color.blue.frame(height: 50) }192 let host = NSHostingView(rootView: view.frame(width: 320).fixedSize(horizontal: false, vertical: true))193 #expect(host.fittingSize.height == 50, "the row is as tall as its tallest column")194 #expect(host.fittingSize.width == 320)195 }196197 // MARK: State and events through the runtime198199 @Test func boundComponentsRenderFromStateAndEventsRunActions() throws {200 let rt = try app([201 PrismObject(id: "crumbs", type: "prism.breadcrumb", props: ["items": ["Home", ["title": "Projects", "value": "projects"], "Atlas"]],202 events: ["click": [["type": "setState", "key": "place", "value": ["$expr": "value"]]]]),203 PrismObject(id: "bar", type: "prism.banner", props: ["title": "Update ready", "presented": ["$bind": "showBanner"]],204 events: ["dismiss": [["type": "setState", "key": "dismissals", "value": ["$expr": "state.dismissals + 1"]]]]),205 PrismObject(id: "swatch", type: "prism.colorSwatch", props: ["colors": ["#FF0000", "#00FF00"], "selection": ["$bind": "color"]],206 events: ["select": [["type": "setState", "key": "picked", "value": ["$expr": "value"]]]]),207 PrismObject(id: "ask", type: "prism.confirm", props: ["presented": ["$bind": "asking"], "title": "Delete?"],208 events: ["confirm": [["type": "setState", "key": "place", "value": "deleted"]], "cancelled": [["type": "setState", "key": "place", "value": "kept"]]]),209 PrismObject(id: "timer", type: "prism.countdown", props: ["until": "2000-01-01"], events: ["complete": [["type": "setState", "key": "place", "value": "done"]]]),210 PrismObject(id: "busy", type: "prism.loadingOverlay", props: ["loading": ["$expr": "state.asking"]], children: ["inner"]),211 PrismObject(id: "inner", type: "prism.text", props: ["text": "Inside"]),212 ], state: ["place": "", "showBanner": true, "dismissals": 0, "color": "#00FF00", "picked": "", "asking": false])213214 // The events the views fire reach the actions with the documented payloads.215 rt.fire("click", on: "crumbs", value: "projects")216 #expect(rt.state["place"] == "projects")217 rt.fire("click", on: "crumbs", value: 0)218 #expect(rt.state["place"] == 0)219 rt.fire("select", on: "swatch", value: "#FF0000")220 #expect(rt.state["picked"] == "#FF0000")221 rt.fire("dismiss", on: "bar")222 #expect(rt.state["dismissals"] == 1)223 rt.fire("confirm", on: "ask")224 #expect(rt.state["place"] == "deleted")225 rt.fire("cancelled", on: "ask")226 #expect(rt.state["place"] == "kept")227228 // Rendering a countdown that is already over shows the done text and does not fire `complete`.229 let rep = try #require(renderBitmap(AppView(runtime: rt), size: CGSize(width: 640, height: 420)))230 #expect(distinctColors(rep) > 2)231 #expect(rt.state["place"] == "kept", "a countdown that opens already over must stay silent")232 #expect(!rt.logs.contains { $0.level != .info }, "\(rt.logs.filter { $0.level != .info }.map(\.message))")233234 // A banner bound to state disappears when its key turns false.235 let shown = distinctColors(try #require(renderBitmap(NodeViewHost(runtime: rt, id: "bar"), size: CGSize(width: 400, height: 80))))236 rt.setState("showBanner", false)237 let hidden = distinctColors(try #require(renderBitmap(NodeViewHost(runtime: rt, id: "bar"), size: CGSize(width: 400, height: 80))))238 #expect(shown > 1 && hidden == 1)239 }240241 @Test func hiddenAtRestComponentsDrawNothing() throws {242 let rt = try app([243 PrismObject(id: "zero", type: "prism.counterBadge", props: ["count": 0]),244 PrismObject(id: "seven", type: "prism.counterBadge", props: ["count": 7]),245 PrismObject(id: "shownZero", type: "prism.counterBadge", props: ["count": 0, "hideZero": false]),246 ])247 func colors(_ id: String) throws -> Int { distinctColors(try #require(renderBitmap(NodeViewHost(runtime: rt, id: id), size: CGSize(width: 120, height: 60)))) }248 #expect(try colors("zero") == 1)249 #expect(try colors("seven") > 1)250 #expect(try colors("shownZero") > 1)251 }252253 @Test func everyFamilyAFixtureAlsoRendersInDarkModeAndDesignMode() throws {254 for type in Self.familyTypes {255 let manifest = try #require(Catalog.registry.manifest(type))256 let rt = try makeRuntime(try manifest.fixtureBlueprint())257 let dark = AppView(runtime: rt).environment(\.colorScheme, .dark)258 #expect(renderBitmap(dark, size: CGSize(width: 480, height: 320)) != nil, "\(type)")259 let design = AppView(runtime: rt).environment(\.prismDesign, DesignContext(selectedID: "fx", select: { _ in }))260 let rep = try #require(renderBitmap(design, size: CGSize(width: 480, height: 320)), "\(type)")261 #expect(distinctColors(rep) > 1, "\(type) is blank in Design mode")262 #expect(!rt.logs.contains { $0.level != .info }, "\(type): \(rt.logs.filter { $0.level != .info }.map(\.message))")263 }264 }265}266267/// One component of a running app, hosted alone for a bitmap.268private struct NodeViewHost: View {269 let runtime: AppRuntime270 let id: String271 var body: some View { NodeView(id: id).environment(runtime).environment(\.prismTheme, PrismTheme()) }272}273