leptos-use/src/use_window_scroll.rs

62 lines
1.6 KiB
Rust
Raw Normal View History

2023-07-14 22:43:19 +01:00
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports))]
2023-07-07 23:07:56 +01:00
use crate::use_event_listener_with_options;
2023-07-14 22:43:19 +01:00
use cfg_if::cfg_if;
2023-07-07 23:07:56 +01:00
use leptos::ev::scroll;
use leptos::*;
use web_sys::AddEventListenerOptions;
/// Reactive window scroll.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_window_scroll)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
2023-07-07 23:34:50 +01:00
/// # use leptos_use::use_window_scroll;
2023-07-07 23:07:56 +01:00
/// #
/// # #[component]
/// # fn Demo(cx: Scope) -> impl IntoView {
/// let (x, y) = use_window_scroll(cx);
/// #
/// # view! { cx, }
/// # }
/// ```
2023-07-14 22:43:19 +01:00
///
/// ## Server-Side Rendering
///
/// On the server this returns `Signal`s that are always `0.0`.
2023-07-07 23:07:56 +01:00
pub fn use_window_scroll(cx: Scope) -> (Signal<f64>, Signal<f64>) {
2023-07-14 22:43:19 +01:00
cfg_if! { if #[cfg(feature = "ssr")] {
let initial_x = 0.0;
let initial_y = 0.0;
} else {
let initial_x = window().scroll_x().unwrap_or_default();
let initial_y = window().scroll_y().unwrap_or_default();
}}
let (x, set_x) = create_signal(cx, initial_x);
let (y, set_y) = create_signal(cx, initial_y);
2023-07-07 23:07:56 +01:00
2023-07-14 22:43:19 +01:00
cfg_if! { if #[cfg(not(feature = "ssr"))] {
let mut options = AddEventListenerOptions::new();
options.capture(false);
options.passive(true);
2023-07-07 23:07:56 +01:00
2023-07-14 22:43:19 +01:00
let _ = use_event_listener_with_options(
cx,
window(),
scroll,
move |_| {
set_x.set(window().scroll_x().unwrap_or_default());
set_y.set(window().scroll_y().unwrap_or_default());
},
options,
);
}}
2023-07-07 23:07:56 +01:00
(x.into(), y.into())
}