leptos_use/
use_element_visibility.rs

1use crate::core::IntoElementMaybeSignal;
2use cfg_if::cfg_if;
3use default_struct_builder::DefaultBuilder;
4use leptos::prelude::*;
5use std::marker::PhantomData;
6
7#[cfg(not(feature = "ssr"))]
8use crate::{use_intersection_observer_with_options, UseIntersectionObserverOptions};
9use leptos::reactive::wrappers::read::Signal;
10
11/// Tracks the visibility of an element within the viewport.
12///
13/// ## Demo
14///
15/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_element_visibility)
16///
17/// ## Usage
18///
19/// ```
20/// # use leptos::prelude::*;
21/// # use leptos::html::Div;
22/// # use leptos_use::use_element_visibility;
23/// #
24/// # #[component]
25/// # fn Demo() -> impl IntoView {
26/// let el = NodeRef::<Div>::new();
27///
28/// let is_visible = use_element_visibility(el);
29///
30/// view! {
31///     <div node_ref=el>
32///         <h1>{is_visible}</h1>
33///     </div>
34/// }
35/// # }
36/// ```
37///
38/// ## Server-Side Rendering
39///
40/// On the server this returns a `Signal` that always contains the value `false`.
41///
42/// ## See also
43///
44/// * [`fn@crate::use_intersection_observer`]
45pub fn use_element_visibility<El, M>(target: El) -> Signal<bool>
46where
47    El: IntoElementMaybeSignal<web_sys::Element, M>,
48{
49    use_element_visibility_with_options::<El, M, web_sys::Element, _>(
50        target,
51        UseElementVisibilityOptions::default(),
52    )
53}
54
55/// Version of [`use_element_visibility`] with that takes a `UseElementVisibilityOptions`. See [`use_element_visibility`] for how to use.
56#[cfg_attr(feature = "ssr", allow(unused_variables))]
57pub fn use_element_visibility_with_options<El, M, ContainerEl, ContainerM>(
58    target: El,
59    options: UseElementVisibilityOptions<ContainerEl, ContainerM>,
60) -> Signal<bool>
61where
62    El: IntoElementMaybeSignal<web_sys::Element, M>,
63    ContainerEl: IntoElementMaybeSignal<web_sys::Element, ContainerM>,
64{
65    let (is_visible, set_visible) = signal(false);
66
67    cfg_if! { if #[cfg(not(feature = "ssr"))] {
68        use_intersection_observer_with_options(
69            target.into_element_maybe_signal(),
70            move |entries, _| {
71                // In some circumstances Chrome passes a first (or only) entry which has a zero bounding client rect
72                // and returns `is_intersecting` erroneously as `false`.
73                if let Some(entry) = entries.into_iter().find(|entry| {
74                    let rect = entry.bounding_client_rect();
75                    rect.width() > 0.0 || rect.height() > 0.0
76                }) {
77                    set_visible.set(entry.is_intersecting());
78                }
79            },
80            UseIntersectionObserverOptions::default().root(options.viewport),
81        );
82    }}
83
84    is_visible.into()
85}
86
87/// Options for [`use_element_visibility_with_options`].
88#[derive(DefaultBuilder)]
89pub struct UseElementVisibilityOptions<El, M>
90where
91    El: IntoElementMaybeSignal<web_sys::Element, M>,
92{
93    /// A `web_sys::Element` or `web_sys::Document` object which is an ancestor of the intended `target`,
94    /// whose bounding rectangle will be considered the viewport.
95    /// Any part of the target not visible in the visible area of the `root` is not considered visible.
96    /// Defaults to `None` (which means the root `document` will be used).
97    /// Please note that setting this to a `Some(document)` may not be supported by all browsers.
98    /// See [Browser Compatibility](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#browser_compatibility)
99    #[cfg_attr(feature = "ssr", allow(dead_code))]
100    viewport: Option<El>,
101
102    #[builder(skip)]
103    _marker: PhantomData<M>,
104}
105
106impl<M> Default for UseElementVisibilityOptions<web_sys::Element, M>
107where
108    web_sys::Element: IntoElementMaybeSignal<web_sys::Element, M>,
109{
110    fn default() -> Self {
111        Self {
112            viewport: None,
113            _marker: PhantomData,
114        }
115    }
116}