ppoppo_clock/wasm.rs
1// WASM arm: WasmClock + WasmTimer.
2//
3// WasmClock sources "now" from `js_sys::Date::now()` (f64 epoch millis) — the
4// only clock readout the browser offers synchronously. All zone math happens
5// in jiff against the bundled tzdb (identical to the native arm; RFC
6// RFC_202607130309_jiff-migration D5 overturned the zero-bundle Intl design).
7// The one remaining Intl call is `browser_local_tz()` — a *name* probe
8// (`resolvedOptions().timeZone`), resolved against jiff's tzdb.
9//
10// WasmTimer uses `Window.setTimeout` wired through a `futures::channel::oneshot`
11// so that the returned `BoxFuture` is `Send` (the JsFuture itself is !Send, but
12// awaiting a oneshot::Receiver is Send).
13
14use crate::{Clock, Timer};
15use futures::channel::oneshot;
16use futures::future::BoxFuture;
17use jiff::tz::TimeZone;
18use jiff::Timestamp;
19use std::time::Duration;
20use wasm_bindgen::JsCast;
21
22pub struct WasmClock;
23
24impl Clock for WasmClock {
25 fn now(&self) -> Timestamp {
26 let ms = js_sys::Date::now(); // f64 millis since epoch
27 Timestamp::from_millisecond(ms as i64).unwrap_or(Timestamp::UNIX_EPOCH)
28 }
29}
30
31/// Read the browser's local IANA timezone name via
32/// `Intl.DateTimeFormat.resolvedOptions()` and resolve it in jiff's tzdb.
33///
34/// Falls back to `TimeZone::UTC` if the browser returns an unrecognised name.
35/// Call once at app startup and provide the result via Leptos context.
36pub fn browser_local_tz() -> TimeZone {
37 use js_sys::{Array, Intl, Object, Reflect};
38 use wasm_bindgen::JsValue;
39
40 let fmt = Intl::DateTimeFormat::new(&Array::new(), &Object::new());
41 let resolved = fmt.resolved_options();
42 Reflect::get(&resolved, &JsValue::from_str("timeZone"))
43 .ok()
44 .and_then(|v| v.as_string())
45 .and_then(|s| TimeZone::get(&s).ok())
46 .unwrap_or(TimeZone::UTC)
47}
48
49pub struct WasmTimer;
50
51impl Timer for WasmTimer {
52 fn sleep(&self, dur: Duration) -> BoxFuture<'static, ()> {
53 let ms = dur.as_millis().min(i32::MAX as u128) as i32;
54 let (tx, rx) = oneshot::channel::<()>();
55
56 // Wire setTimeout → oneshot sender. The closure captures `tx` (which is Send).
57 // `Closure::once` is the approved wasm-bindgen pattern for fire-once callbacks.
58 let closure = wasm_bindgen::closure::Closure::once(move || {
59 let _ = tx.send(());
60 });
61 if let Some(win) = web_sys::window() {
62 let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(
63 closure.as_ref().unchecked_ref(),
64 ms,
65 );
66 }
67 // Leak the closure so JS can call it after Rust drops ownership.
68 // Memory is reclaimed by JS GC once the callback fires.
69 closure.forget();
70
71 Box::pin(async move {
72 // rx is Send; this future is Send.
73 let _ = rx.await;
74 })
75 }
76
77 fn next_tick(&self) -> BoxFuture<'static, ()> {
78 self.sleep(Duration::ZERO)
79 }
80}