cranpose_ui/
unhandled_keys.rs1use 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#[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
56pub 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}