|
| 1 | +use dioxus::prelude::*; |
| 2 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
| 3 | + |
| 4 | +/// Scroll metrics. |
| 5 | +#[derive(serde::Deserialize, Clone, Debug)] |
| 6 | +pub struct ScrollMetrics { |
| 7 | + /// Current scroll position from top: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop |
| 8 | + pub scroll_top: f64, |
| 9 | + /// Current scroll position from left: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft |
| 10 | + pub scroll_left: f64, |
| 11 | + |
| 12 | + /// Viewport height: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight |
| 13 | + pub client_height: f64, |
| 14 | + /// Viewport width: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth |
| 15 | + pub client_width: f64, |
| 16 | + |
| 17 | + /// Content height: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight |
| 18 | + pub scroll_height: f64, |
| 19 | + /// Content width: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth |
| 20 | + pub scroll_width: f64, |
| 21 | +} |
| 22 | + |
| 23 | +// Static counter to generate unique IDs for each scroll tracker instance |
| 24 | +static SCROLL_TRACKER_COUNTER: AtomicUsize = AtomicUsize::new(0); |
| 25 | + |
| 26 | +/// Creates a signal that tracks root scrolling. |
| 27 | +/// ```rust |
| 28 | +/// use dioxus::{logger::tracing::{info, Level}, prelude::*}; |
| 29 | +/// use dioxus_sdk::utils::scroll::use_root_scroll; |
| 30 | +/// |
| 31 | +/// fn main() { |
| 32 | +/// dioxus::logger::init(Level::TRACE).unwrap(); |
| 33 | +/// launch(App); |
| 34 | +/// } |
| 35 | +/// |
| 36 | +/// #[component] |
| 37 | +/// fn App() -> Element { |
| 38 | +/// let random_text = "This is some random repeating text. ".repeat(1000); |
| 39 | +/// |
| 40 | +/// let scroll_metrics = use_root_scroll(); |
| 41 | +/// use_effect(move || { |
| 42 | +/// let scroll_metrics = scroll_metrics(); |
| 43 | +/// let distance_from_bottom = scroll_metrics.scroll_height - (scroll_metrics.scroll_top + scroll_metrics.client_height); |
| 44 | +/// info!("Distance from bottom: {}", distance_from_bottom); |
| 45 | +/// let scroll_percentage = (scroll_metrics.scroll_top + scroll_metrics.client_height) / scroll_metrics.scroll_height; |
| 46 | +/// info!("Scroll percentage: {}", scroll_percentage); |
| 47 | +/// }); |
| 48 | +/// |
| 49 | +/// rsx! { |
| 50 | +/// p { "{random_text}" } |
| 51 | +/// } |
| 52 | +/// } |
| 53 | +/// ``` |
| 54 | +pub fn use_root_scroll() -> Signal<ScrollMetrics> { |
| 55 | + let callback_name = use_hook(|| { |
| 56 | + let instance_id = SCROLL_TRACKER_COUNTER.fetch_add(1, Ordering::SeqCst); |
| 57 | + format!("scrollCallback_{}", instance_id) |
| 58 | + }); |
| 59 | + |
| 60 | + let mut scroll_metrics = use_signal(|| ScrollMetrics { |
| 61 | + scroll_top: 0.0, |
| 62 | + scroll_left: 0.0, |
| 63 | + client_height: 0.0, |
| 64 | + client_width: 0.0, |
| 65 | + scroll_height: 0.0, |
| 66 | + scroll_width: 0.0, |
| 67 | + }); |
| 68 | + |
| 69 | + use_future({ |
| 70 | + to_owned![callback_name]; |
| 71 | + move || { |
| 72 | + to_owned![callback_name]; |
| 73 | + async move { |
| 74 | + let js_code = format!( |
| 75 | + r#" |
| 76 | + function {callback_name}() {{ |
| 77 | + const doc = document.documentElement; |
| 78 | + const scrollTop = window.scrollY || doc.scrollTop; |
| 79 | + const scrollLeft = window.scrollX || doc.scrollLeft; |
| 80 | + const viewportHeight = window.innerHeight; |
| 81 | + const viewportWidth = window.innerWidth; |
| 82 | + const contentHeight = doc.scrollHeight; |
| 83 | + const contentWidth = doc.scrollWidth; |
| 84 | +
|
| 85 | + dioxus.send({{ |
| 86 | + scroll_top: scrollTop, |
| 87 | + scroll_left: scrollLeft, |
| 88 | + client_height: viewportHeight, |
| 89 | + client_width: viewportWidth, |
| 90 | + scroll_height: contentHeight, |
| 91 | + scroll_width: contentWidth, |
| 92 | + }}); |
| 93 | + }} |
| 94 | +
|
| 95 | + {callback_name}(); |
| 96 | +
|
| 97 | + window['{callback_name}'] = {callback_name}; |
| 98 | + window.addEventListener('scroll', window['{callback_name}']); |
| 99 | + window.addEventListener('resize', window['{callback_name}']); |
| 100 | + "#, |
| 101 | + ); |
| 102 | + |
| 103 | + let mut eval = document::eval(&js_code); |
| 104 | + |
| 105 | + loop { |
| 106 | + match eval.recv::<ScrollMetrics>().await { |
| 107 | + Ok(metrics) => { |
| 108 | + dioxus::logger::tracing::trace!("Got scroll metrics {:?}", metrics); |
| 109 | + scroll_metrics.set(metrics); |
| 110 | + } |
| 111 | + Err(error) => dioxus::logger::tracing::error!( |
| 112 | + "Error receiving scroll metrics: {:?}", |
| 113 | + error |
| 114 | + ), |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + }); |
| 120 | + |
| 121 | + use_drop(move || { |
| 122 | + let cleanup_code = format!( |
| 123 | + r#" |
| 124 | + window.removeEventListener('scroll', window['{callback_name}']); |
| 125 | + window.removeEventListener('resize', window['{callback_name}']); |
| 126 | + delete window['{callback_name}']; |
| 127 | + "#, |
| 128 | + ); |
| 129 | + let _ = document::eval(&cleanup_code); |
| 130 | + }); |
| 131 | + |
| 132 | + scroll_metrics |
| 133 | +} |
0 commit comments