Repository Public License
1import AppKit2import Foundation3import SwiftUI4import Testing5import PrismComponentCatalog6import PrismComponentSDK7import PrismCore8import PrismDataRuntime9import PrismObjectModel10@testable import PrismRenderer1112/// Renders a SwiftUI view off-screen and returns its bitmap. This is the real renderer, not a mock.13@MainActor14func renderBitmap<V: View>(_ view: V, size: CGSize = CGSize(width: 900, height: 620)) -> NSBitmapImageRep? {15 let host = NSHostingView(rootView: view.frame(width: size.width, height: size.height).background(Color(nsColor: .windowBackgroundColor)))16 host.frame = CGRect(origin: .zero, size: size)17 let window = NSWindow(contentRect: host.frame, styleMask: [.borderless], backing: .buffered, defer: false)18 window.contentView = host19 host.layoutSubtreeIfNeeded()20 RunLoop.main.run(until: Date().addingTimeInterval(0.15))21 host.layoutSubtreeIfNeeded()22 guard let rep = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { return nil }23 host.cacheDisplay(in: host.bounds, to: rep)24 return rep25}2627/// Number of clearly different colors on a coarse sample grid: 1 means a blank image.28func distinctColors(_ rep: NSBitmapImageRep) -> Int {29 var seen = Set<Int>()30 for x in stride(from: 2, to: rep.pixelsWide, by: 6) {31 for y in stride(from: 2, to: rep.pixelsHigh, by: 6) {32 guard let c = rep.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) else { continue }33 seen.insert(Int(c.redComponent * 15) << 8 | Int(c.greenComponent * 15) << 4 | Int(c.blueComponent * 15))34 }35 }36 return seen.count37}3839func saveSnapshot(_ rep: NSBitmapImageRep, _ name: String) {40 let dir = repoRoot.appendingPathComponent("build/snapshots")41 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)42 try? rep.representation(using: .png, properties: [:])?.write(to: dir.appendingPathComponent(name + ".png"))43}4445@MainActor46@Suite(.serialized) struct RenderTests {47 @Test(arguments: Catalog.manifests.map(\.type))48 func everyComponentFixtureRenders(type: String) throws {49 let manifest = try #require(Catalog.registry.manifest(type))50 let rt = try makeRuntime(try manifest.fixtureBlueprint())51 let rep = try #require(renderBitmap(AppView(runtime: rt), size: CGSize(width: 640, height: 420)))52 saveSnapshot(rep, "component-" + type.replacingOccurrences(of: ".", with: "-"))53 #expect(rep.pixelsWide >= 640)54 // State-hidden components draw nothing at rest, and a hairline divider falls between the sample points.55 let drawsNothingAtRest: Set<String> = ["prism.modal", "prism.validationSummary", "prism.divider"]56 // Components whose accessibility role is `none` are invisible by contract (timers and other logic).57 if !drawsNothingAtRest.contains(type), manifest.accessibilityRole != "none" { #expect(distinctColors(rep) > 1, "\(type) rendered a blank image") }58 #expect(!rt.logs.contains { $0.level == .error }, "\(type): \(rt.logs.filter { $0.level == .error }.map(\.message))")59 }6061 @Test func expenseTrackerRendersWithData() throws {62 let rt = try makeRuntime(try expenseTracker())63 _ = rt.importCSV(from: sampleCSVURL, into: "transactions")64 let rep = try #require(renderBitmap(AppView(runtime: rt), size: CGSize(width: 1100, height: 700)))65 saveSnapshot(rep, "expense-tracker")66 #expect(distinctColors(rep) > 12, "The app should draw a table, tiles and a colored chart.")67 #expect(!rt.logs.contains { $0.level != .info }, "\(rt.logs.filter { $0.level != .info }.map(\.message))")68 }6970 @Test func designModeRendersHiddenComponentsAndUnknownTypesSafely() throws {71 var bp = try expenseTracker()72 bp.objects.append(PrismObject(id: "mystery", type: "prism.hologram"))73 bp.objects[bp.index(of: "root")!].children.append("mystery")74 let rt = try makeRuntime(bp)75 let view = AppView(runtime: rt).environment(\.prismDesign, DesignContext(selectedID: "stats", select: { _ in }))76 let rep = try #require(renderBitmap(view, size: CGSize(width: 1100, height: 760)))77 saveSnapshot(rep, "expense-tracker-design")78 #expect(distinctColors(rep) > 8)79 }8081 @Test func fiftyComponentAppRenders() throws {82 var bp = AppBlueprint(id: "app_big", name: "Big", entrypoint: "home")83 var ids: [String] = []84 for i in 0..<60 {85 ids.append("t\(i)")86 bp.objects.append(PrismObject(id: "t\(i)", type: i % 3 == 0 ? "prism.badge" : "prism.text", props: ["text": .string("Item \(i)")]))87 }88 bp.objects.append(PrismObject(id: "home", type: ObjectType.page, name: "Home", children: ["grid"]))89 bp.objects.append(PrismObject(id: "grid", type: "prism.grid", props: ["columns": 6], children: ids))90 #expect(BlueprintValidator.validate(bp, registry: Catalog.registry).errors.isEmpty)91 let rep = try #require(renderBitmap(AppView(runtime: try makeRuntime(bp))))92 #expect(distinctColors(rep) > 2)93 }94}95