strata-dom 0.1.3

Core DOM, reactive signals, and synthetic event routing for Strata
Documentation
//! Reactive interaction and pseudo-class tracking hooks (:hover, :focus, :active, click outside).

use crate::events::EventType;
use crate::reactive::Signal;
use crate::Attribute;
use std::cell::RefCell;
use std::rc::Rc;

/// Event handler callbacks generated by `use_hover()`.
#[derive(Clone)]
pub struct HoverHandlers {
    pub onmouseenter: Rc<dyn Fn()>,
    pub onmouseleave: Rc<dyn Fn()>,
}

impl HoverHandlers {
    /// Returns the corresponding DOM event listener attributes to attach to an element.
    pub fn attributes(&self) -> Vec<Attribute> {
        let enter = self.onmouseenter.clone();
        let leave = self.onmouseleave.clone();
        vec![
            Attribute::event_listener(EventType::MouseEnter, move |_| enter()),
            Attribute::event_listener(EventType::MouseLeave, move |_| leave()),
        ]
    }
}

/// Headless hook tracking whether pointer is hovered over an element.
pub fn use_hover() -> (Signal<bool>, HoverHandlers) {
    let is_hovered = Signal::new(false);
    let on_enter = {
        let sig = is_hovered.clone();
        Rc::new(move || sig.set(true))
    };
    let on_leave = {
        let sig = is_hovered.clone();
        Rc::new(move || sig.set(false))
    };

    (
        is_hovered,
        HoverHandlers {
            onmouseenter: on_enter,
            onmouseleave: on_leave,
        },
    )
}

/// Event handler callbacks generated by `use_focus()`.
#[derive(Clone)]
pub struct FocusHandlers {
    pub onfocus: Rc<dyn Fn()>,
    pub onblur: Rc<dyn Fn()>,
}

impl FocusHandlers {
    /// Returns the corresponding DOM event listener attributes to attach to an element.
    pub fn attributes(&self) -> Vec<Attribute> {
        let focus = self.onfocus.clone();
        let blur = self.onblur.clone();
        vec![
            Attribute::event_listener(EventType::Focus, move |_| focus()),
            Attribute::event_listener(EventType::Blur, move |_| blur()),
        ]
    }
}

/// Headless hook tracking whether an element has focus.
pub fn use_focus() -> (Signal<bool>, FocusHandlers) {
    let is_focused = Signal::new(false);
    let on_focus = {
        let sig = is_focused.clone();
        Rc::new(move || sig.set(true))
    };
    let on_blur = {
        let sig = is_focused.clone();
        Rc::new(move || sig.set(false))
    };

    (
        is_focused,
        FocusHandlers {
            onfocus: on_focus,
            onblur: on_blur,
        },
    )
}

/// Headless hook tracking whether an element or any descendant has focus (:focus-within).
pub fn use_focus_within() -> (Signal<bool>, FocusHandlers) {
    let has_focus = Signal::new(false);
    let focus_depth = Rc::new(RefCell::new(0usize));

    let on_focus = {
        let sig = has_focus.clone();
        let depth = focus_depth.clone();
        Rc::new(move || {
            let mut d = depth.borrow_mut();
            *d += 1;
            sig.set(true);
        })
    };

    let on_blur = {
        let sig = has_focus.clone();
        let depth = focus_depth.clone();
        Rc::new(move || {
            let mut d = depth.borrow_mut();
            if *d > 0 {
                *d -= 1;
            }
            if *d == 0 {
                sig.set(false);
            }
        })
    };

    (
        has_focus,
        FocusHandlers {
            onfocus: on_focus,
            onblur: on_blur,
        },
    )
}

/// Event handler callbacks generated by `use_active()` or `use_press()`.
#[derive(Clone)]
pub struct PressHandlers {
    pub onmousedown: Rc<dyn Fn()>,
    pub onmouseup: Rc<dyn Fn()>,
    pub onmouseleave: Rc<dyn Fn()>,
}

