use crate::events::EventType;
use crate::reactive::Signal;
use crate::Attribute;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
pub struct HoverHandlers {
pub onmouseenter: Rc<dyn Fn()>,
pub onmouseleave: Rc<dyn Fn()>,
}
impl HoverHandlers {
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()),
]
}
}
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,
},
)
}
#[derive(Clone)]
pub struct FocusHandlers {
pub onfocus: Rc<dyn Fn()>,
pub onblur: Rc<dyn Fn()>,
}
impl FocusHandlers {
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()),
]
}
}
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,
},
)
}
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,
},
)
}
#[derive(Clone)]
pub struct PressHandlers {
pub onmousedown: Rc<dyn Fn()>,
pub onmouseup: Rc<dyn Fn()>,
pub onmouseleave: Rc<dyn Fn()>,
}
impl PressHandlers {
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()),
]
}
}
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,
},
)
}
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) };
}
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);
});
}
}
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 }
}
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
}
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()
})
}
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
}
#[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());
}
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 });
});
}
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 });
});
}
pub fn scroll_to_bottom(id: impl Into<String>) {
PENDING_SCROLL_COMMANDS.with(|q| {
q.borrow_mut()
.push(ProgrammaticScrollCommand::ScrollToBottom { id: id.into() });
});
}
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(),
});
});
}
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)))
}
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));
});
}
pub fn take_pending_scroll_commands() -> Vec<ProgrammaticScrollCommand> {
PENDING_SCROLL_COMMANDS.with(|q| std::mem::take(&mut *q.borrow_mut()))
}
pub fn has_pending_scroll_commands() -> bool {
PENDING_SCROLL_COMMANDS.with(|q| !q.borrow().is_empty())
}