Skip to main content

cranpose_ui/
unhandled_keys.rs

1use std::{cell::RefCell, rc::Rc};
2
3use cranpose_core::{DisposableEffect, remember};
4use cranpose_macros::composable;
5
6use crate::KeyEvent;
7
8type KeyHandler = Rc<RefCell<Rc<dyn Fn(&KeyEvent) -> bool>>>;
9
10thread_local! {
11    static HANDLERS: RefCell<Vec<(u64, KeyHandler)>> = const { RefCell::new(Vec::new()) };
12    static NEXT_ID: RefCell<u64> = const { RefCell::new(0) };
13}
14
15/// Hands `handler` every key event no control took: none was focused, a
16/// focused control let the key pass, and no text field is taking typing.
17///
18/// This is where an application puts the shortcuts that work anywhere in it,
19/// a media player's play and stop keys, for instance. The handler returns
20/// `true` for a key it used. While several are composed, the one composed
21/// last is asked first, and a key goes no further once one takes it.
22///
23/// ```ignore
24/// UnhandledKeyEvents(move |event| {
25///     if event.event_type != KeyEventType::KeyDown {
26///         return false;
27///     }
28///     match event.key_code {
29///         KeyCode::X => { play(); true }
30///         KeyCode::V => { stop(); true }
31///         _ => false,
32///     }
33/// });
34/// ```
35#[composable]
36pub fn UnhandledKeyEvents(handler: impl Fn(&KeyEvent) -> bool + 'static) {
37    let latest: KeyHandler = remember(|| {
38        let placeholder: Rc<dyn Fn(&KeyEvent) -> bool> = Rc::new(|_: &KeyEvent| false);
39        Rc::new(RefCell::new(placeholder))
40    })
41    .with(Rc::clone);
42    *latest.borrow_mut() = Rc::new(handler);
43    DisposableEffect((), move |scope| {
44        let id = NEXT_ID.with(|next| {
45            let mut next = next.borrow_mut();
46            *next += 1;
47            *next
48        });
49        HANDLERS.with(|handlers| handlers.borrow_mut().push((id, latest)));
50        scope.on_dispose(move || {
51            HANDLERS.with(|handlers| handlers.borrow_mut().retain(|(held, _)| *held != id));
52        })
53    });
54}
55
56/// Offers `event` to the [`UnhandledKeyEvents`] handlers, the one composed
57/// last first, and says whether one of them took it. The platform shells
58/// call this with each key the focused controls and text fields let pass.
59pub fn dispatch_unhandled_key_event(event: &KeyEvent) -> bool {
60    let handlers: Vec<KeyHandler> = HANDLERS.with(|handlers| {
61        handlers
62            .borrow()
63            .iter()
64            .rev()
65            .map(|(_, handler)| Rc::clone(handler))
66            .collect()
67    });
68    handlers.into_iter().any(|handler| {
69        let current = Rc::clone(&handler.borrow());
70        current(event)
71    })
72}