Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Undeprecate preview traits? #353

Merged
merged 3 commits into from
Mar 31, 2025
Merged

Undeprecate preview traits? #353

merged 3 commits into from
Mar 31, 2025

Conversation

stephencelis
Copy link
Member

I believe I stumbled onto a fix for preview code bleeding between previews, so this works in a single file:

struct MyView: View {
  @Dependency(\.date.now) var now
  var body: some View {
    Text("\(now)")
  }
}

#Preview(
  "Controlled",
  traits: .dependency(\.date.now, Date(timeIntervalSince1970: 0)
) {
  MyView()
}

#Preview("Uncontrolled") {
  MyView()
}

The one caveat to this is that if you access a dependency directly in the #Preview block you must use @Previewable @Dependency, but that's the same for @Environment.

@stephencelis stephencelis requested a review from mbrandonw March 19, 2025 20:07
Comment on lines +26 to +33
private struct DependenciesPreviewModifier: PreviewModifier {
let updateValuesForPreview: @Sendable (inout DependencyValues) -> Void

func body(content: Content, context: ()) -> some View {
prepareDependencies(updateValuesForPreview)
return content
}
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Introducing a preview modifier allows us to delay when dependencies are prepared to the computation of the preview's body.

@stephencelis stephencelis merged commit 4e6b6a8 into main Mar 31, 2025
7 checks passed
@stephencelis stephencelis deleted the preview-trait-fixes branch March 31, 2025 23:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants