From c29c6e22cbd094a6619a4a746d02e6e729abd6aa Mon Sep 17 00:00:00 2001 From: david-swift Date: Tue, 30 Dec 2025 15:14:40 +0100 Subject: [PATCH] Add id modifier #74 --- Sources/Adwaita/AnyView+.swift | 7 +++++++ Sources/Adwaita/View/ViewStack.swift | 20 +++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Sources/Adwaita/AnyView+.swift b/Sources/Adwaita/AnyView+.swift index 902dff5..63b8376 100644 --- a/Sources/Adwaita/AnyView+.swift +++ b/Sources/Adwaita/AnyView+.swift @@ -390,4 +390,11 @@ extension AnyView { BreakpointBin(condition: .naturalHeight(padding: padding), matches: matches) { self } } + /// Build the UI from scratch once the identifier changes. + /// - Parameter id: The identifier. + public func id(_ id: CustomStringConvertible) -> AnyView { + ViewStack(id: id) { _ in self } + .limitChildren() + } + } diff --git a/Sources/Adwaita/View/ViewStack.swift b/Sources/Adwaita/View/ViewStack.swift index fc79ccc..bca4739 100644 --- a/Sources/Adwaita/View/ViewStack.swift +++ b/Sources/Adwaita/View/ViewStack.swift @@ -16,6 +16,8 @@ public struct ViewStack: AdwaitaWidget { var id: CustomStringConvertible /// Whether the view stack allocates the same height and width for all children. var homogeneous: Bool? + /// Whether to limit the stack to one child (always redraw the UI when the id changes). + var limitChildren: Bool? /// Initialize the stack. /// - Parameters: @@ -87,14 +89,30 @@ public struct ViewStack: AdwaitaWidget { gtk_stack_set_vhomogeneous(storage.opaquePointer, homogeneous.cBool) gtk_stack_set_hhomogeneous(storage.opaquePointer, homogeneous.cBool) } + if let limitChildren, limitChildren { + for element in storage.content where element.key != id.description { + guard let first = element.value.first else { + continue + } + gtk_stack_remove(storage.opaquePointer, first.opaquePointer?.cast()) + storage.content.removeValue(forKey: element.key) + } + } storage.previousState = self } /// Whether the view stack allocates the same height and width for all children. /// - Parameter homogeneous: Whether this is enabled. /// - Returns: The stack. - public func homogeneous(_ homogeneous: Bool? = nil) -> Self { + public func homogeneous(_ homogeneous: Bool? = true) -> Self { modify { $0.homogeneous = homogeneous } } + /// Whether to limit the stack to one child (always redraw the UI when the id changes). + /// - Parameter limit: Whether to limit the stack to one child. + /// - Returns: The stack. + public func limitChildren(_ limitChildren: Bool? = true) -> Self { + modify { $0.limitChildren = limitChildren } + } + }