1use std::time::Duration;
4
5use dioxus::core::Task;
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::time::sleep;
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum RouteProgressState {
15 #[default]
17 Idle,
18 Pending,
20 Loading,
22 Complete,
24}
25
26impl RouteProgressState {
27 pub fn as_str(self) -> &'static str {
29 match self {
30 Self::Idle => "idle",
31 Self::Pending => "pending",
32 Self::Loading => "loading",
33 Self::Complete => "complete",
34 }
35 }
36}
37
38const ROUTE_PROGRESS_DELAY: Duration = Duration::from_millis(150);
39const ROUTE_PROGRESS_COMPLETE: Duration = Duration::from_millis(250);
40const ROUTE_PROGRESS_TRICKLE: Duration = Duration::from_millis(200);
41const ROUTE_PROGRESS_LABEL: &str = "Loading page";
42const ROUTE_PROGRESS_START: f64 = 0.08;
44const ROUTE_PROGRESS_MAX: f64 = 0.994;
46
47pub fn next_route_progress_value(value: f64) -> f64 {
51 if !value.is_finite() || value < ROUTE_PROGRESS_START {
52 return ROUTE_PROGRESS_START;
53 }
54
55 let step = if value < 0.2 {
56 0.1
57 } else if value < 0.5 {
58 0.04
59 } else if value < 0.8 {
60 0.02
61 } else {
62 0.005
63 };
64
65 (value + step).min(ROUTE_PROGRESS_MAX)
66}
67
68fn format_milliseconds(duration: Duration) -> String {
69 let millis = duration.as_secs_f64() * 1000.0;
70
71 format!("{millis}")
72}
73
74#[derive(Clone, Copy)]
76struct RouteProgressMachine {
77 state: Signal<RouteProgressState>,
78 value: Signal<f64>,
79 task: CopyValue<Option<Task>>,
80 delay: CopyValue<Duration>,
81}
82
83impl RouteProgressMachine {
84 fn cancel(self) {
85 let mut task = self.task;
86
87 if let Some(task) = task.write().take() {
88 task.cancel();
89 }
90 }
91
92 fn set(self, state: RouteProgressState, value: f64) {
93 let (mut state_signal, mut value_signal) = (self.state, self.value);
94 state_signal.set(state);
95 value_signal.set(value);
96 }
97
98 fn reset(self) {
99 self.cancel();
100 self.set(RouteProgressState::Idle, 0.0);
101 }
102
103 fn show(self) {
104 self.set(RouteProgressState::Loading, ROUTE_PROGRESS_START);
105
106 let mut value = self.value;
107 let task = spawn(async move {
108 loop {
109 sleep(ROUTE_PROGRESS_TRICKLE).await;
110 let next = next_route_progress_value(*value.peek());
111 value.set(next);
112 }
113 });
114 let mut slot = self.task;
115 slot.set(Some(task));
116 }
117
118 fn start(self) {
119 let state = *self.state.peek();
120
121 if matches!(
122 state,
123 RouteProgressState::Loading | RouteProgressState::Pending
124 ) {
125 return;
126 }
127
128 self.cancel();
129 let delay = *self.delay.peek();
130
131 if delay.is_zero() {
132 self.show();
133 return;
134 }
135
136 self.set(RouteProgressState::Pending, 0.0);
137 let task = spawn(async move {
138 sleep(delay).await;
139 self.show();
140 });
141 let mut slot = self.task;
142 slot.set(Some(task));
143 }
144
145 fn done(self) {
146 match *self.state.peek() {
147 RouteProgressState::Idle | RouteProgressState::Complete => {}
148 RouteProgressState::Pending => self.reset(),
149 RouteProgressState::Loading => {
150 self.cancel();
151 self.set(RouteProgressState::Complete, 1.0);
152 let task = spawn(async move {
153 sleep(ROUTE_PROGRESS_COMPLETE).await;
154 self.set(RouteProgressState::Idle, 0.0);
155 });
156 let mut slot = self.task;
157 slot.set(Some(task));
158 }
159 }
160 }
161}
162
163#[derive(Props, Clone, PartialEq)]
165pub struct RouteProgressProps {
166 pub active: bool,
168 pub delay: Option<Duration>,
171 #[props(into)]
173 pub label: Option<String>,
174 #[props(into)]
176 pub class: Option<String>,
177 #[props(extends = GlobalAttributes, extends = div)]
179 pub attributes: Vec<Attribute>,
180}
181
182#[component]
187pub fn RouteProgress(props: RouteProgressProps) -> Element {
188 let delay = props.delay.unwrap_or(ROUTE_PROGRESS_DELAY);
189 let label = props
190 .label
191 .as_deref()
192 .map(str::trim)
193 .filter(|value| !value.is_empty())
194 .unwrap_or(ROUTE_PROGRESS_LABEL)
195 .to_string();
196 let machine = use_hook(|| RouteProgressMachine {
197 state: Signal::new(RouteProgressState::Idle),
198 value: Signal::new(0.0),
199 task: CopyValue::new(None),
200 delay: CopyValue::new(delay),
201 });
202 let mut delay_slot = machine.delay;
203 delay_slot.set(delay);
204
205 use_effect(use_reactive((&props.active,), move |(active,)| {
206 if active {
207 machine.start();
208 } else {
209 machine.done();
210 }
211 }));
212
213 let state = *machine.state.read();
214 let value = *machine.value.read();
215 let visible = matches!(
216 state,
217 RouteProgressState::Loading | RouteProgressState::Complete
218 );
219 let class = compose([Some("ui-route-progress"), props.class.as_deref()]);
220 let style =
221 (state != RouteProgressState::Idle).then(|| format!("--ui-route-progress-value:{value}"));
222
223 rsx! {
224 div {
225 aria_busy: (state == RouteProgressState::Loading).then_some("true"),
226 aria_hidden: (!visible).then_some("true"),
227 aria_label: visible.then(|| label.clone()),
228 aria_valuemax: visible.then_some("100"),
229 aria_valuemin: visible.then_some("0"),
230 class,
231 "data-delay": format_milliseconds(delay),
232 "data-label": label.clone(),
233 "data-slot": "route-progress",
234 "data-state": state.as_str(),
235 "data-ui-owner": "dioxus",
236 "data-ui-route-progress": "",
237 role: visible.then_some("progressbar"),
238 style,
239 ..props.attributes,
240 div { class: "ui-route-progress__bar", "data-slot": "route-progress-bar" }
241 }
242 }
243}
244
245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
247pub enum ScrollProgressPosition {
248 #[default]
250 Top,
251 Bottom,
253}
254
255impl ScrollProgressPosition {
256 pub fn as_str(self) -> &'static str {
258 match self {
259 Self::Top => "top",
260 Self::Bottom => "bottom",
261 }
262 }
263}
264
265#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
267#[non_exhaustive]
268pub enum ScrollProgressTone {
269 #[default]
271 Brand,
272 Accent,
274 Success,
276 Warning,
278 Danger,
280 Ink,
282}
283
284impl ScrollProgressTone {
285 fn class(self) -> Option<&'static str> {
286 match self {
287 Self::Brand => None,
288 Self::Accent => Some("ui-scroll-progress--accent"),
289 Self::Success => Some("ui-scroll-progress--success"),
290 Self::Warning => Some("ui-scroll-progress--warning"),
291 Self::Danger => Some("ui-scroll-progress--danger"),
292 Self::Ink => Some("ui-scroll-progress--ink"),
293 }
294 }
295}
296
297pub fn scroll_progress_ratio(scroll_top: f64, scroll_height: i32, client_height: i32) -> f64 {
302 let range = f64::from(scroll_height.saturating_sub(client_height).max(1));
303 let ratio = scroll_top / range;
304
305 if ratio.is_finite() {
306 ratio.clamp(0.0, 1.0)
307 } else {
308 0.0
309 }
310}
311
312const SCROLL_PROGRESS_SCRIPT: &str = r"
316const targetId = await dioxus.recv();
317const doc = document;
318const view = window;
319const clamp = (ratio) => Math.min(1, Math.max(0, ratio));
320const measure = () => {
321 const scroller = doc.scrollingElement || doc.documentElement;
322 const height = scroller.clientHeight;
323 const target = targetId ? doc.getElementById(targetId) : null;
324 if (!target) return clamp(scroller.scrollTop / Math.max(1, scroller.scrollHeight - height));
325 const rect = target.getBoundingClientRect();
326 if (!rect.height) return 0;
327 if (rect.bottom <= height) return 1;
328 const padding = view.getComputedStyle(scroller).scrollPaddingTop || '';
329 let start = Number.parseFloat(padding) || 0;
330 if (padding.endsWith('%')) start *= height / 100;
331 return clamp((start - rect.top) / Math.max(1, rect.height - height + start));
332};
333let frame = 0;
334const update = () => { frame = 0; dioxus.send(measure()); };
335const schedule = () => { if (!frame) frame = view.requestAnimationFrame(update); };
336view.addEventListener('scroll', schedule, { passive: true });
337view.addEventListener('resize', schedule, { passive: true });
338schedule();
339await dioxus.recv();
340if (frame) view.cancelAnimationFrame(frame);
341view.removeEventListener('scroll', schedule);
342view.removeEventListener('resize', schedule);
343";
344
345#[derive(Props, Clone, PartialEq)]
347pub struct ScrollProgressProps {
348 #[props(default)]
350 pub position: ScrollProgressPosition,
351 #[props(into)]
353 pub target_id: Option<String>,
354 #[props(default)]
356 pub tone: ScrollProgressTone,
357 pub value: Option<f64>,
360 #[props(default = "Reading progress".to_string(), into)]
362 pub aria_label: String,
363 #[props(into)]
365 pub class: Option<String>,
366 #[props(extends = GlobalAttributes, extends = div)]
368 pub attributes: Vec<Attribute>,
369}
370
371#[component]
376pub fn ScrollProgress(props: ScrollProgressProps) -> Element {
377 let mut measured = use_signal(|| 0.0_f64);
378 let mut ready = use_signal(|| false);
379 let tracking = props.value.is_none();
380 let target = props.target_id.clone().unwrap_or_default();
381
382 let mut tracker = use_hook(|| CopyValue::new(None::<Task>));
383
384 use_effect(use_reactive(
385 (&tracking, &target),
386 move |(tracking, target)| {
387 if let Some(task) = tracker.write().take() {
388 task.cancel();
389 }
390
391 if !tracking {
392 return;
393 }
394
395 ready.set(false);
396
397 let task = spawn(async move {
398 let mut eval = document::eval(SCROLL_PROGRESS_SCRIPT);
399
400 if eval.send(target).is_err() {
401 ready.set(true);
402 return;
403 }
404
405 let _guard = ScrollProgressGuard(eval);
407
408 while let Ok(ratio) = eval.recv::<f64>().await {
409 if ratio.is_finite() {
410 measured.set(ratio.clamp(0.0, 1.0));
411 ready.set(true);
412 }
413 }
414
415 ready.set(true);
417 });
418 tracker.set(Some(task));
419 },
420 ));
421
422 let ratio = props
423 .value
424 .filter(|value| value.is_finite())
425 .map_or_else(|| *measured.read(), |value| value.clamp(0.0, 1.0));
426 let percentage = (ratio * 100.0).round();
427 let class = compose([
428 Some("ui-scroll-progress"),
429 (props.position == ScrollProgressPosition::Bottom).then_some("ui-scroll-progress--bottom"),
430 props.tone.class(),
431 props.class.as_deref(),
432 ]);
433 let bar_style = (ratio > 0.0).then(|| format!("transform:scaleX({ratio})"));
434
435 rsx! {
436 div {
437 aria_label: props.aria_label,
438 aria_valuemax: "100",
439 aria_valuemin: "0",
440 aria_valuenow: "{percentage}",
441 class,
442 "data-position": props.position.as_str(),
443 "data-ui-scroll-progress": "true",
444 "data-ui-scroll-progress-pending": (tracking && !ready()).then_some("true"),
445 "data-ui-scroll-progress-target": props.target_id,
446 role: "progressbar",
447 ..props.attributes,
448 span { class: "ui-scroll-progress__bar", style: bar_style }
449 }
450 }
451}
452
453struct ScrollProgressGuard(document::Eval);
455
456impl Drop for ScrollProgressGuard {
457 fn drop(&mut self) {
458 let _ = self.0.send(true);
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use std::time::Duration;
465
466 use super::{format_milliseconds, next_route_progress_value, scroll_progress_ratio};
467
468 #[test]
469 fn route_progress_trickles_and_caps() {
470 assert!((next_route_progress_value(0.0) - 0.08).abs() < f64::EPSILON);
471 assert!((next_route_progress_value(f64::NAN) - 0.08).abs() < f64::EPSILON);
472 assert!((next_route_progress_value(0.1) - 0.2).abs() < 1e-9);
473 assert!((next_route_progress_value(0.3) - 0.34).abs() < 1e-9);
474 assert!((next_route_progress_value(0.6) - 0.62).abs() < 1e-9);
475 assert!((next_route_progress_value(0.9) - 0.905).abs() < 1e-9);
476 assert!((next_route_progress_value(0.993) - 0.994).abs() < 1e-9);
477 let mut value = 0.0;
478 for _ in 0..1_000 {
479 value = next_route_progress_value(value);
480 }
481 assert!(value <= 0.994);
482 }
483
484 #[test]
485 fn route_progress_delay_formats_like_javascript() {
486 assert_eq!(format_milliseconds(Duration::from_millis(150)), "150");
487 assert_eq!(format_milliseconds(Duration::ZERO), "0");
488 assert_eq!(format_milliseconds(Duration::from_micros(1500)), "1.5");
489 }
490
491 #[test]
492 fn scroll_ratio_clamps() {
493 assert!((scroll_progress_ratio(0.0, 2000, 1000)).abs() < f64::EPSILON);
494 assert!((scroll_progress_ratio(500.0, 2000, 1000) - 0.5).abs() < f64::EPSILON);
495 assert!((scroll_progress_ratio(5000.0, 2000, 1000) - 1.0).abs() < f64::EPSILON);
496 assert!((scroll_progress_ratio(-10.0, 2000, 1000)).abs() < f64::EPSILON);
497 assert!((scroll_progress_ratio(10.0, 500, 1000) - 1.0).abs() < f64::EPSILON);
498 assert!((scroll_progress_ratio(f64::NAN, 500, 1000)).abs() < f64::EPSILON);
499 }
500}