-
-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathuse_window_scroll.rs
More file actions
57 lines (53 loc) · 1.56 KB
/
use_window_scroll.rs
File metadata and controls
57 lines (53 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports))]
use crate::{UseEventListenerOptions, use_event_listener_with_options, use_window};
use cfg_if::cfg_if;
use leptos::ev::scroll;
use leptos::prelude::*;
/// Reactive window scroll.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_window_scroll)
///
/// ## Usage
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos_use::use_window_scroll;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (x, y) = use_window_scroll();
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// > Make sure you follow the [instructions in Server-Side Rendering](https://leptos-use.rs/server_side_rendering.html).
///
/// On the server this returns `Signal`s that are always `0.0`.
pub fn use_window_scroll() -> (Signal<f64>, Signal<f64>) {
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) = signal(initial_x);
let (y, set_y) = signal(initial_y);
let _ = use_event_listener_with_options(
use_window(),
scroll,
move |_| {
set_x.set(window().scroll_x().unwrap_or_default());
set_y.set(window().scroll_y().unwrap_or_default());
},
UseEventListenerOptions::default()
.capture(false)
.passive(true),
);
(x.into(), y.into())
}