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    fn normalize_key_token(raw: &str) -> String {
78        if raw == " " {
79            return "space".to_string();
80        }
81        match raw.trim().to_ascii_lowercase().as_str() {
82            "" | "space" | "spacebar" if raw == " " || raw.eq_ignore_ascii_case("space") || raw.eq_ignore_ascii_case("spacebar") => {
83                "space".to_string()
84            }
85            "esc" | "escape" => "escape".to_string(),
86            "return" | "enter" => "enter".to_string(),
87            other => other.to_string(),
88        }
89    }
90
91    /// Parses a string like "Ctrl+Shift+P", "Cmd+K", or "Escape".
92    pub fn parse(s: &str) -> Self {
93        let mut ctrl = false;
94        let mut shift = false;
95        let mut alt = false;
96        let mut meta = false;
97        let mut key = String::new();
98
99        for part in s.split('+') {
100            if part == " " {
101                key = "space".to_string();
102                continue;
103            }
104            let p = part.trim();
105            match p.to_ascii_lowercase().as_str() {
106                "ctrl" | "control" => ctrl = true,
107                "shift" => shift = true,
108                "alt" | "option" => alt = true,
109                "cmd" | "command" | "meta" | "super" => meta = true,
110                other => key = Self::normalize_key_token(other),
111            }
112        }
113
114        Self {
115            key,
116            ctrl,
117            shift,
118            alt,
119            meta,
120        }
121    }
122
123    /// Evaluates if an incoming keystroke matches this key chord.
124    pub fn matches(&self, key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
125        let incoming = Self::normalize_key_token(key);
126        self.key.eq_ignore_ascii_case(&incoming)
127            && self.ctrl == ctrl
128            && self.shift == shift
129            && self.alt == alt
130            && self.meta == meta
131    }
132}
133
134/// Handle returned by `use_keyboard_shortcut` that unregisters the shortcut on drop.
135pub struct ShortcutHandle {
136    id: u32,
137}
138
139impl Drop for ShortcutHandle {
140    fn drop(&mut self) {
141        REGISTERED_SHORTCUTS.with(|s| {
142            s.borrow_mut().retain(|(id, _, _)| *id != self.id);
143        });
144    }
145}
146
147/// Registers a global keyboard shortcut with an invoked callback.
148pub fn use_keyboard_shortcut<F: Fn() + 'static>(shortcut: &str, handler: F) -> ShortcutHandle {
149    let chord = KeyChord::parse(shortcut);
150    let id = NEXT_SHORTCUT_ID.with(|n| {
151        let mut val = n.borrow_mut();
152        let cur = *val;
153        *val += 1;
154        cur
155    });
156
157    let callback = Rc::new(handler);
158    REGISTERED_SHORTCUTS.with(|s| {
159        s.borrow_mut().push((id, chord, callback));
160    });
161
162    ShortcutHandle { id }
163}
164
165/// Dispatches a keydown event through registered shortcuts.
166/// Returns true if any registered shortcut consumed the key event.
167pub fn dispatch_global_keydown(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> bool {
168    let mut handled = false;
169    REGISTERED_SHORTCUTS.with(|s| {
170        let list = s.borrow().clone();
171        for (_, chord, callback) in list {
172            if chord.matches(key, ctrl, shift, alt, meta) {
173                callback();
174                handled = true;
175                break;
176            }
177        }
178    });
179    handled
180}
181
182/// Handle returned by `use_clipboard()` providing reactive clipboard operations.
183#[derive(Clone)]
184pub struct ClipboardHandle {
185    pub text: Signal<String>,
186    pub copy: Rc<dyn Fn(&str)>,
187    pub read_text: Rc<dyn Fn() -> String>,
188}
189
190/// Headless hook providing reactive clipboard reading and writing.
191pub fn use_clipboard() -> ClipboardHandle {
192    let text_sig = CLIPBOARD_CONTENT.with(|c| c.borrow().clone());
193
194    let copy = {
195        let sig = text_sig.clone();
196        Rc::new(move |val: &str| {
197            sig.set(val.to_string());
198        })
199    };
200
201    let read_text = {
202        let sig = text_sig.clone();
203        Rc::new(move || sig.get())
204    };
205
206    ClipboardHandle {
207        text: text_sig,
208        copy,
209        read_text,
210    }
211}