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 = (u32, KeyChord, Rc<dyn Fn()>);
24
25thread_local! {
26    static MANUAL_CURSOR: RefCell<Signal<Option<CursorIcon>>> = RefCell::new(Signal::new(None));
27    static CURSOR_REQUESTS: RefCell<Vec<(CursorIcon, Signal<bool>)>> = const { RefCell::new(Vec::new()) };
28    static REGISTERED_SHORTCUTS: RefCell<Vec<ShortcutEntry>> = RefCell::new(Vec::new());
29    static NEXT_SHORTCUT_ID: RefCell<u32> = const { RefCell::new(1) };
30    static CLIPBOARD_CONTENT: RefCell<Signal<String>> = RefCell::new(Signal::new(String::new()));
31}
32
33/// Returns the currently active pointer cursor icon, taking into account manual overrides and reactive hooks.
34pub fn current_cursor() -> CursorIcon {
35    if let Some(manual) = MANUAL_CURSOR.with(|c| c.borrow().get()) {
36        return manual;
37    }
38
39    CURSOR_REQUESTS.with(|reqs| {
40        for (icon, active) in reqs.borrow().iter().rev() {
41            if active.get() {
42                return *icon;
43            }
44        }
45        CursorIcon::Default
46    })
47}
48
49/// Sets the current pointer cursor icon directly as an explicit override.
50pub fn set_current_cursor(icon: CursorIcon) {
51    MANUAL_CURSOR.with(|c| c.borrow().set(Some(icon)));
52}
53
54/// Clears any manual pointer cursor override, returning control to reactive hooks.
55pub fn clear_cursor_override() {
56    MANUAL_CURSOR.with(|c| c.borrow().set(None));
57}
58
59/// Reactive hook that activates the specified pointer cursor whenever `active` signal evaluates to true.
60pub fn use_cursor(icon: CursorIcon, active: Signal<bool>) {
61    CURSOR_REQUESTS.with(|reqs| {
62        reqs.borrow_mut().push((icon, active));
63    });
64}
65
66/// Representation of a parsed keyboard key chord.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct KeyChord {
69    pub key: String,
70    pub ctrl: bool,
71    pub shift: bool,
72    pub alt: bool,
73    pub meta: bool,
74}
75
76impl KeyChord {
77    /// Parses a string like "Ctrl+Shift+P", "Cmd+K", or "Escape".
78    pub fn parse(s: &str) -> Self {
79        let mut ctrl = false;
80        let mut shift = false;
81        let mut alt = false;
82        let mut meta = false;
83        let mut key = String::new();
84
85        for part in s.split('+') {
86            let p = part.trim();
87            match p.to_ascii_lowercase().as_str() {
88                "ctrl" | "control" => ctrl = true,
89                "shift" => shift = true,
90                "alt" | "option" => alt = true,
91                "cmd" | "command" | "meta" | "super" => meta = true,
92                other => key = other.to_ascii_lowercase(),
93            }
94        }
95
96        Self {
97            key,
98            ctrl,
99            shift,
100            alt,
101            meta,
102        }
103    }
104
105    /// Evaluates if an incoming keystroke matches this key chord.
106    pub fn matches(&self, key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
107        self.key.eq_ignore_ascii_case(key)
108            && self.ctrl == ctrl
109            && self.shift == shift
110            && self.alt == alt
111            && self.meta == meta
112    }
113}
114
115/// Handle returned by `use_keyboard_shortcut` that unregisters the shortcut on drop.
116pub struct ShortcutHandle {
117    id: u32,
118}
119
120impl Drop for ShortcutHandle {
121    fn drop(&mut self) {
122        REGISTERED_SHORTCUTS.with(|s| {
123            s.borrow_mut().retain(|(id, _, _)| *id != self.id);
124        });
125    }
126}
127
128/// Registers a global keyboard shortcut with an invoked callback.
129pub fn use_keyboard_shortcut<F: Fn() + 'static>(shortcut: &str, handler: F) -> ShortcutHandle {
130    let chord = KeyChord::parse(shortcut);
131    let id = NEXT_SHORTCUT_ID.with(|n| {
132        let mut val = n.borrow_mut();
133        let cur = *val;
134        *val += 1;
135        cur
136    });
137
138    let callback = Rc::new(handler);
139    REGISTERED_SHORTCUTS.with(|s| {
140        s.borrow_mut().push((id, chord, callback));
141    });
142
143    ShortcutHandle { id }
144}
145
146/// Dispatches a keydown event through registered shortcuts.
147/// Returns true if any registered shortcut consumed the key event.
148pub fn dispatch_global_keydown(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
149    let mut handled = false;
150    REGISTERED_SHORTCUTS.with(|s| {
151        let list = s.borrow().clone();
152        for (_, chord, callback) in list {
153            if chord.matches(key, ctrl, shift, alt, meta) {
154                callback();
155                handled = true;
156                break;
157            }
158        }
159    });
160    handled
161}
162
163/// Handle returned by `use_clipboard()` providing reactive clipboard operations.
164#[derive(Clone)]
165pub struct ClipboardHandle {
166    pub text: Signal<String>,
167    pub copy: Rc<dyn Fn(&str)>,
168    pub read_text: Rc<dyn Fn() -> String>,
169}
170
171/// Headless hook providing reactive clipboard reading and writing.
172pub fn use_clipboard() -> ClipboardHandle {
173    let text_sig = CLIPBOARD_CONTENT.with(|c| c.borrow().clone());
174
175    let copy = {
176        let sig = text_sig.clone();
177        Rc::new(move |val: &str| {
178            sig.set(val.to_string());
179        })
180    };
181
182    let read_text = {
183        let sig = text_sig.clone();
184        Rc::new(move || sig.get())
185    };
186
187    ClipboardHandle {
188        text: text_sig,
189        copy,
190        read_text,
191    }
192}