Skip to main content

strata_dom/hooks/
interaction.rs

1//! Reactive interaction and pseudo-class tracking hooks (:hover, :focus, :active, click outside).
2
3use crate::events::EventType;
4use crate::reactive::Signal;
5use crate::Attribute;
6use std::cell::RefCell;
7use std::rc::Rc;
8
9/// Event handler callbacks generated by `use_hover()`.
10#[derive(Clone)]
11pub struct HoverHandlers {
12    pub onmouseenter: Rc<dyn Fn()>,
13    pub onmouseleave: Rc<dyn Fn()>,
14}
15
16impl HoverHandlers {
17    /// Returns the corresponding DOM event listener attributes to attach to an element.
18    pub fn attributes(&self) -> Vec<Attribute> {
19        let enter = self.onmouseenter.clone();
20        let leave = self.onmouseleave.clone();
21        vec![
22            Attribute::event_listener(EventType::MouseEnter, move |_| enter()),
23            Attribute::event_listener(EventType::MouseLeave, move |_| leave()),
24        ]
25    }
26}
27
28/// Headless hook tracking whether pointer is hovered over an element.
29pub fn use_hover() -> (Signal<bool>, HoverHandlers) {
30    let is_hovered = Signal::new(false);
31    let on_enter = {
32        let sig = is_hovered.clone();
33        Rc::new(move || sig.set(true))
34    };
35    let on_leave = {
36        let sig = is_hovered.clone();
37        Rc::new(move || sig.set(false))
38    };
39
40    (
41        is_hovered,
42        HoverHandlers {
43            onmouseenter: on_enter,
44            onmouseleave: on_leave,
45        },
46    )
47}
48
49/// Event handler callbacks generated by `use_focus()`.
50#[derive(Clone)]
51pub struct FocusHandlers {
52    pub onfocus: Rc<dyn Fn()>,
53    pub onblur: Rc<dyn Fn()>,
54}
55
56impl FocusHandlers {
57    /// Returns the corresponding DOM event listener attributes to attach to an element.
58    pub fn attributes(&self) -> Vec<Attribute> {
59        let focus = self.onfocus.clone();
60        let blur = self.onblur.clone();
61        vec![
62            Attribute::event_listener(EventType::Focus, move |_| focus()),
63            Attribute::event_listener(EventType::Blur, move |_| blur()),
64        ]
65    }
66}
67
68/// Headless hook tracking whether an element has focus.
69pub fn use_focus() -> (Signal<bool>, FocusHandlers) {
70    let is_focused = Signal::new(false);
71    let on_focus = {
72        let sig = is_focused.clone();
73        Rc::new(move || sig.set(true))
74    };
75    let on_blur = {
76        let sig = is_focused.clone();
77        Rc::new(move || sig.set(false))
78    };
79
80    (
81        is_focused,
82        FocusHandlers {
83            onfocus: on_focus,
84            onblur: on_blur,
85        },
86    )
87}
88
89/// Headless hook tracking whether an element or any descendant has focus (:focus-within).
90pub fn use_focus_within() -> (Signal<bool>, FocusHandlers) {
91    let has_focus = Signal::new(false);
92    let focus_depth = Rc::new(RefCell::new(0usize));
93
94    let on_focus = {
95        let sig = has_focus.clone();
96        let depth = focus_depth.clone();
97        Rc::new(move || {
98            let mut d = depth.borrow_mut();
99            *d += 1;
100            sig.set(true);
101        })
102    };
103
104    let on_blur = {
105        let sig = has_focus.clone();
106        let depth = focus_depth.clone();
107        Rc::new(move || {
108            let mut d = depth.borrow_mut();
109            if *d > 0 {
110                *d -= 1;
111            }
112            if *d == 0 {
113                sig.set(false);
114            }
115        })
116    };
117
118    (
119        has_focus,
120        FocusHandlers {
121            onfocus: on_focus,
122            onblur: on_blur,
123        },
124    )
125}
126
127/// Event handler callbacks generated by `use_active()` or `use_press()`.
128#[derive(Clone)]
129pub struct PressHandlers {
130    pub onmousedown: Rc<dyn Fn()>,
131    pub onmouseup: Rc<dyn Fn()>,
132    pub onmouseleave: Rc<dyn Fn()>,
133}
134
135impl PressHandlers {
136    /// Returns the corresponding DOM event listener attributes to attach to an element.
137    pub fn attributes(&self) -> Vec<Attribute> {
138        let down = self.onmousedown.clone();
139        let up = self.onmouseup.clone();
140        let leave = self.onmouseleave.clone();
141        vec![
142            Attribute::event_listener(EventType::MouseDown, move |_| down()),
143            Attribute::event_listener(EventType::MouseUp, move |_| up()),
144            Attribute::event_listener(EventType::MouseLeave, move |_| leave()),
145        ]
146    }
147}
148
149/// Headless hook tracking whether an element is currently in an active/pressed state (:active).
150pub fn use_active() -> (Signal<bool>, PressHandlers) {
151    let is_active = Signal::new(false);
152    let on_down = {
153        let sig = is_active.clone();
154        Rc::new(move || sig.set(true))
155    };
156    let on_up = {
157        let sig = is_active.clone();
158        Rc::new(move || sig.set(false))
159    };
160    let on_leave = {
161        let sig = is_active.clone();
162        Rc::new(move || sig.set(false))
163    };
164
165    (
166        is_active,
167        PressHandlers {
168            onmousedown: on_down,
169            onmouseup: on_up,
170            onmouseleave: on_leave,
171        },
172    )
173}
174
175/// Alias for `use_active` adhering to mobile touch/pointer conventions.
176pub fn use_press() -> (Signal<bool>, PressHandlers) {
177    use_active()
178}
179
180type OutsideListener = (u32, Signal<bool>, Rc<dyn Fn()>);
181
182thread_local! {
183    static OUTSIDE_LISTENERS: RefCell<Vec<OutsideListener>> = RefCell::new(Vec::new());
184    static NEXT_LISTENER_ID: RefCell<u32> = const { RefCell::new(1) };
185}
186
187/// Handle returned by `use_click_outside` that automatically deregisters on drop.
188pub struct ClickOutsideHandle {
189    id: u32,
190}
191
192impl Drop for ClickOutsideHandle {
193    fn drop(&mut self) {
194        OUTSIDE_LISTENERS.with(|l| {
195            l.borrow_mut().retain(|(id, _, _)| *id != self.id);
196        });
197    }
198}
199
200/// Registers an outside click callback that triggers when pointer clicks occur outside an element boundary.
201pub fn use_click_outside<F: Fn() + 'static>(
202    is_open: Signal<bool>,
203    on_dismiss: F,
204) -> ClickOutsideHandle {
205    let id = NEXT_LISTENER_ID.with(|n| {
206        let mut val = n.borrow_mut();
207        let cur = *val;
208        *val += 1;
209        cur
210    });
211
212    let callback = Rc::new(on_dismiss);
213
214    OUTSIDE_LISTENERS.with(|l| {
215        l.borrow_mut().push((id, is_open, callback));
216    });
217
218    ClickOutsideHandle { id }
219}
220
221/// Dispatches an outside click event from the platform or runtime event router.
222/// Returns true if any outside dismiss handler was invoked.
223pub fn dispatch_click_outside() -> bool {
224    let mut triggered = false;
225    OUTSIDE_LISTENERS.with(|l| {
226        let list = l.borrow().clone();
227        for (_, is_open, handler) in list {
228            if is_open.get() {
229                handler();
230                triggered = true;
231            }
232        }
233    });
234    triggered
235}
236
237/// Captures the listener IDs of all `use_click_outside` registrations whose `is_open` signal
238/// is currently `true` prior to dispatching a pointer-down event.
239pub fn snapshot_open_click_outside_ids() -> Vec<u32> {
240    OUTSIDE_LISTENERS.with(|l| {
241        l.borrow()
242            .iter()
243            .filter_map(|(id, is_open, _)| if is_open.get() { Some(*id) } else { None })
244            .collect()
245    })
246}
247
248/// Dispatches outside-click dismissal only for listeners that were already open in `open_ids`
249/// and are still open after the pointer-down event finished.
250pub fn dispatch_click_outside_for_ids(open_ids: &[u32]) -> bool {
251    if open_ids.is_empty() {
252        return false;
253    }
254    let mut triggered = false;
255    OUTSIDE_LISTENERS.with(|l| {
256        let list = l.borrow().clone();
257        for (id, is_open, handler) in list {
258            if open_ids.contains(&id) && is_open.get() {
259                handler();
260                triggered = true;
261            }
262        }
263    });
264    triggered
265}
266
267/// Queued programmatic scroll operation executed by `AppRuntime`.
268#[derive(Debug, Clone, PartialEq)]
269pub enum ProgrammaticScrollCommand {
270    ScrollTo { id: String, x: f32, y: f32 },
271    ScrollToTop { id: String },
272    ScrollToBottom { id: String },
273    ScrollIntoView { target_id: String },
274}
275
276thread_local! {
277    static PENDING_SCROLL_COMMANDS: RefCell<Vec<ProgrammaticScrollCommand>> = const { RefCell::new(Vec::new()) };
278    static LIVE_SCROLL_OFFSETS: RefCell<std::collections::HashMap<String, (f32, f32)>> = RefCell::new(std::collections::HashMap::new());
279}
280
281/// Programmatically scrolls a scrollable container with DOM `id` to `(x, y)` in pixels.
282pub fn scroll_to(id: impl Into<String>, x: f32, y: f32) {
283    let id = id.into();
284    LIVE_SCROLL_OFFSETS.with(|m| {
285        m.borrow_mut().insert(id.clone(), (x.max(0.0), y.max(0.0)));
286    });
287    PENDING_SCROLL_COMMANDS.with(|q| {
288        q.borrow_mut()
289            .push(ProgrammaticScrollCommand::ScrollTo { id, x, y });
290    });
291}
292
293/// Programmatically scrolls a scrollable container with DOM `id` to the top (`scroll_y = 0`).
294pub fn scroll_to_top(id: impl Into<String>) {
295    let id = id.into();
296    LIVE_SCROLL_OFFSETS.with(|m| {
297        let cur_x = m.borrow().get(&id).map(|v| v.0).unwrap_or(0.0);
298        m.borrow_mut().insert(id.clone(), (cur_x, 0.0));
299    });
300    PENDING_SCROLL_COMMANDS.with(|q| {
301        q.borrow_mut()
302            .push(ProgrammaticScrollCommand::ScrollToTop { id });
303    });
304}
305
306/// Programmatically scrolls a scrollable container with DOM `id` to its maximum vertical extent.
307pub fn scroll_to_bottom(id: impl Into<String>) {
308    PENDING_SCROLL_COMMANDS.with(|q| {
309        q.borrow_mut()
310            .push(ProgrammaticScrollCommand::ScrollToBottom { id: id.into() });
311    });
312}
313
314/// Programmatically scrolls the nearest scrollable ancestor of `target_id` so the target element is visible.
315pub fn scroll_into_view(target_id: impl Into<String>) {
316    PENDING_SCROLL_COMMANDS.with(|q| {
317        q.borrow_mut()
318            .push(ProgrammaticScrollCommand::ScrollIntoView {
319                target_id: target_id.into(),
320            });
321    });
322}
323
324/// Returns the live `(scroll_left, scroll_top)` offset for the scrollable container with DOM `id`.
325pub fn get_scroll_offset(id: &str) -> (f32, f32) {
326    LIVE_SCROLL_OFFSETS.with(|m| m.borrow().get(id).copied().unwrap_or((0.0, 0.0)))
327}
328
329/// Updates the live `(scroll_left, scroll_top)` registry for `id` (called by `AppRuntime`).
330pub fn set_live_scroll_offset(id: &str, x: f32, y: f32) {
331    LIVE_SCROLL_OFFSETS.with(|m| {
332        m.borrow_mut().insert(id.to_string(), (x, y));
333    });
334}
335
336/// Drains all queued programmatic scroll commands for execution by `AppRuntime`.
337pub fn take_pending_scroll_commands() -> Vec<ProgrammaticScrollCommand> {
338    PENDING_SCROLL_COMMANDS.with(|q| std::mem::take(&mut *q.borrow_mut()))
339}
340
341/// Returns `true` if any programmatic scroll commands are queued.
342pub fn has_pending_scroll_commands() -> bool {
343    PENDING_SCROLL_COMMANDS.with(|q| !q.borrow().is_empty())
344}