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]
36#[allow(non_snake_case)]
37pub fn UnhandledKeyEvents(handler: impl Fn(&KeyEvent) -> bool + 'static) {
38    let latest: KeyHandler = remember(|| {
39        let placeholder: Rc<dyn Fn(&KeyEvent) -> bool> = Rc::new(|_: &KeyEvent| false);
40        Rc::new(RefCell::new(placeholder))
41    })
42    .with(Rc::clone);
43    *latest.borrow_mut() = Rc::new(handler);
44    DisposableEffect((), move |scope| {
45        let id = NEXT_ID.with(|next| {
46            let mut next = next.borrow_mut();
47            *next += 1;
48            *next
49        });
50        HANDLERS.with(|handlers| handlers.borrow_mut().push((id, latest)));
51        scope.on_dispose(move || {
52            HANDLERS.with(|handlers| handlers.borrow_mut().retain(|(held, _)| *held != id));
53        })
54    });
55}
56
57/// Offers `event` to the [`UnhandledKeyEvents`] handlers, the one composed
58/// last first, and says whether one of them took it. The platform shells
59/// call this with each key the focused controls and text fields let pass.
60pub fn dispatch_unhandled_key_event(event: &KeyEvent) -> bool {
61    let handlers: Vec<KeyHandler> = HANDLERS.with(|handlers| {
62        handlers
63            .borrow()
64            .iter()
65            .rev()
66            .map(|(_, handler)| Rc::clone(handler))
67            .collect()
68    });
69    handlers.into_iter().any(|handler| {
70        let current = Rc::clone(&handler.borrow());
71        current(event)
72    })
73}