feat: add keyboard_nav module with unfocus support
This commit is contained in:
parent
352bf8e401
commit
f441a364a6
3 changed files with 68 additions and 26 deletions
58
src/keyboard_nav.rs
Normal file
58
src/keyboard_nav.rs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
use iced::{event, keyboard, mouse, subscription, Command, Event, Subscription};
|
||||
use iced_native::widget::{operation, Id, Operation};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Message {
|
||||
FocusNext,
|
||||
FocusPrevious,
|
||||
Unfocus,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn subscription() -> Subscription<Message> {
|
||||
subscription::events_with(|event, status| match (event, status) {
|
||||
(
|
||||
Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key_code: keyboard::KeyCode::Tab,
|
||||
modifiers,
|
||||
..
|
||||
}),
|
||||
event::Status::Ignored,
|
||||
) => Some(if modifiers.shift() {
|
||||
Message::FocusPrevious
|
||||
} else {
|
||||
Message::FocusNext
|
||||
}),
|
||||
(Event::Mouse(mouse::Event::ButtonReleased { .. }), _) => Some(Message::Unfocus),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Unfocuses any actively-focused widget.
|
||||
#[must_use]
|
||||
pub fn unfocus<Message: 'static>() -> Command<Message> {
|
||||
Command::<Message>::widget(unfocus_operation())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn unfocus_operation<T>() -> impl Operation<T> {
|
||||
struct Unfocus {}
|
||||
|
||||
impl<T> Operation<T> for Unfocus {
|
||||
fn focusable(&mut self, state: &mut dyn operation::Focusable, _id: Option<&Id>) {
|
||||
if state.is_focused() {
|
||||
state.unfocus();
|
||||
}
|
||||
}
|
||||
|
||||
fn container(
|
||||
&mut self,
|
||||
_id: Option<&Id>,
|
||||
operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
|
||||
) {
|
||||
operate_on_children(self);
|
||||
}
|
||||
}
|
||||
|
||||
Unfocus {}
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ pub use iced_winit;
|
|||
#[cfg(feature = "applet")]
|
||||
pub mod applet;
|
||||
pub mod font;
|
||||
pub mod keyboard_nav;
|
||||
pub mod theme;
|
||||
pub mod widget;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue