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
58
59
use gloo::utils::window;
use yew::prelude::*;

use super::{use_event_with_window, use_mount, use_raf_state};

/// A sensor hook that tracks Window scroll position.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(UseWindowScroll)]
/// fn window_scroll() -> Html {
///     let state = use_window_scroll();
///     
///     html! {
///         <>
///             <b>{ " X: " }</b>
///             { state.0 }
///             <b>{ " Y: " }</b>
///             { state.1 }
///         </>
///     }
/// }
/// ```
#[hook]
pub fn use_window_scroll() -> (f64, f64) {
    let state = use_raf_state(|| {
        (
            window().page_x_offset().unwrap(),
            window().page_y_offset().unwrap(),
        )
    });

    {
        let state = state.clone();
        use_event_with_window("scroll", move |_: Event| {
            state.set((
                window().page_x_offset().unwrap(),
                window().page_y_offset().unwrap(),
            ));
        });
    }

    {
        let state = state.clone();
        use_mount(move || {
            state.set((
                window().page_x_offset().unwrap(),
                window().page_y_offset().unwrap(),
            ));
        });
    }

    *state
}