leptos-use/src/use_resize_observer.rs

184 lines
5.5 KiB
Rust
Raw Normal View History

2023-06-13 00:31:38 +01:00
use crate::core::ElementsMaybeSignal;
use cfg_if::cfg_if;
2023-06-05 00:02:13 +01:00
use default_struct_builder::DefaultBuilder;
2023-05-29 01:52:03 +01:00
use leptos::*;
cfg_if! { if #[cfg(not(feature = "ssr"))] {
use crate::use_supported;
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
}}
2023-05-29 01:52:03 +01:00
2023-05-31 05:56:32 +01:00
/// Reports changes to the dimensions of an Element's content or the border-box.
///
/// Please refer to [ResizeObserver on MDN](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
/// for more details.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_resize_observer)
///
/// ## Usage
///
/// ```
/// # use leptos::{html::Div, *};
2023-05-31 05:56:32 +01:00
/// # use leptos_use::use_resize_observer;
/// #
/// # #[component]
2023-07-27 18:06:36 +01:00
/// # fn Demo() -> impl IntoView {
/// let el = create_node_ref::<Div>();
2023-07-27 18:06:36 +01:00
/// let (text, set_text) = create_signal("".to_string());
2023-05-31 05:56:32 +01:00
///
/// use_resize_observer(
/// el,
/// move |entries, observer| {
/// let rect = entries[0].content_rect();
/// set_text.set(format!("width: {}\nheight: {}", rect.width(), rect.height()));
2023-05-31 05:56:32 +01:00
/// },
/// );
///
2023-07-27 18:06:36 +01:00
/// view! {
/// <div node_ref=el>{ move || text.get() }</div>
/// }
2023-05-31 05:56:32 +01:00
/// # }
/// ```
2023-07-14 22:43:19 +01:00
///
/// ## Server-Side Rendering
///
/// On the server this amounts to a no-op.
2023-07-14 22:43:19 +01:00
///
2023-06-05 00:02:13 +01:00
/// ## See also
///
/// - [`use_element_size`]
2023-05-31 05:56:32 +01:00
pub fn use_resize_observer<El, T, F>(
target: El, // TODO : multiple elements?
callback: F,
2023-06-13 00:31:38 +01:00
) -> UseResizeObserverReturn<impl Fn() + Clone>
2023-05-31 05:56:32 +01:00
where
2023-07-27 18:06:36 +01:00
El: Into<ElementsMaybeSignal<T, web_sys::Element>>,
2023-05-31 05:56:32 +01:00
T: Into<web_sys::Element> + Clone + 'static,
2023-06-13 00:31:38 +01:00
F: FnMut(Vec<web_sys::ResizeObserverEntry>, web_sys::ResizeObserver) + 'static,
2023-05-31 05:56:32 +01:00
{
2023-07-27 18:06:36 +01:00
use_resize_observer_with_options(target, callback, UseResizeObserverOptions::default())
2023-05-31 05:56:32 +01:00
}
2023-06-05 00:02:13 +01:00
/// Version of [`use_resize_observer`] that takes a `web_sys::ResizeObserverOptions`. See [`use_resize_observer`] for how to use.
#[cfg_attr(feature = "ssr", allow(unused_variables, unused_mut))]
2023-05-29 01:52:03 +01:00
pub fn use_resize_observer_with_options<El, T, F>(
target: El, // TODO : multiple elements?
2023-06-13 00:31:38 +01:00
mut callback: F,
2023-06-05 00:02:13 +01:00
options: UseResizeObserverOptions,
2023-06-13 00:31:38 +01:00
) -> UseResizeObserverReturn<impl Fn() + Clone>
2023-05-31 05:56:32 +01:00
where
2023-07-27 18:06:36 +01:00
El: Into<ElementsMaybeSignal<T, web_sys::Element>>,
2023-05-29 01:52:03 +01:00
T: Into<web_sys::Element> + Clone + 'static,
2023-06-13 00:31:38 +01:00
F: FnMut(Vec<web_sys::ResizeObserverEntry>, web_sys::ResizeObserver) + 'static,
2023-05-29 01:52:03 +01:00
{
#[cfg(feature = "ssr")]
{
UseResizeObserverReturn {
is_supported: Signal::derive(|| true),
stop: || {},
2023-05-29 01:52:03 +01:00
}
}
#[cfg(not(feature = "ssr"))]
{
use crate::js;
let closure_js = Closure::<dyn FnMut(js_sys::Array, web_sys::ResizeObserver)>::new(
move |entries: js_sys::Array, observer| {
callback(
entries
.to_vec()
.into_iter()
.map(|v| v.unchecked_into::<web_sys::ResizeObserverEntry>())
.collect(),
observer,
);
},
)
.into_js_value();
2023-05-29 01:52:03 +01:00
let observer: Rc<RefCell<Option<web_sys::ResizeObserver>>> = Rc::new(RefCell::new(None));
2023-05-29 01:52:03 +01:00
let is_supported = use_supported(|| js!("ResizeObserver" in &window()));
2023-06-13 17:50:39 +01:00
let cleanup = {
let observer = Rc::clone(&observer);
2023-05-31 05:56:32 +01:00
move || {
let mut observer = observer.borrow_mut();
if let Some(o) = observer.as_ref() {
o.disconnect();
*observer = None;
}
}
};
2023-05-31 05:56:32 +01:00
let targets = target.into();
2023-06-13 00:31:38 +01:00
let stop_watch = {
let cleanup = cleanup.clone();
2023-05-29 01:52:03 +01:00
watch(
move || targets.get(),
move |targets, _, _| {
cleanup();
2023-05-31 05:56:32 +01:00
if is_supported.get_untracked() && !targets.is_empty() {
let obs = web_sys::ResizeObserver::new(
closure_js.clone().as_ref().unchecked_ref(),
)
.expect("failed to create ResizeObserver");
2023-05-31 05:56:32 +01:00
for target in targets.iter().flatten() {
let target: web_sys::Element = target.clone().into();
obs.observe_with_options(&target, &options.clone().into());
}
observer.replace(Some(obs));
}
},
true,
)
};
let stop = move || {
cleanup();
stop_watch();
};
on_cleanup(stop.clone());
UseResizeObserverReturn { is_supported, stop }
}
2023-05-31 05:56:32 +01:00
}
2023-06-05 00:02:13 +01:00
/// Options for [`use_resize_observer_with_options`].
#[derive(DefaultBuilder, Clone, Default)]
2023-06-05 00:02:13 +01:00
pub struct UseResizeObserverOptions {
/// The box that is used to determine the dimensions of the target. Defaults to `ContentBox`.
#[builder(into)]
pub box_: Option<web_sys::ResizeObserverBoxOptions>,
2023-06-05 00:02:13 +01:00
}
2023-06-10 19:43:51 +01:00
impl From<UseResizeObserverOptions> for web_sys::ResizeObserverOptions {
fn from(val: UseResizeObserverOptions) -> Self {
2023-06-05 00:02:13 +01:00
let mut options = web_sys::ResizeObserverOptions::new();
options.box_(
val.box_
.unwrap_or(web_sys::ResizeObserverBoxOptions::ContentBox),
);
2023-06-05 00:02:13 +01:00
options
}
}
2023-05-31 05:56:32 +01:00
/// The return value of [`use_resize_observer`].
2023-06-13 00:31:38 +01:00
pub struct UseResizeObserverReturn<F: Fn() + Clone> {
2023-05-31 05:56:32 +01:00
/// Whether the browser supports the ResizeObserver API
pub is_supported: Signal<bool>,
/// A function to stop and detach the ResizeObserver
2023-06-13 00:31:38 +01:00
pub stop: F,
2023-05-29 01:52:03 +01:00
}