meta/Sources/View/AppearObserver.swift
david-swift 9f50e272f3
All checks were successful
Deploy Docs / publish (push) Successful in 55s
SwiftLint / SwiftLint (push) Successful in 3s
Add support for accessing the widget data when inspecting
2025-02-10 17:54:22 +01:00

72 lines
2.2 KiB
Swift

//
// AppearObserver.swift
// Meta
//
// Created by david-swift on 29.06.24.
//
/// Run a custom code accessing the view's storage when initializing the view.
struct AppearObserver: ConvenienceWidget {
/// The custom code to edit the widget.
var modify: (ViewStorage, WidgetData) -> Void
/// The wrapped view.
var content: AnyView
/// The view storage.
/// - Parameters:
/// - data: Modify views before being updated.
/// - type: The view render data type.
/// - Returns: The view storage.
func container<Data>(
data: WidgetData,
type: Data.Type
) -> ViewStorage where Data: ViewRenderData {
let storage = content.storage(data: data, type: type)
modify(storage, data)
return storage
}
/// Update the stored content.
/// - Parameters:
/// - storage: The storage to update.
/// - data: Modify views before being updated
/// - updateProperties: Whether to update the view's properties.
/// - type: The view render data type.
func update<Data>(
_ storage: ViewStorage,
data: WidgetData,
updateProperties: Bool,
type: Data.Type
) where Data: ViewRenderData {
content.updateStorage(storage, data: data, updateProperties: updateProperties, type: type)
}
}
/// Extend any view.
extension AnyView {
/// Run a function on the widget when it appears for the first time.
/// - Parameter closure: The function.
/// - Returns: A view.
public func inspectOnAppear(_ closure: @escaping (ViewStorage, WidgetData) -> Void) -> AnyView {
AppearObserver(modify: closure, content: self)
}
/// Run a function on the widget when it appears for the first time.
/// - Parameter closure: The function.
/// - Returns: A view.
public func inspectOnAppear(_ closure: @escaping (ViewStorage) -> Void) -> AnyView {
inspectOnAppear { storage, _ in closure(storage) }
}
/// Run a function when the view appears for the first time.
/// - Parameter closure: The function.
/// - Returns: A view.
public func onAppear(_ closure: @escaping () -> Void) -> AnyView {
inspectOnAppear { _ in closure() }
}
}