Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureWorkspace/Tests/ORIXFeatureWorkspaceTests/RenderTests.swift3// Description: Renders the real screens off-screen in several configurations (phone light/dark, large type, iPad zones) to PNG files for visual review.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7#if canImport(UIKit)8import SwiftUI9import Testing10import UIKit11import ORIXUI12import ORIXWorkspace13@testable import ORIXFeatureWorkspace1415/// Captures the layer tree of a window. In the package test runner this cannot draw a list whose content scrolls, so sheets are16/// rendered on canvases tall enough to show every cell; the proportions are therefore not those of a device screen.17@MainActor func snapshot<V: View>(_ view: V, size: CGSize, dark: Bool = false, type: DynamicTypeSize = .large, name: String) async throws -> UIImage? {18 let host = UIHostingController(rootView: view.environment(\.dynamicTypeSize, type).preferredColorScheme(dark ? .dark : .light))19 // The runner's window scene connects shortly after launch; without one nothing can be drawn and the snapshot is skipped.20 var found: UIWindowScene?21 for _ in 0..<(SceneProbe.gaveUp ? 1 : 50) {22 found = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first23 if found != nil { break }24 try await Task.sleep(for: .milliseconds(100))25 }26 guard let scene = found else {27 SceneProbe.gaveUp = true28 print("SHOT \(name) skipped: the test runner has no window scene")29 return nil30 }31 let window = UIWindow(windowScene: scene)32 window.frame = CGRect(origin: .zero, size: size)33 window.overrideUserInterfaceStyle = dark ? .dark : .light34 window.rootViewController = host35 window.makeKeyAndVisible()36 window.layoutIfNeeded()37 try await Task.sleep(for: .milliseconds(900))38 window.layoutIfNeeded()39 CATransaction.flush()40 let image = UIGraphicsImageRenderer(bounds: window.bounds).image { context in41 // Without a host application there is no screen to capture: render the layer tree instead.42 window.layer.render(in: context.cgContext)43 }44 try? FileManager.default.createDirectory(atPath: shotsDirectory, withIntermediateDirectories: true)45 try image.pngData()?.write(to: URL(fileURLWithPath: "\(shotsDirectory)/\(name).png"))46 window.isHidden = true47 return image48}4950@MainActor enum SceneProbe { static var gaveUp = false }5152@MainActor @Suite(.serialized) struct RenderTests {53 func demoStore(_ app: AppModel) -> WorkspaceStore {54 let store = WorkspaceStore(app: app, demo: true)55 return store56 }57 func layout(_ store: WorkspaceStore, _ app: AppModel, width: CGFloat) -> some View {58 WorkspaceLayout(store: store, width: width).environment(app).tint(CalcMode.workspace.tint).background(ORIXColor.background)59 }6061 @Test func phoneLightAndDark() async throws {62 let app = makeApp()63 app.mode = .workspace64 let store = demoStore(app)65 let npvCell = try #require(store.sheet?.cellDefining("NPV"))66 store.sheet?.selection = npvCell.id67 let size = CGSize(width: 393, height: 2700)68 let light = try await snapshot(layout(store, app, width: size.width), size: size, name: "phone-light")69 let dark = try await snapshot(layout(store, app, width: size.width), size: size, dark: true, name: "phone-dark")70 #expect(light == nil || light?.size == size)71 #expect(dark == nil || dark?.size == size)72 }7374 @Test func phoneAccessibilityType() async throws {75 let app = makeApp()76 let store = demoStore(app)77 let size = CGSize(width: 393, height: 6200)78 _ = try await snapshot(layout(store, app, width: size.width), size: size, type: .accessibility3, name: "phone-ax3")79 }8081 @Test func phoneLibraryAndInspector() async throws {82 let app = makeApp()83 let store = WorkspaceStore(app: app)84 let size = CGSize(width: 393, height: 852)85 _ = try await snapshot(layout(store, app, width: size.width), size: size, name: "phone-library-empty")86 for template in WorkspaceTemplate.allCases { store.create(template: template) }87 store.close()88 _ = try await snapshot(layout(store, app, width: size.width), size: size, name: "phone-library")89 store.create(template: .projectile)90 let sheet = try #require(store.sheet)91 sheet.selection = sheet.cells.first { $0.kind == .parameter }?.id92 _ = try await snapshot(NavigationStack { InspectorView(sheet: sheet, embedded: false) }.environment(app).tint(CalcMode.workspace.tint), size: size, name: "phone-inspector-parameter")93 sheet.selection = sheet.cellDefining("Distance")?.id94 _ = try await snapshot(NavigationStack { InspectorView(sheet: sheet, embedded: false) }.environment(app).tint(CalcMode.workspace.tint), size: size, dark: true, name: "phone-inspector-formula-dark")95 _ = try await snapshot(DocumentSettingsView(sheet: sheet).environment(app), size: size, name: "phone-settings")96 }9798 @Test func padThreeZones() async throws {99 let app = makeApp()100 let store = WorkspaceStore(app: app)101 store.create(template: .loanComparison)102 store.create(template: .unitEconomics)103 store.create(template: .capitalBudgeting)104 let sheet = try #require(store.sheet)105 sheet.selection = sheet.cellDefining("NPV")?.id106 let wide = CGSize(width: 1094, height: 2500)107 _ = try await snapshot(layout(store, app, width: wide.width), size: wide, name: "pad-three-zones")108 _ = try await snapshot(layout(store, app, width: wide.width), size: wide, dark: true, name: "pad-three-zones-dark")109 let medium = CGSize(width: 922, height: 2500)110 _ = try await snapshot(layout(store, app, width: medium.width), size: medium, name: "pad-two-zones")111 store.close()112 _ = try await snapshot(layout(store, app, width: wide.width), size: wide, name: "pad-empty")113 }114115 @Test func errorsAndGraphProvider() async throws {116 let app = makeApp()117 let document = WorkspaceDocument(title: "Errors", cells: [118 .text("# Error states"), .formula("a = b + 1"), .formula("b = a + 1"), .formula("c = 1/0"), .formula("d = c + 1", unit: "kg"),119 .formula("ratio = 1/3"), .formula("root = sqrt(2)", unit: "m"), .formula("f(x) = x^2 + 1"),120 .table(TableSpec(expression: "1/x", variable: "x", start: -2, step: 1, count: 5)),121 .graph(GraphSpec(expressions: ["f(x)", "sin(x)"])),122 ])123 app.pendingWorkspaceDocument = document124 let store = WorkspaceStore(app: app)125 let size = CGSize(width: 393, height: 1500)126 _ = try await snapshot(layout(store, app, width: size.width), size: size, name: "phone-errors")127 // with a provider installed, the graph cell hosts whatever the Graph environment returns (a stand-in here, only to check the frame)128 let provider = GraphPreviewProvider { request in129 AnyView(ZStack { ORIXColor.surfaceRaised; Text("provider view for \(request.expressions.joined(separator: ", "))").font(.caption) })130 }131 _ = try await snapshot(layout(store, app, width: size.width).environment(\.graphPreview, provider), size: size, dark: true, name: "phone-errors-provider-dark")132 }133}134#endif135