impl PressHandlers {
    /// Returns the corresponding DOM event listener attributes to attach to an element.
    pub fn attributes(&self) -> Vec<Attribute> {
        let down = self.onmousedown.clone();
        let up = self.onmouseup.clone();
        let leave = self.onmouseleave.clone();
        vec![
            Attribute::event_listener(EventType::MouseDown, move |_| down()),
            Attribute::event_listener(EventType::MouseUp, move |_| up()),
            Attribute::event_listener(EventType::MouseLeave, move |_| leave()),
        ]
    }
}

/// Headless hook tracking whether an element is currently in an active/pressed state (:active).
pub fn use_active() -> (Signal<bool>, PressHandlers) {
    let is_active = Signal::new(false);
    let on_down = {
        let sig = is_active.clone();
        Rc::new(move || sig.set(true))
    };
    let on_up = {
        let sig = is_active.clone();
        Rc::new(move || sig.set(false))
    };
    let on_leave = {
        let sig = is_active.clone();
        Rc::new(move || sig.set(false))
    };

    (
        is_active,
        PressHandlers {
            onmousedown: on_down,
            onmouseup: on_up,
            onmouseleave: on_leave,
        },
    )
}

/// Alias for `use_active` adhering to mobile touch/pointer conventions.
pub fn use_press() -> (Signal<bool>, PressHandlers) {
    use_active()
}

type OutsideListener = (u32, Signal<bool>, Rc<dyn Fn()>);

thread_local! {
    static OUTSIDE_LISTENERS: RefCell<Vec<OutsideListener>> = RefCell::new(Vec::new());
    static NEXT_LISTENER_ID: RefCell<u32> = const { RefCell::new(1) };
}

/// Handle returned by `use_click_outside` that automatically deregisters on drop.
pub struct ClickOutsideHandle {
    id: u32,
}

impl Drop for ClickOutsideHandle {
    fn drop(&mut self) {
        OUTSIDE_LISTENERS.with(|l| {
            l.borrow_mut().retain(|(id, _, _)| *id != self.id);
        });
    }
}

/// Registers an outside click callback that triggers when pointer clicks occur outside an element boundary.
pub fn use_click_outside<F: Fn() + 'static>(
    is_open: Signal<bool>,
    on_dismiss: F,
) -> ClickOutsideHandle {
    let id = NEXT_LISTENER_ID.with(|n| {
        let mut val = n.borrow_mut();
        let cur = *val;
        *val += 1;
        cur
    });

    let callback = Rc::new(on_dismiss);

    OUTSIDE_LISTENERS.with(|l| {
        l.borrow_mut().push((id, is_open, callback));
    });

    ClickOutsideHandle { id }
}

/// Dispatches an outside click event from the platform or runtime event router.
/// Returns true if any outside dismiss handler was invoked.
pub fn dispatch_click_outside() -> bool {
    let mut triggered = false;
    OUTSIDE_LISTENERS.with(|l| {
        let list = l.borrow().clone();
        for (_, is_open, handler) in list {
            if is_open.get() {
                handler();
                triggered = true;
            }
        }
    });
    triggered
}

/// Captures the listener IDs of all `use_click_outside` registrations whose `is_open` signal
/// is currently `true` prior to dispatching a pointer-down event.
pub fn snapshot_open_click_outside_ids() -> Vec<u32> {
    OUTSIDE_LISTENERS.with(|l| {
        l.borrow()
            .iter()
            .filter_map(|(id, is_open, _)| if is_open.get() { Some(*id) } else { None })
            .collect()
    })
}

/// Dispatches outside-click dismissal only for listeners that were already open in `open_ids`
/// and are still open after the pointer-down event finished.
pub fn dispatch_click_outside_for_ids(open_ids: &[u32]) -> bool {
    if open_ids.is_empty() {
        return false;
    }
    let mut triggered = false;
    OUTSIDE_LISTENERS.with(|l| {
        let list = l.borrow().clone();
        for (id, is_open, handler) in list {
            if open_ids.contains(&id) && is_open.get() {
                handler();
                triggered = true;
            }
        }
    });
    triggered
}

