Skip to main content

blit_widget/interact/
keyboard.rs

1use blit::{Context, InteractCx, KeyboardEvent};
2
3/// maps a keyboard event to an action, or lets it bubble
4pub trait Handler: FnOnce(KeyboardEvent<'_>) -> Option<Self::Action> + Copy + 'static {
5    type Action: Copy + 'static;
6}
7
8impl<A: Copy + 'static, F> Handler for F
9where
10    F: FnOnce(KeyboardEvent<'_>) -> Option<A> + Copy + 'static,
11{
12    type Action = A;
13}
14
15blit::builder! {
16    /// handles unclaimed keyboard and text input
17    #[derive(Clone, Copy)]
18    pub struct Interact<F> {
19        new(handler: F),
20        /// only handles events while this widget itself is focused
21        require_focus: bool = false,
22    }
23}
24
25impl<C: Context, F: Handler> blit::Interact<C> for Interact<F> {
26    type State = ();
27    type Response = Option<F::Action>;
28
29    fn update(&self, _: &mut (), cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response {
30        if self.require_focus && !cx.focused() {
31            return None;
32        }
33        let action = (self.handler)(cx.keyboard()?)?;
34        cx.claim_keyboard();
35        Some(action)
36    }
37}