leptos-use-scroll 0.20.0

Reactive scroll position and state
Documentation
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use crate::{Directions, IntoElementMaybeSignal, UseScrollOptions, UseScrollReturn};
use cfg_if::cfg_if;
use leptos::prelude::*;
#[cfg(not(feature = "ssr"))]
use leptos::reactive::wrappers::read::Signal;
#[cfg(not(feature = "ssr"))]
use std::rc::Rc;

cfg_if! { if #[cfg(not(feature = "ssr"))] {
use crate::use_event_listener_with_options;
use crate::{
    sendwrap_fn, use_debounce_fn_with_arg, use_throttle_fn_with_arg_and_options, ThrottleOptions,
};
use leptos::ev;
use leptos::ev::scrollend;
use send_wrapper::SendWrapper;
use wasm_bindgen::JsCast;


/// We have to check if the scroll amount is close enough to some threshold in order to
/// more accurately calculate arrivedState. This is because scrollTop/scrollLeft are non-rounded
/// numbers, while scrollHeight/scrollWidth and clientHeight/clientWidth are rounded.
/// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#determine_if_an_element_has_been_totally_scrolled
const ARRIVED_STATE_THRESHOLD_PIXELS: f64 = 1.0;
}}

/// Reactive scroll position and state.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_scroll)
///
/// ## Usage
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::ev::resize;
/// # use leptos::html::Div;
/// # use leptos_use_scroll::{use_scroll, UseScrollReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let element = NodeRef::<Div>::new();
///
/// let UseScrollReturn {
///     x, y, set_x, set_y, is_scrolling, arrived_state, directions, ..
/// } = use_scroll(element);
///
/// view! {
///     <div node_ref=element>"..."</div>
/// }
/// # }
/// ```
///
/// ### With Offsets
///
/// You can provide offsets when you use [`use_scroll_with_options`].
/// These offsets are thresholds in pixels when a side is considered to have arrived. This is reflected in the return field `arrived_state`.
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::html::Div;
/// # use leptos::ev::resize;
/// # use leptos_use_scroll::{use_scroll_with_options, UseScrollReturn, UseScrollOptions, ScrollOffset};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// # let element = NodeRef::<Div>::new();
/// #
/// let UseScrollReturn {
///     x,
///     y,
///     set_x,
///     set_y,
///     is_scrolling,
///     arrived_state,
///     directions,
///     ..
/// } = use_scroll_with_options(
///     element,
///     UseScrollOptions::default().offset(ScrollOffset {
///         top: 30.0,
///         bottom: 30.0,
///         right: 30.0,
///         left: 30.0,
///     }),
/// );
/// #
/// #     view! { /// #         <div node_ref=element>"..."</div>
/// #     }
/// # }
/// ```
///
/// ### Setting Scroll Position
///
/// Set the `x` and `y` values to make the element scroll to that position.
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::html::Div;
/// # use leptos::ev::resize;
/// # use leptos_use_scroll::{use_scroll, UseScrollReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let element = NodeRef::<Div>::new();
///
/// let UseScrollReturn {
///     x, y, set_x, set_y, ..
/// } = use_scroll(element);
///
/// view! {
///     <div node_ref=element>"..."</div>
///     <button on:click=move |_| set_x(x.get_untracked() + 10.0)>"Scroll right 10px"</button>
///     <button on:click=move |_| set_y(y.get_untracked() + 10.0)>"Scroll down 10px"</button>
/// }
/// # }
/// ```
///
/// ### Smooth Scrolling
///
/// Set `behavior: smooth` to enable smooth scrolling. The `behavior` option defaults to `auto`,
/// which means no smooth scrolling. See the `behavior` option on
/// [Element.scrollTo](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo) for more information.
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::ev::resize;
/// # use leptos::html::Div;
/// # use leptos_use_scroll::{use_scroll_with_options, UseScrollReturn, UseScrollOptions, ScrollBehavior};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// # let element = NodeRef::<Div>::new();
/// #
/// let UseScrollReturn {
///     x, y, set_x, set_y, ..
/// } = use_scroll_with_options(
///     element,
///     UseScrollOptions::default().behavior(ScrollBehavior::Smooth),
/// );
/// #
/// # view! { /// #     <div node_ref=element>"..."</div>
/// # }
/// # }
/// ```
///
/// or as a `Signal`:
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::ev::resize;
/// # use leptos::html::Div;
/// # use leptos_use_scroll::{use_scroll_with_options, UseScrollReturn, UseScrollOptions, ScrollBehavior};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// # let element = NodeRef::<Div>::new();
/// #
/// let (smooth, set_smooth) = signal(false);
///
/// let behavior = Signal::derive(move || {
///     if smooth.get() { ScrollBehavior::Smooth } else { ScrollBehavior::Auto }
/// });
///
/// let UseScrollReturn {
///     x, y, set_x, set_y, ..
/// } = use_scroll_with_options(
///     element,
///     UseScrollOptions::default().behavior(behavior),
/// );
/// #
/// # view! { /// #     <div node_ref=element>"..."</div>
/// # }
/// # }
/// ```
///
/// ## SendWrapped Return
///
/// The returned closures `set_x`, `set_y` and `measure` are sendwrapped functions. They can
/// only be called from the same thread that called `use_scroll`.
///
/// ## 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 signals that don't change and setters that are noops.
pub fn use_scroll<El, M>(
    element: El,
) -> UseScrollReturn<
    impl Fn(f64) + Clone + Send + Sync,
    impl Fn(f64) + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
