StanfordSpezi / Spezi

Open-source framework for rapid development of modern, interoperable digital health applications.
https://swiftpackageindex.com/StanfordSpezi/Spezi/documentation
MIT License
130 stars 10 forks source link

Inject Spezi Components as ViewModifier into the SwiftUI view hierarchy #87

Closed Supereg closed 8 months ago

Supereg commented 8 months ago

Use Case

There is a general need for Spezi Components to either inject information or retrieve information from the SwiftUI view hierarchy. We already have the ObservableObjectProvider to inject Observable Objects into the view hierarchy. However, components might want to do more. There is a use case for SpeziAccount, where Account Services might want to inject view components globally (e.g., an alert box to reauthenticate on security related operations) or SpeziFirebase that requires access to the AuthorizationController that is part of the SwiftUI Environment.

Problem

Doing any of this, except for injecting ObservableObjects, is not supported by Spezi and requires custom modifiers or, generally, requires a manual approach.

Solution

A viable solution is to make all Component s conform to the SwiftUI ViewModifier protocol and injecting the into the global View hierarchy within the global spezi(_:) modifier.

This has several benefits:

Alternatives considered

Alternatives, where a Component provides a set of ViewModifiers (e.g. via a property wrapper similar to @Provide) were discussed. But generally those approaches reduce the flexibility or don't result in the same benefits as listed above. You wouldn't be able to use SwiftUI modifiers within your Component and it would increase the steps necessary to inject a view modifier into the view hierarchy.

Additional context

CC: @PSchmiedmayer

Code of Conduct

PSchmiedmayer commented 8 months ago

Thank you @Supereg; I approve the ViewModifier approach as discussed in the meeting 🚀

Supereg commented 8 months ago

There is some content only suggesting that you want to avoid using classes for Views and ViewModifier (e.g. https://stackoverflow.com/questions/60321144/can-a-class-be-a-view-in-swiftui). We might need to investigate the true impact here, especially with ViewModifier.