diff --git a/Documentation/Reference/extensions/View.md b/Documentation/Reference/extensions/View.md index 02a166f..c509e5b 100644 --- a/Documentation/Reference/extensions/View.md +++ b/Documentation/Reference/extensions/View.md @@ -159,6 +159,12 @@ Set the view's visibility. - Parameter visible: Whether the view is visible. - Returns: A view. +### `focused(_:)` + +Bind to the view's focus. +- Parameter focus: Whether the view is focused. +- Returns: A view. + ### `stopModifiers()` Remove all of the content modifiers for the wrapped views. diff --git a/Sources/Adwaita/View/Modifiers/InspectorWrapper.swift b/Sources/Adwaita/View/Modifiers/InspectorWrapper.swift index 41a15d8..438c993 100644 --- a/Sources/Adwaita/View/Modifiers/InspectorWrapper.swift +++ b/Sources/Adwaita/View/Modifiers/InspectorWrapper.swift @@ -138,4 +138,21 @@ extension View { inspect { gtk_widget_set_visible($0.pointer?.cast(), visible.cBool) } } + /// Bind to the view's focus. + /// - Parameter focus: Whether the view is focused. + /// - Returns: A view. + public func focused(_ focused: Binding) -> View { + inspect { storage in + storage.notify(name: "has-focus", id: "focused") { + let newValue = gtk_widget_has_focus(storage.pointer?.cast()) != 0 + if focused.wrappedValue != newValue { + focused.wrappedValue = newValue + } + } + if focused.wrappedValue != (gtk_widget_has_focus(storage.pointer?.cast()) != 0) { + gtk_widget_grab_focus(storage.pointer?.cast()) + } + } + } + } diff --git a/user-manual/Information/Widgets.md b/user-manual/Information/Widgets.md index 0b59622..d2b66fb 100644 --- a/user-manual/Information/Widgets.md +++ b/user-manual/Information/Widgets.md @@ -47,6 +47,7 @@ There are many more widgets available using auto-generation. Learn [how to use t | `overlay(_:)` | Overlay a view with another view. | | `insensitive(_:)` | Make a view unable to detect actions. This is especially useful for overlays. | | `onClick(handler:)` | Run a function when the user clicks on the widget. | +| `focused(_:)` | Set and observe whether a view is focused. | | `verticalCenter()` | Wrap a view in a `VStack` and center vertically. | | `horizontalCenter()` | Wrap a view in an `HStack` and center horizontally. |