From 9cba92f57f5686f5295cb3430a3787aa3694a1fc Mon Sep 17 00:00:00 2001 From: Andrew Baldwin Date: Mon, 17 Feb 2025 11:15:36 -0800 Subject: Add `is_focused` function that produces an `Operation` to get the focused state of a `focusable` by ID. Add `is_focused` function that produces a `Task` to get the focused state of a `text_input` by ID. --- core/src/widget/operation/focusable.rs | 45 ++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'core/src') diff --git a/core/src/widget/operation/focusable.rs b/core/src/widget/operation/focusable.rs index 1ee41244..49c574c4 100644 --- a/core/src/widget/operation/focusable.rs +++ b/core/src/widget/operation/focusable.rs @@ -257,3 +257,48 @@ pub fn find_focused() -> impl Operation { FindFocused { focused: None } } + +/// Produces an [`Operation`] that searches for the focusable widget +/// and stores whether it is focused or not. This ignores widgets that +/// do not have an ID. +pub fn is_focused(target: Id) -> impl Operation { + struct IsFocused { + target: Id, + is_focused: Option, + } + + impl Operation for IsFocused { + fn focusable( + &mut self, + id: Option<&Id>, + _bounds: Rectangle, + state: &mut dyn Focusable, + ) { + if id.is_some_and(|id| *id == self.target) { + self.is_focused = Some(state.is_focused()); + } + } + + fn container( + &mut self, + _id: Option<&Id>, + _bounds: Rectangle, + operate_on_children: &mut dyn FnMut(&mut dyn Operation), + ) { + operate_on_children(self); + } + + fn finish(&self) -> Outcome { + if let Some(is_focused) = &self.is_focused { + Outcome::Some(*is_focused) + } else { + Outcome::None + } + } + } + + IsFocused { + target, + is_focused: None, + } +} -- cgit