>
where
    El: IntoElementMaybeSignal<web_sys::Element, M>,
{
    use_scroll_with_options(element, Default::default())
}

/// Version of [`use_scroll`] with options. See [`use_scroll`] for how to use.
#[cfg_attr(feature = "ssr", allow(unused_variables))]
pub fn use_scroll_with_options<El, M>(
    element: El,
    options: UseScrollOptions,
) -> UseScrollReturn<
    impl Fn(f64) + Clone + Send + Sync,
    impl Fn(f64) + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
>
where
    El: IntoElementMaybeSignal<web_sys::Element, M>,
{
    let (internal_x, set_internal_x) = signal(0.0);
    let (internal_y, set_internal_y) = signal(0.0);

    let (is_scrolling, set_is_scrolling) = signal(false);

    let arrived_state = RwSignal::new(Directions {
        left: true,
        right: false,
        top: true,
        bottom: false,
    });
    let directions = RwSignal::new(Directions {
        left: false,
        right: false,
        top: false,
        bottom: false,
    });

    let set_x;
    let set_y;
    let measure;

    #[cfg(feature = "ssr")]
    {
        set_x = |_| {};
        set_y = |_| {};
        measure = || {};
    }

    #[cfg(not(feature = "ssr"))]
    {
        let signal = element.into_element_maybe_signal();
        let behavior = options.behavior;

        let scroll_to = move |x: Option<f64>, y: Option<f64>| {
            let element = signal.get_untracked();

            if let Some(element) = element {
                let scroll_options = web_sys::ScrollToOptions::new();
                scroll_options.set_behavior(behavior.get_untracked().into());

                if let Some(x) = x {
                    scroll_options.set_left(x);
                }
                if let Some(y) = y {
                    scroll_options.set_top(y);
                }

                element.scroll_to_with_scroll_to_options(&scroll_options);
            }
        };

        set_x = sendwrap_fn!(move |x| scroll_to(Some(x), None));

        set_y = sendwrap_fn!(move |y| scroll_to(None, Some(y)));

        let on_scroll_end = {
            let on_stop = Rc::clone(&options.on_stop);

            move |e| {
                if !is_scrolling.try_get_untracked().unwrap_or_default() {
                    return;
                }

                set_is_scrolling.set(false);
                directions.update(|directions| {
                    directions.left = false;
                    directions.right = false;
                    directions.top = false;
                    directions.bottom = false;
                    on_stop.clone()(e);
                });
            }
        };

        let throttle = options.throttle;

        let on_scroll_end_debounced =
            use_debounce_fn_with_arg(on_scroll_end.clone(), throttle + options.idle);

        let offset = options.offset;

        #[allow(clippy::unnecessary_cast)]
        let set_arrived_state = move |target: web_sys::Element| {
            let style = window()
                .get_computed_style(&target)
                .expect("failed to get computed style");

            if let Some(style) = style {
                let display = style
                    .get_property_value("display")
                    .expect("failed to get display");
                let flex_direction = style
                    .get_property_value("flex-direction")
                    .expect("failed to get flex-direction");
                let direction = style.get_property_value("direction").unwrap_or_default();

                let scroll_left = target.scroll_left() as f64;
                let scroll_left_abs = scroll_left.abs();

                directions.update(|directions| {
                    directions.left = scroll_left < internal_x.get_untracked();
                    directions.right = scroll_left > internal_x.get_untracked();
                });

                let left = scroll_left_abs <= offset.left;
                let right = scroll_left_abs + target.client_width() as f64
                    >= target.scroll_width() as f64 - offset.right - ARRIVED_STATE_THRESHOLD_PIXELS;

                // Right-to-left containers use the "negative scrollLeft" model:
                // 0 is the right-hand edge and the value decreases towards the
                // left one, so taking the absolute value above reports the two
                // edges swapped. A row-reverse flex box swaps them as well, and
                // a container that is both swaps twice.
                let is_reversed =
                    (display == "flex" && flex_direction == "row-reverse") != (direction == "rtl");

                arrived_state.update(|arrived_state| {
                    if is_reversed {
                        arrived_state.left = right;
                        arrived_state.right = left;
                    } else {
                        arrived_state.left = left;
                        arrived_state.right = right;
                    }
                });
                set_internal_x.set(scroll_left);

                let mut scroll_top = target.scroll_top() as f64;

                // patch for mobile compatibility
                if target == document().unchecked_into::<web_sys::Element>() && scroll_top == 0.0 {
                    scroll_top = document().body().expect("failed to get body").scroll_top() as f64;
                }

                let scroll_top_abs = scroll_top.abs();

                directions.update(|directions| {
                    directions.top = scroll_top < internal_y.get_untracked();
                    directions.bottom = scroll_top > internal_y.get_untracked();
                });

                let top = scroll_top_abs <= offset.top;
                let bottom = scroll_top_abs + target.client_height() as f64
                    >= target.scroll_height() as f64
                        - offset.bottom
                        - ARRIVED_STATE_THRESHOLD_PIXELS;

                // reverse columns and rows behave exactly the other way around,
                // bottom is treated as top and top is treated as the negative version of bottom
                arrived_state.update(|arrived_state| {
                    if display == "flex" && flex_direction == "column-reverse" {
                        arrived_state.top = bottom;
                        arrived_state.bottom = top;
                    } else {
                        arrived_state.top = top;
                        arrived_state.bottom = bottom;
                    }
                });

                set_internal_y.set(scroll_top);
            }
        };

        let on_scroll_handler = {
            let on_scroll = Rc::clone(&options.on_scroll);

            move |e: web_sys::Event| {
                let target: web_sys::Element = event_target(&e);

                set_arrived_state(target);
                set_is_scrolling.set(true);

                on_scroll_end_debounced.clone()(e.clone());
                on_scroll.clone()(e);
            }
        };

        let target = Signal::derive(move || {
            let element = signal.get();
            element.map(|element| {
                SendWrapper::new(element.take().unchecked_into::<web_sys::EventTarget>())
            })
        });

        if throttle >= 0.0 {
            use send_wrapper::SendWrapper;

            let throttled_scroll_handler = use_throttle_fn_with_arg_and_options(
                on_scroll_handler.clone(),
                throttle,
                ThrottleOptions {
                    trailing: true,
                    leading: false,
                },
            );

            let handler = move |e: web_sys::Event| {
                throttled_scroll_handler.clone()(e);
            };

            let _ = use_event_listener_with_options::<
                _,
                Signal<Option<SendWrapper<web_sys::EventTarget>>>,
                _,
                _,
            >(target, ev::scroll, handler, options.event_listener_options);
        } else {
            let _ = use_event_listener_with_options::<
                _,
                Signal<Option<SendWrapper<web_sys::EventTarget>>>,
                _,
                _,
            >(
                target,
                ev::scroll,
                on_scroll_handler,
                options.event_listener_options,
            );
        }

        let _ = use_event_listener_with_options::<
            _,
            Signal<Option<SendWrapper<web_sys::EventTarget>>>,
            _,
            _,
        >(
            target,
            scrollend,
            on_scroll_end,
            options.event_listener_options,
        );

        measure = sendwrap_fn!(move || {
            if let Some(el) = signal.try_get_untracked().flatten() {
                set_arrived_state(el.take());
            }
        });
    }

    UseScrollReturn {
        x: internal_x.into(),
        set_x,
        y: internal_y.into(),
        set_y,
        is_scrolling: is_scrolling.into(),
        arrived_state: arrived_state.into(),
        directions: directions.into(),
        measure,
    }
}