/// Queued programmatic scroll operation executed by `AppRuntime`.
#[derive(Debug, Clone, PartialEq)]
pub enum ProgrammaticScrollCommand {
    ScrollTo { id: String, x: f32, y: f32 },
    ScrollToTop { id: String },
    ScrollToBottom { id: String },
    ScrollIntoView { target_id: String },
}

thread_local! {
    static PENDING_SCROLL_COMMANDS: RefCell<Vec<ProgrammaticScrollCommand>> = const { RefCell::new(Vec::new()) };
    static LIVE_SCROLL_OFFSETS: RefCell<std::collections::HashMap<String, (f32, f32)>> = RefCell::new(std::collections::HashMap::new());
}

/// Programmatically scrolls a scrollable container with DOM `id` to `(x, y)` in pixels.
pub fn scroll_to(id: impl Into<String>, x: f32, y: f32) {
    let id = id.into();
    LIVE_SCROLL_OFFSETS.with(|m| {
        m.borrow_mut().insert(id.clone(), (x.max(0.0), y.max(0.0)));
    });
    PENDING_SCROLL_COMMANDS.with(|q| {
        q.borrow_mut()
            .push(ProgrammaticScrollCommand::ScrollTo { id, x, y });
    });
}

/// Programmatically scrolls a scrollable container with DOM `id` to the top (`scroll_y = 0`).
pub fn scroll_to_top(id: impl Into<String>) {
    let id = id.into();
    LIVE_SCROLL_OFFSETS.with(|m| {
        let cur_x = m.borrow().get(&id).map(|v| v.0).unwrap_or(0.0);
        m.borrow_mut().insert(id.clone(), (cur_x, 0.0));
    });
    PENDING_SCROLL_COMMANDS.with(|q| {
        q.borrow_mut()
            .push(ProgrammaticScrollCommand::ScrollToTop { id });
    });
}

/// Programmatically scrolls a scrollable container with DOM `id` to its maximum vertical extent.
pub fn scroll_to_bottom(id: impl Into<String>) {
    PENDING_SCROLL_COMMANDS.with(|q| {
        q.borrow_mut()
            .push(ProgrammaticScrollCommand::ScrollToBottom { id: id.into() });
    });
}

/// Programmatically scrolls the nearest scrollable ancestor of `target_id` so the target element is visible.
pub fn scroll_into_view(target_id: impl Into<String>) {
    PENDING_SCROLL_COMMANDS.with(|q| {
        q.borrow_mut()
            .push(ProgrammaticScrollCommand::ScrollIntoView {
                target_id: target_id.into(),
            });
    });
}

/// Returns the live `(scroll_left, scroll_top)` offset for the scrollable container with DOM `id`.
pub fn get_scroll_offset(id: &str) -> (f32, f32) {
    LIVE_SCROLL_OFFSETS.with(|m| m.borrow().get(id).copied().unwrap_or((0.0, 0.0)))
}

/// Updates the live `(scroll_left, scroll_top)` registry for `id` (called by `AppRuntime`).
pub fn set_live_scroll_offset(id: &str, x: f32, y: f32) {
    LIVE_SCROLL_OFFSETS.with(|m| {
        m.borrow_mut().insert(id.to_string(), (x, y));
    });
}

/// Drains all queued programmatic scroll commands for execution by `AppRuntime`.
pub fn take_pending_scroll_commands() -> Vec<ProgrammaticScrollCommand> {
    PENDING_SCROLL_COMMANDS.with(|q| std::mem::take(&mut *q.borrow_mut()))
}

/// Returns `true` if any programmatic scroll commands are queued.
pub fn has_pending_scroll_commands() -> bool {
    PENDING_SCROLL_COMMANDS.with(|q| !q.borrow().is_empty())
}