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

feat: add an on_key_press method to TextInput #2643

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions widget/src/text_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ pub struct TextInput<
on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
on_paste: Option<Box<dyn Fn(String) -> Message + 'a>>,
on_submit: Option<Message>,
on_key_press:
Option<Box<dyn Fn(keyboard::Key, keyboard::Modifiers) -> Message + 'a>>,
icon: Option<Icon<Renderer::Font>>,
class: Theme::Class<'a>,
}
Expand Down Expand Up @@ -148,6 +150,7 @@ where
on_input: None,
on_paste: None,
on_submit: None,
on_key_press: None,
icon: None,
class: Theme::default(),
}
Expand Down Expand Up @@ -223,6 +226,16 @@ where
self
}

/// Sets the message that should be produced when the [`TextInput`] is
/// focused and a key is pressed.
pub fn on_key_press(
mut self,
on_key_press: impl Fn(keyboard::Key, keyboard::Modifiers) -> Message + 'a,
) -> Self {
self.on_key_press = Some(Box::new(on_key_press));
self
}

/// Sets the [`Font`] of the [`TextInput`].
///
/// [`Font`]: text::Renderer::Font
Expand Down Expand Up @@ -817,6 +830,13 @@ where
let modifiers = state.keyboard_modifiers;
focus.updated_at = Instant::now();

if let Some(on_key_press) = &self.on_key_press {
let message =
(on_key_press)(key.clone(), modifiers.clone());

shell.publish(message);
}

match key.as_ref() {
keyboard::Key::Character("c")
if state.keyboard_modifiers.command()
Expand Down