Skip to main content

strata_dom/hooks/
window.rs

1//! Window, cursor, keyboard shortcut, and clipboard control hooks.
2
3use crate::reactive::Signal;
4use std::cell::RefCell;
5use std::rc::Rc;
6
7/// Standard pointer cursor icons.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum CursorIcon {
10    #[default]
11    Default,
12    Pointer,
13    Text,
14    Move,
15    NotAllowed,
16    Grab,
17    Grabbing,
18    Crosshair,
19    ColResize,
20    RowResize,
21}
22
23type ShortcutEntry = (KeyChord, Rc<dyn Fn()>);
24type CursorEntry = (CursorIcon, Signal<bool>);
25
26thread_local! {
27    static MANUAL_CURSOR: RefCell<Signal<Option<CursorIcon>>> = RefCell::new(Signal::new(None));
28    static CURSOR_REQUESTS: RefCell<Vec<(u32, CursorEntry)>> = const { RefCell::new(Vec::new()) };
29    static REGISTERED_SHORTCUTS: RefCell<Vec<(u32, ShortcutEntry)>> = RefCell::new(Vec::new());
30    static NEXT_SHORTCUT_ID: RefCell<u32> = const { RefCell::new(1) };
31    static CLIPBOARD_CONTENT: RefCell<Signal<String>> = RefCell::new(Signal::new(String::new()));
32}
33
34/// Returns the currently active pointer cursor icon, taking into account manual overrides and reactive hooks.
35pub fn current_cursor() -> CursorIcon {
36    if let Some(manual) = MANUAL_CURSOR.with(|c| c.borrow().get()) {
37        return manual;
38    }
39
40    CURSOR_REQUESTS.with(|reqs| {
41        for (_, (icon, active)) in reqs.borrow().iter().rev() {
42            if active.get() {
43                return *icon;
44            }
45        }
46        CursorIcon::Default
47    })
48}
49
50/// Sets the current pointer cursor icon directly as an explicit override.
51pub fn set_current_cursor(icon: CursorIcon) {
52    MANUAL_CURSOR.with(|c| c.borrow().set(Some(icon)));
53}
54
55/// Clears any manual pointer cursor override, returning control to reactive hooks.
56pub fn clear_cursor_override() {
57    MANUAL_CURSOR.with(|c| c.borrow().set(None));
58}
59
60/// Reactive hook that activates the specified pointer cursor whenever `active` signal evaluates to true.
61///
62/// Inside a `#[component]` render body, the cursor request is persisted in a component hook slot,
63/// updated in place on re-renders (preventing duplicate `CURSOR_REQUESTS` entries), and automatically
64/// removed when the component unmounts. Outside a component scope or inside an effect, registers an
65/// unscoped reactive cursor entry.
66pub fn use_cursor(icon: CursorIcon, active: Signal<bool>) {
67    let entry: CursorEntry = (icon, active);
68    if crate::reactive::in_component_hook_context() {
69        let _ = upsert_component_entry(&CURSOR_REQUESTS, entry);
70    } else {
71        let id = alloc_registry_id();
72        CURSOR_REQUESTS.with(|reqs| {
73            reqs.borrow_mut().push((id, entry));
74        });
75    }
76}
77
78/// Representation of a parsed keyboard key chord.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct KeyChord {
81    pub key: String,
82    pub ctrl: bool,
83    pub shift: bool,
84    pub alt: bool,
85    pub meta: bool,
86}
87
88impl KeyChord {
89    fn normalize_key_token(raw: &str) -> String {
90        if raw == " " {
91            return "space".to_string();
92        }
93        match raw.trim().to_ascii_lowercase().as_str() {
94            "" | "space" | "spacebar" if raw == " " || raw.eq_ignore_ascii_case("space") || raw.eq_ignore_ascii_case("spacebar") => {
95                "space".to_string()
96            }
97            "esc" | "escape" => "escape".to_string(),
98            "return" | "enter" => "enter".to_string(),
99            other => other.to_string(),
100        }
101    }
102
103    /// Parses a string like "Ctrl+Shift+P", "Cmd+K", or "Escape".
104    pub fn parse(s: &str) -> Self {
105        let mut ctrl = false;
106        let mut shift = false;
107        let mut alt = false;
108        let mut meta = false;
109        let mut key = String::new();
110
111        for part in s.split('+') {
112            if part == " " {
113                key = "space".to_string();
114                continue;
115            }
116            let p = part.trim();
117            match p.to_ascii_lowercase().as_str() {
118                "ctrl" | "control" => ctrl = true,
119                "shift" => shift = true,
120                "alt" | "option" => alt = true,
121                "cmd" | "command" | "meta" | "super" => meta = true,
122                other => key = Self::normalize_key_token(other),
123            }
124        }
125
126        Self {
127            key,
128            ctrl,
129            shift,
130            alt,
131            meta,
132        }
133    }
134
135    /// Evaluates if an incoming keystroke matches this key chord.
136    pub fn matches(&self, key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
137        let incoming = Self::normalize_key_token(key);
138        self.key.eq_ignore_ascii_case(&incoming)
139            && self.ctrl == ctrl
140            && self.shift == shift
141            && self.alt == alt
142            && self.meta == meta
143    }
144}
145
146struct ScopedEntryGuard<T: 'static> {
147    id: u32,
148    registry: &'static std::thread::LocalKey<RefCell<Vec<(u32, T)>>>,
149}
150
151impl<T: 'static> Drop for ScopedEntryGuard<T> {
152    fn drop(&mut self) {
153        let _ = self.registry.try_with(|s| {
154            if let Ok(mut list) = s.try_borrow_mut() {
155                list.retain(|(id, _)| *id != self.id);
156            }
157        });
158    }
159}
160
161struct ComponentEntrySlot<T: 'static> {
162    id: u32,
163    guard: Rc<ScopedEntryGuard<T>>,
164}
165
166impl<T: 'static> Clone for ComponentEntrySlot<T> {
167    fn clone(&self) -> Self {
168        Self {
169            id: self.id,
170            guard: Rc::clone(&self.guard),
171        }
172    }
173}
174
175fn alloc_registry_id() -> u32 {
176    NEXT_SHORTCUT_ID.with(|n| {
177        let mut val = n.borrow_mut();
178        let cur = *val;
179        *val += 1;
180        cur
181    })
182}
183
184fn push_unscoped_entry<T: 'static>(
185    registry: &'static std::thread::LocalKey<RefCell<Vec<(u32, T)>>>,
186    value: T,
187) -> (u32, ScopedEntryGuard<T>) {
188    let id = alloc_registry_id();
189    registry.with(|s| {
190        s.borrow_mut().push((id, value));
191    });
192    (id, ScopedEntryGuard { id, registry })
193}
194
195fn upsert_component_entry<T: 'static>(
196    registry: &'static std::thread::LocalKey<RefCell<Vec<(u32, T)>>>,
197    value: T,
198) -> Rc<ScopedEntryGuard<T>> {
199    let mut init_val = Some(value);
200    let slot = crate::reactive::use_hook_slot_cloned(|| {
201        let initial = init_val.take().unwrap();
202        let (id, guard) = push_unscoped_entry(registry, initial);
203        ComponentEntrySlot {
204            id,
205            guard: Rc::new(guard),
206        }
207    })
208    .expect("component hook context active");
209
210    if let Some(latest) = init_val.take() {
211        registry.with(|s| {
212            let mut list = s.borrow_mut();
213            if let Some(entry) = list.iter_mut().find(|(id, _)| *id == slot.id) {
214                entry.1 = latest;
215            } else {
216                list.push((slot.id, latest));
217            }
218        });
219    }
220
221    Rc::clone(&slot.guard)
222}
223
224/// Handle returned by [`use_keyboard_shortcut`].
225///
226/// Outside a `#[component]` scope, dropping the handle unregisters the shortcut immediately.
227/// Inside a `#[component]` body, lifetime is bound to the component hook slot so dropping the
228/// handle at the end of `render` keeps the shortcut active until component unmount.
229pub struct ShortcutHandle {
230    _guard: Rc<ScopedEntryGuard<ShortcutEntry>>,
231}
232
233/// Registers a global keyboard shortcut with an invoked callback.
234///
235/// Inside a `#[component]` render body, the shortcut is persisted in the component's hook slot,
236/// updated in place on re-renders (preventing duplicate registrations), and unregistered
237/// automatically when the component unmounts. Outside a component scope or inside an effect,
238/// returns an RAII [`ShortcutHandle`] whose `Drop` unregisters immediately.
239pub fn use_keyboard_shortcut<F: Fn() + 'static>(shortcut: &str, handler: F) -> ShortcutHandle {
240    let entry: ShortcutEntry = (KeyChord::parse(shortcut), Rc::new(handler));
241    let guard = if crate::reactive::in_component_hook_context() {
242        upsert_component_entry(&REGISTERED_SHORTCUTS, entry)
243    } else {
244        Rc::new(push_unscoped_entry(&REGISTERED_SHORTCUTS, entry).1)
245    };
246    ShortcutHandle { _guard: guard }
247}
248
249/// Component-ergonomic alias for [`use_keyboard_shortcut`] discarding the [`ShortcutHandle`].
250///
251/// Registers the shortcut on mount, refreshes the closure in place on re-render, and cleans up
252/// on component unmount.
253pub fn use_shortcut<F: Fn() + 'static>(shortcut: &str, handler: F) {
254    let _ = use_keyboard_shortcut(shortcut, handler);
255}
256
257/// Dispatches a keydown event through registered shortcuts.
258/// Returns true if any registered shortcut consumed the key event.
259pub fn dispatch_global_keydown(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
260    let mut handled = false;
261    REGISTERED_SHORTCUTS.with(|s| {
262        let list = s.borrow().clone();
263        for (_, (chord, callback)) in list {
264            if chord.matches(key, ctrl, shift, alt, meta) {
265                callback();
266                handled = true;
267                break;
268            }
269        }
270    });
271    handled
272}
273
274/// Handle returned by `use_clipboard()` providing reactive clipboard operations.
275#[derive(Clone)]
276pub struct ClipboardHandle {
277    pub text: Signal<String>,
278    pub copy: Rc<dyn Fn(&str)>,
279    pub read_text: Rc<dyn Fn() -> String>,
280}
281
282/// Headless hook providing reactive clipboard reading and writing.
283pub fn use_clipboard() -> ClipboardHandle {
284    let text_sig = CLIPBOARD_CONTENT.with(|c| c.borrow().clone());
285
286    let copy = {
287        let sig = text_sig.clone();
288        Rc::new(move |val: &str| {
289            sig.set(val.to_string());
290        })
291    };
292
293    let read_text = {
294        let sig = text_sig.clone();
295        Rc::new(move || sig.get())
296    };
297
298    ClipboardHandle {
299        text: text_sig,
300        copy,
301        read_text,
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use crate::reactive::{
309        reset_component_hooks, with_root_component_scope, ComponentScopeGuard,
310    };
311
312    #[test]
313    fn test_component_use_cursor_does_not_leak_cursor_requests_across_rerenders_or_unmount() {
314        reset_component_hooks();
315        CURSOR_REQUESTS.with(|reqs| reqs.borrow_mut().clear());
316        clear_cursor_override();
317
318        let sig = Signal::new(true);
319        let render = |icon: CursorIcon| {
320            let sig_c = sig.clone();
321            with_root_component_scope(|| {
322                let _comp = ComponentScopeGuard::enter("CursorOwner");
323                use_cursor(icon, sig_c);
324            });
325        };
326
327        for _ in 0..25 {
328            render(CursorIcon::Grab);
329        }
330        assert_eq!(CURSOR_REQUESTS.with(|r| r.borrow().len()), 1);
331        assert_eq!(current_cursor(), CursorIcon::Grab);
332
333        // Updating icon updates the single slot in place without pushing a second entry
334        render(CursorIcon::ColResize);
335        assert_eq!(CURSOR_REQUESTS.with(|r| r.borrow().len()), 1);
336        assert_eq!(current_cursor(), CursorIcon::ColResize);
337
338        // Unmounting clears the entry completely
339        reset_component_hooks();
340        assert_eq!(CURSOR_REQUESTS.with(|r| r.borrow().len()), 0);
341        assert_eq!(current_cursor(), CursorIcon::Default);
342    }
343}
344