Skip to content

Commit 23364bc

Browse files
authored
Merge pull request #1526 from mtkennerly/feature/find-focused
Add widget operation to find currently focused widget
2 parents cf410a5 + e56c454 commit 23364bc

3 files changed

Lines changed: 46 additions & 0 deletions

File tree

native/src/widget/operation/focusable.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,37 @@ pub fn focus_next<T>() -> impl Operation<T> {
167167

168168
count(|count| FocusNext { count, current: 0 })
169169
}
170+
171+
/// Produces an [`Operation`] that searches for the current focused widget
172+
/// and stores its ID. This ignores widgets that do not have an ID.
173+
pub fn find_focused() -> impl Operation<Id> {
174+
struct FindFocused {
175+
focused: Option<Id>,
176+
}
177+
178+
impl Operation<Id> for FindFocused {
179+
fn focusable(&mut self, state: &mut dyn Focusable, id: Option<&Id>) {
180+
if state.is_focused() && id.is_some() {
181+
self.focused = id.cloned();
182+
}
183+
}
184+
185+
fn container(
186+
&mut self,
187+
_id: Option<&Id>,
188+
operate_on_children: &mut dyn FnMut(&mut dyn Operation<Id>),
189+
) {
190+
operate_on_children(self)
191+
}
192+
193+
fn finish(&self) -> Outcome<Id> {
194+
if let Some(id) = &self.focused {
195+
Outcome::Some(id.clone())
196+
} else {
197+
Outcome::None
198+
}
199+
}
200+
}
201+
202+
FindFocused { focused: None }
203+
}

native/src/widget/scrollable.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,12 @@ impl Id {
334334
}
335335
}
336336

337+
impl From<Id> for widget::Id {
338+
fn from(id: Id) -> Self {
339+
id.0
340+
}
341+
}
342+
337343
/// Produces a [`Command`] that snaps the [`Scrollable`] with the given [`Id`]
338344
/// to the provided `percentage`.
339345
pub fn snap_to<Message: 'static>(id: Id, percentage: f32) -> Command<Message> {

native/src/widget/text_input.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,12 @@ impl Id {
333333
}
334334
}
335335

336+
impl From<Id> for widget::Id {
337+
fn from(id: Id) -> Self {
338+
id.0
339+
}
340+
}
341+
336342
/// Produces a [`Command`] that focuses the [`TextInput`] with the given [`Id`].
337343
pub fn focus<Message: 'static>(id: Id) -> Command<Message> {
338344
Command::widget(operation::focusable::focus(id.0))

0 commit comments

Comments
 (0)