I've been looking for a way to get snapshots of SwiftUI previews without changing the source code.
My use case is that I'm trying to augment the capabilities of coding assistants by letting them "see" what they did (using unit test is generally a great feedback loop for those AI assistants). But this is a broader use case as SwiftUI Previews are often used for testing and any decent testing is available from the CLI and can be integrated in different systems.
In an ideal world a developper would be able to run something like this and get snapshots:
swift snapshot-previews --filter SignupPreview --output ./snapshots
just like I'm able to run
swift test --filter SignupTests --xunit-output ./test-output
I know this is not possible, and that any library out there for snapshotting SwiftUI Previews requires some direct integration and modification to the source code. I also know that while core to our development workflows, SwiftUI and its previews are not open source and developed privately by Apple.
So... what would folks recommend as the best solution to make this happen? I've been hesitating between three different directions:
- copy the source code to a tmp directory, do the required rewritting there without changing the original source code, and leverage an existing 3rd party solution to do the snapshotting. Doesn't feel great but is likely to work while being brittle.
- find out if it is possible to do some injection. Into what? The preview needs a running process, but a swift build/test doesn't create one afaik. Maybe it's the opposite where the code to be snapshotted is injected into a host snapshotter process. Not sure it can work but maybe good.
- give up, it's a lost battle! The easiest option.
It seems that Apple does some code rewritting to support Previews, at least the hot reloading and private imports. Other than that I'm really out of my confort zone and I know little about those systems.