dioxus_provider/
platform.rs

1//! # Cross-Platform Abstractions
2//!
3//! This module provides unified abstractions for cross-platform functionality,
4//! eliminating code duplication between web and desktop targets.
5
6use std::time::Duration;
7
8// Cross-platform time imports
9#[cfg(not(target_family = "wasm"))]
10use std::time::{SystemTime, UNIX_EPOCH};
11#[cfg(target_family = "wasm")]
12use web_time::{SystemTime, UNIX_EPOCH};
13
14// Cross-platform sleep function
15#[cfg(not(target_family = "wasm"))]
16use tokio::time::sleep as tokio_sleep;
17#[cfg(target_family = "wasm")]
18use wasmtimer::tokio::sleep as wasm_sleep;
19
20// Cross-platform task spawning
21use dioxus_lib::prelude::spawn as dioxus_spawn;
22
23/// Cross-platform time utilities
24pub mod time {
25    use super::*;
26
27    /// Get current timestamp in seconds since Unix epoch
28    pub fn now_secs() -> u64 {
29        SystemTime::now()
30            .duration_since(UNIX_EPOCH)
31            .unwrap()
32            .as_secs()
33    }
34
35    /// Sleep for the specified duration
36    pub async fn sleep(duration: Duration) {
37        #[cfg(not(target_family = "wasm"))]
38        tokio_sleep(duration).await;
39        #[cfg(target_family = "wasm")]
40        wasm_sleep(duration).await;
41    }
42
43    /// Format timestamp as relative time (e.g., "5s ago", "2m ago")
44    pub fn format_relative_time(timestamp: u64) -> String {
45        let now = now_secs();
46        let diff = now.saturating_sub(timestamp);
47
48        if diff < 60 {
49            format!("{}s ago", diff)
50        } else if diff < 3600 {
51            format!("{}m ago", diff / 60)
52        } else {
53            format!("{}h ago", diff / 3600)
54        }
55    }
56}
57
58/// Cross-platform task management
59pub mod task {
60    use super::*;
61
62    /// Spawn an async task that works on both web and desktop
63    pub fn spawn<F>(future: F)
64    where
65        F: std::future::Future<Output = ()> + 'static,
66    {
67        dioxus_spawn(future);
68    }
69
70    /// Spawn a task with a name for debugging
71    pub fn spawn_named<F>(name: &'static str, future: F)
72    where
73        F: std::future::Future<Output = ()> + 'static,
74    {
75        dioxus_spawn(async move {
76            tracing::debug!("Starting task: {}", name);
77            future.await;
78            tracing::debug!("Completed task: {}", name);
79        });
80    }
81}
82
83/// Cross-platform configuration
84pub mod config {
85    use super::*;
86
87    /// Default cache cleanup interval
88    pub const DEFAULT_CLEANUP_INTERVAL: Duration = Duration::from_secs(30);
89
90    /// Default cache size limit
91    pub const DEFAULT_MAX_CACHE_SIZE: usize = 1000;
92
93    /// Default unused entry threshold
94    pub const DEFAULT_UNUSED_THRESHOLD: Duration = Duration::from_secs(300);
95}
96
97pub use config::*;
98/// Re-export commonly used platform functions
99pub use time::{format_relative_time, now_secs, sleep};