Repository Public License
1import AppKit2import SwiftUI34/// Draws a running app off-screen, so the builder (and tests) can look at what a blueprint produces.5@MainActor6public enum AppSnapshot {7 public static func png(runtime: AppRuntime, size: CGSize = CGSize(width: 900, height: 620), settle: Duration = .milliseconds(350)) async -> Data? {8 let view = AppView(runtime: runtime).frame(width: size.width, height: size.height).background(Color(nsColor: .windowBackgroundColor))9 let host = NSHostingView(rootView: view)10 host.frame = CGRect(origin: .zero, size: size)11 // The window is never ordered in: it only gives the view a backing store and an appearance.12 let window = NSWindow(contentRect: host.frame, styleMask: [.borderless], backing: .buffered, defer: false)13 window.isReleasedWhenClosed = false14 window.contentView = host15 host.layoutSubtreeIfNeeded()16 try? await Task.sleep(for: settle)17 host.layoutSubtreeIfNeeded()18 guard let rep = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { return nil }19 rep.size = size20 host.cacheDisplay(in: host.bounds, to: rep)21 window.contentView = nil22 return rep.representation(using: .png, properties: [:])23 }24}25