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]
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
57pub 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}