use std::time::Duration;
use dioxus::core::Task;
use dioxus::prelude::*;
use crate::class::compose;
use crate::time::sleep;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RouteProgressState {
#[default]
Idle,
Pending,
Loading,
Complete,
}
impl RouteProgressState {
pub fn as_str(self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Pending => "pending",
Self::Loading => "loading",
Self::Complete => "complete",
}
}
}
const ROUTE_PROGRESS_DELAY: Duration = Duration::from_millis(150);
const ROUTE_PROGRESS_COMPLETE: Duration = Duration::from_millis(250);
const ROUTE_PROGRESS_TRICKLE: Duration = Duration::from_millis(200);
const ROUTE_PROGRESS_LABEL: &str = "Loading page";
const ROUTE_PROGRESS_START: f64 = 0.08;
const ROUTE_PROGRESS_MAX: f64 = 0.994;
pub fn next_route_progress_value(value: f64) -> f64 {
if !value.is_finite() || value < ROUTE_PROGRESS_START {
return ROUTE_PROGRESS_START;
}
let step = if value < 0.2 {
0.1
} else if value < 0.5 {
0.04
} else if value < 0.8 {
0.02
} else {
0.005
};
(value + step).min(ROUTE_PROGRESS_MAX)
}
fn format_milliseconds(duration: Duration) -> String {
let millis = duration.as_secs_f64() * 1000.0;
format!("{millis}")
}
#[derive(Clone, Copy)]
struct RouteProgressMachine {
state: Signal<RouteProgressState>,
value: Signal<f64>,
task: CopyValue<Option<Task>>,
delay: CopyValue<Duration>,
}
impl RouteProgressMachine {
fn cancel(self) {
let mut task = self.task;
if let Some(task) = task.write().take() {
task.cancel();
}
}
fn set(self, state: RouteProgressState, value: f64) {
let (mut state_signal, mut value_signal) = (self.state, self.value);
state_signal.set(state);
value_signal.set(value);
}
fn reset(self) {
self.cancel();
self.set(RouteProgressState::Idle, 0.0);
}
fn show(self) {
self.set(RouteProgressState::Loading, ROUTE_PROGRESS_START);
let mut value = self.value;
let task = spawn(async move {
loop {
sleep(ROUTE_PROGRESS_TRICKLE).await;
let next = next_route_progress_value(*value.peek());
value.set(next);
}
});
let mut slot = self.task;
slot.set(Some(task));
}
fn start(self) {
let state = *self.state.peek();
if matches!(
state,
RouteProgressState::Loading | RouteProgressState::Pending
) {
return;
}
self.cancel();
let delay = *self.delay.peek();
if delay.is_zero() {
self.show();
return;
}
self.set(RouteProgressState::Pending, 0.0);
let task = spawn(async move {
sleep(delay).await;
self.show();
});
let mut slot = self.task;
slot.set(Some(task));
}
fn done(self) {
match *self.state.peek() {
RouteProgressState::Idle | RouteProgressState::Complete => {}
RouteProgressState::Pending => self.reset(),
RouteProgressState::Loading => {
self.cancel();
self.set(RouteProgressState::Complete, 1.0);
let task = spawn(async move {
sleep(ROUTE_PROGRESS_COMPLETE).await;
self.set(RouteProgressState::Idle, 0.0);
});
let mut slot = self.task;
slot.set(Some(task));
}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct RouteProgressProps {
pub active: bool,
pub delay: Option<Duration>,
#[props(into)]
pub label: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn RouteProgress(props: RouteProgressProps) -> Element {
let delay = props.delay.unwrap_or(ROUTE_PROGRESS_DELAY);
let label = props
.label
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or(ROUTE_PROGRESS_LABEL)
.to_string();
let machine = use_hook(|| RouteProgressMachine {
state: Signal::new(RouteProgressState::Idle),
value: Signal::new(0.0),
task: CopyValue::new(None),
delay: CopyValue::new(delay),
});
let mut delay_slot = machine.delay;
delay_slot.set(delay);
use_effect(use_reactive((&props.active,), move |(active,)| {
if active {
machine.start();
} else {
machine.done();
}
}));
let state = *machine.state.read();
let value = *machine.value.read();
let visible = matches!(
state,
RouteProgressState::Loading | RouteProgressState::Complete
);
let class = compose([Some("ui-route-progress"), props.class.as_deref()]);
let style =
(state != RouteProgressState::Idle).then(|| format!("--ui-route-progress-value:{value}"));
rsx! {
div {
aria_busy: (state == RouteProgressState::Loading).then_some("true"),
aria_hidden: (!visible).then_some("true"),
aria_label: visible.then(|| label.clone()),
aria_valuemax: visible.then_some("100"),
aria_valuemin: visible.then_some("0"),
class,
"data-delay": format_milliseconds(delay),
"data-label": label.clone(),
"data-slot": "route-progress",
"data-state": state.as_str(),
"data-ui-owner": "dioxus",
"data-ui-route-progress": "",
role: visible.then_some("progressbar"),
style,
..props.attributes,
div { class: "ui-route-progress__bar", "data-slot": "route-progress-bar" }
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollProgressPosition {
#[default]
Top,
Bottom,
}
impl ScrollProgressPosition {
pub fn as_str(self) -> &'static str {
match self {
Self::Top => "top",
Self::Bottom => "bottom",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScrollProgressTone {
#[default]
Brand,
Accent,
Success,
Warning,
Danger,
Ink,
}
impl ScrollProgressTone {
fn class(self) -> Option<&'static str> {
match self {
Self::Brand => None,
Self::Accent => Some("ui-scroll-progress--accent"),
Self::Success => Some("ui-scroll-progress--success"),
Self::Warning => Some("ui-scroll-progress--warning"),
Self::Danger => Some("ui-scroll-progress--danger"),
Self::Ink => Some("ui-scroll-progress--ink"),
}
}
}
pub fn scroll_progress_ratio(scroll_top: f64, scroll_height: i32, client_height: i32) -> f64 {
let range = f64::from(scroll_height.saturating_sub(client_height).max(1));
let ratio = scroll_top / range;
if ratio.is_finite() {
ratio.clamp(0.0, 1.0)
} else {
0.0
}
}
const SCROLL_PROGRESS_SCRIPT: &str = r"
const targetId = await dioxus.recv();
const doc = document;
const view = window;
const clamp = (ratio) => Math.min(1, Math.max(0, ratio));
const measure = () => {
const scroller = doc.scrollingElement || doc.documentElement;
const height = scroller.clientHeight;
const target = targetId ? doc.getElementById(targetId) : null;
if (!target) return clamp(scroller.scrollTop / Math.max(1, scroller.scrollHeight - height));
const rect = target.getBoundingClientRect();
if (!rect.height) return 0;
if (rect.bottom <= height) return 1;
const padding = view.getComputedStyle(scroller).scrollPaddingTop || '';
let start = Number.parseFloat(padding) || 0;
if (padding.endsWith('%')) start *= height / 100;
return clamp((start - rect.top) / Math.max(1, rect.height - height + start));
};
let frame = 0;
const update = () => { frame = 0; dioxus.send(measure()); };
const schedule = () => { if (!frame) frame = view.requestAnimationFrame(update); };
view.addEventListener('scroll', schedule, { passive: true });
view.addEventListener('resize', schedule, { passive: true });
schedule();
await dioxus.recv();
if (frame) view.cancelAnimationFrame(frame);
view.removeEventListener('scroll', schedule);
view.removeEventListener('resize', schedule);
";
#[derive(Props, Clone, PartialEq)]
pub struct ScrollProgressProps {
#[props(default)]
pub position: ScrollProgressPosition,
#[props(into)]
pub target_id: Option<String>,
#[props(default)]
pub tone: ScrollProgressTone,
pub value: Option<f64>,
#[props(default = "Reading progress".to_string(), into)]
pub aria_label: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn ScrollProgress(props: ScrollProgressProps) -> Element {
let mut measured = use_signal(|| 0.0_f64);
let mut ready = use_signal(|| false);
let tracking = props.value.is_none();
let target = props.target_id.clone().unwrap_or_default();
let mut tracker = use_hook(|| CopyValue::new(None::<Task>));
use_effect(use_reactive(
(&tracking, &target),
move |(tracking, target)| {
if let Some(task) = tracker.write().take() {
task.cancel();
}
if !tracking {
return;
}
ready.set(false);
let task = spawn(async move {
let mut eval = document::eval(SCROLL_PROGRESS_SCRIPT);
if eval.send(target).is_err() {
ready.set(true);
return;
}
let _guard = ScrollProgressGuard(eval);
while let Ok(ratio) = eval.recv::<f64>().await {
if ratio.is_finite() {
measured.set(ratio.clamp(0.0, 1.0));
ready.set(true);
}
}
ready.set(true);
});
tracker.set(Some(task));
},
));
let ratio = props
.value
.filter(|value| value.is_finite())
.map_or_else(|| *measured.read(), |value| value.clamp(0.0, 1.0));
let percentage = (ratio * 100.0).round();
let class = compose([
Some("ui-scroll-progress"),
(props.position == ScrollProgressPosition::Bottom).then_some("ui-scroll-progress--bottom"),
props.tone.class(),
props.class.as_deref(),
]);
let bar_style = (ratio > 0.0).then(|| format!("transform:scaleX({ratio})"));
rsx! {
div {
aria_label: props.aria_label,
aria_valuemax: "100",
aria_valuemin: "0",
aria_valuenow: "{percentage}",
class,
"data-position": props.position.as_str(),
"data-ui-scroll-progress": "true",
"data-ui-scroll-progress-pending": (tracking && !ready()).then_some("true"),
"data-ui-scroll-progress-target": props.target_id,
role: "progressbar",
..props.attributes,
span { class: "ui-scroll-progress__bar", style: bar_style }
}
}
}
struct ScrollProgressGuard(document::Eval);
impl Drop for ScrollProgressGuard {
fn drop(&mut self) {
let _ = self.0.send(true);
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{format_milliseconds, next_route_progress_value, scroll_progress_ratio};
#[test]
fn route_progress_trickles_and_caps() {
assert!((next_route_progress_value(0.0) - 0.08).abs() < f64::EPSILON);
assert!((next_route_progress_value(f64::NAN) - 0.08).abs() < f64::EPSILON);
assert!((next_route_progress_value(0.1) - 0.2).abs() < 1e-9);
assert!((next_route_progress_value(0.3) - 0.34).abs() < 1e-9);
assert!((next_route_progress_value(0.6) - 0.62).abs() < 1e-9);
assert!((next_route_progress_value(0.9) - 0.905).abs() < 1e-9);
assert!((next_route_progress_value(0.993) - 0.994).abs() < 1e-9);
let mut value = 0.0;
for _ in 0..1_000 {
value = next_route_progress_value(value);
}
assert!(value <= 0.994);
}
#[test]
fn route_progress_delay_formats_like_javascript() {
assert_eq!(format_milliseconds(Duration::from_millis(150)), "150");
assert_eq!(format_milliseconds(Duration::ZERO), "0");
assert_eq!(format_milliseconds(Duration::from_micros(1500)), "1.5");
}
#[test]
fn scroll_ratio_clamps() {
assert!((scroll_progress_ratio(0.0, 2000, 1000)).abs() < f64::EPSILON);
assert!((scroll_progress_ratio(500.0, 2000, 1000) - 0.5).abs() < f64::EPSILON);
assert!((scroll_progress_ratio(5000.0, 2000, 1000) - 1.0).abs() < f64::EPSILON);
assert!((scroll_progress_ratio(-10.0, 2000, 1000)).abs() < f64::EPSILON);
assert!((scroll_progress_ratio(10.0, 500, 1000) - 1.0).abs() < f64::EPSILON);
assert!((scroll_progress_ratio(f64::NAN, 500, 1000)).abs() < f64::EPSILON);
}
}