david-swift ee92f63f86
All checks were successful
Deploy Docs / publish (push) Successful in 50s
SwiftLint / SwiftLint (push) Successful in 4s
Add support for environment properties
2024-10-24 13:16:23 +02:00

63 lines
1.6 KiB
Swift

//
// View.swift
// Meta
//
// Created by david-swift on 09.06.24.
//
/// A structure conforming to `View` is referred to as a view.
/// It can be part of a body.
///
/// ```swift
/// struct Test: View {
///
/// var view: Body {
/// AnotherView()
/// }
///
/// }
/// ```
///
/// Use ``SimpleView`` instead if a view does not have to save state.
///
public protocol View: AnyView {
/// The view's content.
@ViewBuilder var view: Body { get }
}
/// Extend the view type with state.
extension View {
/// The view's content.
public var viewContent: Body {
[StateWrapper(content: { view }, state: getState(), environment: getEnvironmentVariables())]
}
/// Get the state from the properties.
/// - Returns: The state.
func getState() -> [String: StateProtocol] {
var state: [String: StateProtocol] = [:]
for property in Mirror(reflecting: self).children {
if let label = property.label, let value = property.value as? StateProtocol {
state[label] = value
}
}
return state
}
/// Get the environment properties.
/// - Returns: The environment properties.
func getEnvironmentVariables() -> [String: any EnvironmentProtocol] {
var environment: [String: any EnvironmentProtocol] = [:]
for property in Mirror(reflecting: self).children {
if let label = property.label, let value = property.value as? any EnvironmentProtocol {
environment[label] = value
}
}
return environment
}
}