Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add widget operation to find currently focused widget #1526

Merged
merged 2 commits into from
Nov 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions native/src/widget/operation/focusable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,37 @@ pub fn focus_next<T>() -> impl Operation<T> {

count(|count| FocusNext { count, current: 0 })
}

/// Produces an [`Operation`] that searches for the current focused widget
/// and stores its ID. This ignores widgets that do not have an ID.
pub fn find_focused() -> impl Operation<Id> {
struct FindFocused {
focused: Option<Id>,
}

impl Operation<Id> for FindFocused {
fn focusable(&mut self, state: &mut dyn Focusable, id: Option<&Id>) {
if state.is_focused() && id.is_some() {
self.focused = id.cloned();
}
}

fn container(
&mut self,
_id: Option<&Id>,
operate_on_children: &mut dyn FnMut(&mut dyn Operation<Id>),
) {
operate_on_children(self)
}

fn finish(&self) -> Outcome<Id> {
if let Some(id) = &self.focused {
Outcome::Some(id.clone())
} else {
Outcome::None
}
}
}

FindFocused { focused: None }
}
6 changes: 6 additions & 0 deletions native/src/widget/scrollable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,12 @@ impl Id {
}
}

impl From<Id> for widget::Id {
fn from(id: Id) -> Self {
id.0
}
}

/// Produces a [`Command`] that snaps the [`Scrollable`] with the given [`Id`]
/// to the provided `percentage`.
pub fn snap_to<Message: 'static>(id: Id, percentage: f32) -> Command<Message> {
Expand Down
6 changes: 6 additions & 0 deletions native/src/widget/text_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,12 @@ impl Id {
}
}

impl From<Id> for widget::Id {
fn from(id: Id) -> Self {
id.0
}
}

/// Produces a [`Command`] that focuses the [`TextInput`] with the given [`Id`].
pub fn focus<Message: 'static>(id: Id) -> Command<Message> {
Command::widget(operation::focusable::focus(id.0))
Expand Down