use crate::core::ElementMaybeSignal;
use crate::{use_event_listener_with_options, UseEventListenerOptions};
use cfg_if::cfg_if;
use default_struct_builder::DefaultBuilder;
use leptos::ev::{mouseenter, mouseleave};
use leptos::leptos_dom::helpers::TimeoutHandle;
use leptos::*;
cfg_if! { if #[cfg(not(feature = "ssr"))] {
use std::time::Duration;
}}
pub fn use_element_hover<El, T>(el: El) -> Signal<bool>
where
El: Clone,
El: Into<ElementMaybeSignal<T, web_sys::EventTarget>>,
T: Into<web_sys::EventTarget> + Clone + 'static,
{
use_element_hover_with_options(el, UseElementHoverOptions::default())
}
#[cfg_attr(feature = "ssr", allow(unused_variables, unused_mut))]
pub fn use_element_hover_with_options<El, T>(
el: El,
options: UseElementHoverOptions,
) -> Signal<bool>
where
El: Clone,
El: Into<ElementMaybeSignal<T, web_sys::EventTarget>>,
T: Into<web_sys::EventTarget> + Clone + 'static,
{
let UseElementHoverOptions {
delay_enter,
delay_leave,
} = options;
let (is_hovered, set_hovered) = create_signal(false);
let mut timer: Option<TimeoutHandle> = None;
let mut toggle = move |entering: bool| {
cfg_if! { if #[cfg(not(feature = "ssr"))] {
let delay = if entering { delay_enter } else { delay_leave };
if let Some(handle) = timer.take() {
handle.clear();
}
if delay > 0 {
timer = set_timeout_with_handle(
move || set_hovered.set(entering),
Duration::from_millis(delay),
)
.ok();
} else {
set_hovered.set(entering);
}
}}
};
let listener_options = UseEventListenerOptions::default().passive(true);
let _ = use_event_listener_with_options(
el.clone(),
mouseenter,
move |_| toggle(true),
listener_options,
);
let _ =
use_event_listener_with_options(el, mouseleave, move |_| toggle(false), listener_options);
is_hovered.into()
}
#[derive(DefaultBuilder, Default)]
pub struct UseElementHoverOptions {
delay_enter: u64,
delay_leave: u64,
}