Repository Public
1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/Snapshot.swift3// Description: Hosted renders of the feature screens without any visible window: a SwiftUI view is laid out in an4// off-screen hosting view and written as PNG in light / dark × compact / regular under5// /tmp/spnote-next/shots-native (override with SPN_SHOTS_DIR). Not golden files: the renders are looked at6// by a human; the test only checks that something was really drawn.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10#if os(macOS)11import AppKit12import SPNotesDesign13import SPNotesFeatures14import SPNotesFeaturesCatalog15import SwiftUI16import Testing1718@MainActor19enum Snapshot {20 static let directory: URL = {21 let path = ProcessInfo.processInfo.environment["SPN_SHOTS_DIR"] ?? "/tmp/spnote-next/shots-native"22 let url = URL(fileURLWithPath: path)23 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)24 return url25 }()2627 static let compact = CGSize(width: 390, height: 844)28 static let regular = CGSize(width: 1180, height: 820)2930 /// Renders the four variants `<name>-<light|dark>-<compact|regular>.png` and checks each one is not blank.31 /// - Parameter settle: run-loop time given to `.task`, `Canvas` and layout before the capture.32 @discardableResult33 static func render<V: View>(_ name: String, compactSize: CGSize = compact, regularSize: CGSize = regular, settle: TimeInterval = 0.35,34 sourceLocation: SourceLocation = #_sourceLocation, @ViewBuilder _ view: () -> V) -> [URL] {35 var urls: [URL] = []36 let content = view()37 for scheme in [ColorScheme.light, .dark] {38 for sizeClass in FeatureSizeClass.allCases {39 let size = sizeClass == .compact ? compactSize : regularSize40 let file = directory.appendingPathComponent("\(name)-\(scheme == .dark ? "dark" : "light")-\(sizeClass.rawValue).png")41 let colours = capture(content, size: size, scheme: scheme, sizeClass: sizeClass, settle: settle, to: file)42 #expect(colours > 8, "the render \(file.lastPathComponent) looks blank (\(colours) distinct colours)", sourceLocation: sourceLocation)43 urls.append(file)44 }45 }46 return urls47 }4849 /// One capture that lets the view's own `.task` run: a nested run loop cannot run main-actor jobs (the test itself is50 /// one), so the wait alternates real suspensions with short run-loop turns. Use it for views that load by themselves.51 @discardableResult52 static func captureLoading<V: View>(_ view: V, size: CGSize, scheme: ColorScheme, sizeClass: FeatureSizeClass?, settle: TimeInterval = 1.0, to file: URL) async -> Int {53 let (window, hosting) = host(view, size: size, scheme: scheme, sizeClass: sizeClass)54 defer { window.contentView = nil }55 let end = Date().addingTimeInterval(settle)56 while Date() < end {57 try? await Task.sleep(for: .milliseconds(30))58 spin(0.02)59 }60 hosting.layoutSubtreeIfNeeded()61 spin(0.1)62 var colours = write(hosting, to: file)63 // Under load (the whole target runs in parallel) a view may still be loading: wait for real content, up to 20 s.64 let deadline = Date().addingTimeInterval(20)65 while colours <= 8, Date() < deadline {66 try? await Task.sleep(for: .milliseconds(100))67 spin(0.05)68 hosting.layoutSubtreeIfNeeded()69 colours = write(hosting, to: file)70 }71 return colours72 }7374 private static func spin(_ seconds: TimeInterval) { RunLoop.main.run(until: Date().addingTimeInterval(seconds)) }7576 /// One capture; returns the number of distinct colours sampled on a grid (a blank render has 1 or 2).77 @discardableResult78 static func capture<V: View>(_ view: V, size: CGSize, scheme: ColorScheme, sizeClass: FeatureSizeClass?, settle: TimeInterval = 0.35, to file: URL) -> Int {79 let (window, hosting) = host(view, size: size, scheme: scheme, sizeClass: sizeClass)80 defer { window.contentView = nil }81 spin(settle)82 hosting.layoutSubtreeIfNeeded()83 return write(hosting, to: file)84 }8586 private static func host<V: View>(_ view: V, size: CGSize, scheme: ColorScheme, sizeClass: FeatureSizeClass?) -> (NSWindow, NSView) {87 _ = NSApplication.shared88 let root = view89 .featureSizeClass(sizeClass)90 .environment(\.featureNow, FeatureSamples.now)91 .environment(\.colorScheme, scheme)92 .transaction { $0.disablesAnimations = true }93 .frame(width: size.width, height: size.height)94 .background(NVColor.bg)95 let hosting = NSHostingView(rootView: root)96 hosting.appearance = NSAppearance(named: scheme == .dark ? .darkAqua : .aqua)97 hosting.frame = CGRect(origin: .zero, size: size)98 // Never ordered in: the window only gives the view a backing store and an appearance.99 let window = NSWindow(contentRect: CGRect(x: -20_000, y: -20_000, width: size.width, height: size.height), styleMask: [.borderless], backing: .buffered, defer: true)100 window.isReleasedWhenClosed = false101 window.appearance = hosting.appearance102 window.contentView = hosting103 hosting.layoutSubtreeIfNeeded()104 return (window, hosting)105 }106107 private static func write(_ hosting: NSView, to file: URL) -> Int {108 guard let bitmap = hosting.bitmapImageRepForCachingDisplay(in: hosting.bounds) else { return 0 }109 hosting.cacheDisplay(in: hosting.bounds, to: bitmap)110 guard let png = bitmap.representation(using: .png, properties: [:]) else { return 0 }111 try? png.write(to: file)112 var seen = Set<UInt32>()113 let stepX = max(1, bitmap.pixelsWide / 48), stepY = max(1, bitmap.pixelsHigh / 48)114 for y in stride(from: 0, to: bitmap.pixelsHigh, by: stepY) {115 for x in stride(from: 0, to: bitmap.pixelsWide, by: stepX) {116 guard let colour = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) else { continue }117 let r = UInt32(colour.redComponent * 255), g = UInt32(colour.greenComponent * 255), b = UInt32(colour.blueComponent * 255)118 seen.insert(r << 16 | g << 8 | b)119 }120 }121 return seen.count122 }123}124#endif125