lumen_dioxus/data/timer/
mod.rs1mod model;
4
5pub use model::*;
6
7use std::time::Duration;
8
9use dioxus::prelude::*;
10
11use crate::class::compose;
12
13const MAX_EPOCH_MS: i64 = 8_640_000_000_000_000;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum TimerInstant {
20 Text(String),
24 Millis(i64),
26}
27
28impl TimerInstant {
29 pub fn to_millis(&self) -> Option<i64> {
31 match self {
32 Self::Text(text) => parse_timer_instant(text),
33 Self::Millis(millis) => {
34 Some(*millis).filter(|ms| (-MAX_EPOCH_MS..=MAX_EPOCH_MS).contains(ms))
35 }
36 }
37 }
38}
39
40impl Default for TimerInstant {
41 fn default() -> Self {
43 Self::Text(String::new())
44 }
45}
46
47impl From<&str> for TimerInstant {
48 fn from(value: &str) -> Self {
49 Self::Text(value.to_string())
50 }
51}
52
53impl From<String> for TimerInstant {
54 fn from(value: String) -> Self {
55 Self::Text(value)
56 }
57}
58
59impl From<i64> for TimerInstant {
60 fn from(value: i64) -> Self {
61 Self::Millis(value)
62 }
63}
64
65impl From<std::time::SystemTime> for TimerInstant {
66 fn from(value: std::time::SystemTime) -> Self {
67 let millis = match value.duration_since(std::time::UNIX_EPOCH) {
68 Ok(after) => i64::try_from(after.as_millis()).unwrap_or(i64::MAX),
69 Err(before) => i64::try_from(before.duration().as_millis()).map_or(i64::MIN, |ms| -ms),
70 };
71
72 Self::Millis(millis)
73 }
74}
75
76#[cfg_attr(
78 not(target_family = "wasm"),
79 allow(
80 clippy::unnecessary_wraps,
81 reason = "the web build has no synchronous clock"
82 )
83)]
84fn now_sync() -> Option<i64> {
85 #[cfg(not(target_family = "wasm"))]
86 {
87 Some(
88 TimerInstant::from(std::time::SystemTime::now())
89 .to_millis()
90 .unwrap_or(0),
91 )
92 }
93
94 #[cfg(target_family = "wasm")]
95 {
96 None
97 }
98}
99
100#[cfg_attr(
103 not(target_family = "wasm"),
104 allow(clippy::unused_async, reason = "only the web build awaits the clock")
105)]
106async fn now_async() -> Option<i64> {
107 #[cfg(not(target_family = "wasm"))]
108 {
109 now_sync()
110 }
111
112 #[cfg(target_family = "wasm")]
113 {
114 let value = document::eval("return Date.now()").await.ok()?;
115
116 value.as_f64().and_then(|ms| {
117 if ms.is_finite() {
118 format!("{ms:.0}").parse::<i64>().ok()
119 } else {
120 None
121 }
122 })
123 }
124}
125
126#[derive(Props, Clone, PartialEq)]
128pub struct TimerProps {
129 #[props(default)]
131 pub mode: TimerMode,
132 #[props(default, into)]
134 pub to: TimerInstant,
135 #[props(default, into)]
137 pub from: TimerInstant,
138 #[props(default)]
140 pub format: TimerFormat,
141 #[props(default)]
143 pub announce: TimerAnnounce,
144 #[props(into)]
146 pub complete_label: Option<String>,
147 #[props(default)]
150 pub units: Vec<TimerUnit>,
151 pub now: Option<i64>,
154 pub on_complete: Option<EventHandler<()>>,
156 #[props(into)]
158 pub class: Option<String>,
159 #[props(extends = GlobalAttributes, extends = span)]
161 pub attributes: Vec<Attribute>,
162}
163
164#[component]
169pub fn Timer(props: TimerProps) -> Element {
170 let instant = match props.mode {
171 TimerMode::Countdown => props.to.to_millis(),
172 TimerMode::Elapsed => props.from.to_millis(),
173 };
174 let config = resolve_timer_config(
175 props.mode,
176 props.format,
177 props.announce,
178 props.complete_label.as_deref(),
179 instant,
180 &props.units,
181 );
182 let initial = props.now;
183 let mut clock = use_signal(|| initial.or_else(now_sync));
184 let mut announcement = use_signal(String::new);
185 let mut on_complete = use_signal(|| props.on_complete);
186 let mut task = use_signal(|| None::<dioxus::core::Task>);
187
188 if *on_complete.peek() != props.on_complete {
189 on_complete.set(props.on_complete);
190 }
191
192 use_effect(use_reactive((&config,), move |(config,)| {
193 let start = *clock.peek();
194
195 if let Some(previous) = task.write().take() {
196 previous.cancel();
197 }
198
199 let ticker = spawn(async move {
200 let mut previous = start.map(|now| timer_snapshot(&config, now));
201
202 loop {
203 let Some(now) = now_async().await else {
204 break;
205 };
206 let next = timer_snapshot(&config, now);
207
208 clock.set(Some(now));
209
210 if let Some(message) = timer_announcement(&config, previous.as_ref(), &next) {
211 announcement.set(message);
212 }
213
214 if is_timer_completion(previous.as_ref(), &next)
215 && let Some(handler) = *on_complete.peek()
216 {
217 handler.call(());
218 }
219
220 let running = next.state == TimerState::Running;
221 previous = Some(next);
222
223 let (true, Some(instant)) = (running, config.instant) else {
224 break;
225 };
226 let now = now_async().await.unwrap_or(now);
227
228 crate::time::sleep(Duration::from_millis(timer_tick_delay(instant, now))).await;
229 }
230 });
231
232 task.set(Some(ticker));
233 }));
234
235 let snapshot = match *clock.read() {
236 Some(now) => timer_snapshot(&config, now),
237 None => timer_snapshot(
238 &TimerConfig {
239 instant: None,
240 ..config.clone()
241 },
242 0,
243 ),
244 };
245 let class = compose([Some("ui-timer"), props.class.as_deref()]);
246
247 rsx! {
248 span {
249 aria_live: "off",
250 class,
251 "data-slot": "timer",
252 "data-state": snapshot.state.as_str(),
253 "data-ui-owner": "dioxus",
254 "data-ui-timer": "true",
255 role: "timer",
256 ..props.attributes,
257 time {
258 class: "ui-timer__value",
259 "data-slot": "timer-value",
260 datetime: snapshot.date_time,
261 "{snapshot.text}"
262 }
263 span {
264 aria_atomic: "true",
265 aria_live: "polite",
266 class: "ui-sr-only",
267 "data-slot": "timer-announcer",
268 "{announcement}"
269 }
270 }
271 }
272}