lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Portable timers for components that wait, such as toasts, timers, and rolling text.

use std::time::Duration;

/// The longest single wait. Browsers fire `setTimeout` immediately above `i32::MAX` milliseconds
/// (about 24.8 days), and gloo-timers rejects delays above `u32::MAX`, so longer waits run in
/// chunks. Tokio also panics when an instant overflows, which chunking avoids.
const MAX_CHUNK: Duration = Duration::from_millis(2_147_483_647);

/// The chunks a wait is split into: full chunks first, then the remainder. A zero wait is one
/// zero step, so `sleep(Duration::ZERO)` still yields to the event loop once, which components
/// use to let a render reach the screen before moving focus.
fn chunks(duration: Duration) -> impl Iterator<Item = Duration> {
    let mut remaining = duration;
    let mut first = true;

    std::iter::from_fn(move || {
        if remaining.is_zero() && !first {
            return None;
        }

        first = false;
        let step = remaining.min(MAX_CHUNK);
        remaining -= step;
        Some(step)
    })
}

/// Waits for `duration` on any Dioxus renderer.
///
/// Uses Tokio on desktop, mobile, and Dioxus Native, which run inside a Tokio runtime, and
/// browser timers on the web. A zero wait still yields once, like `setTimeout(0)`. Waits longer
/// than about 24.8 days run in several steps, so they neither fire early nor overflow.
pub async fn sleep(duration: Duration) {
    for step in chunks(duration) {
        #[cfg(not(target_family = "wasm"))]
        tokio::time::sleep(step).await;

        #[cfg(target_family = "wasm")]
        gloo_timers::future::sleep(step).await;
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{MAX_CHUNK, chunks};

    #[test]
    fn long_waits_split_below_the_browser_timer_limit() {
        let steps: Vec<Duration> = chunks(MAX_CHUNK * 2 + Duration::from_millis(5)).collect();

        assert_eq!(steps, vec![MAX_CHUNK, MAX_CHUNK, Duration::from_millis(5)]);
        assert_eq!(
            chunks(Duration::ZERO).collect::<Vec<_>>(),
            vec![Duration::ZERO]
        );
        assert_eq!(
            chunks(Duration::from_millis(250)).collect::<Vec<_>>(),
            vec![Duration::from_millis(250)]
        );
    }

    #[test]
    fn the_longest_duration_stays_within_the_chunk_limit() {
        assert!(
            chunks(Duration::MAX)
                .take(1_000)
                .all(|step| step == MAX_CHUNK)
        );
    }
}