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
22#[derive(Debug)]
23pub struct WasmClock;
24
25impl Clock for WasmClock {
26 fn now(&self) -> Timestamp {
27 let ms = js_sys::Date::now(); // f64 millis since epoch
28 Timestamp::from_millisecond(ms as i64).unwrap_or(Timestamp::UNIX_EPOCH)
29 }
30}
31
32/// Read the browser's local IANA timezone name via
33/// `Intl.DateTimeFormat.resolvedOptions()` and resolve it in jiff's tzdb.
34///
35/// Falls back to `TimeZone::UTC` if the browser returns an unrecognised name.
36/// Call once at app startup and provide the result via Leptos context.
37pub fn browser_local_tz() -> TimeZone {
38 use js_sys::{Array, Intl, Object, Reflect};
39 use wasm_bindgen::JsValue;
40
41 let fmt = Intl::DateTimeFormat::new(&Array::new(), &Object::new());
42 let resolved = fmt.resolved_options();
43 Reflect::get(&resolved, &JsValue::from_str("timeZone"))
44 .ok()
45 .and_then(|v| v.as_string())
46 .and_then(|s| TimeZone::get(&s).ok())
47 .unwrap_or(TimeZone::UTC)
48}
49
50#[derive(Debug)]
51pub struct WasmTimer;
52
53impl Timer for WasmTimer {
54 fn sleep(&self, dur: Duration) -> BoxFuture<'static, ()> {
55 let ms = dur.as_millis().min(i32::MAX as u128) as i32;
56 let (tx, rx) = oneshot::channel::<()>();
57
58 // Wire setTimeout → oneshot sender. The closure captures `tx` (which is Send).
59 // `Closure::once` is the approved wasm-bindgen pattern for fire-once callbacks.
60 let closure = wasm_bindgen::closure::Closure::once(move || {
61 let _ = tx.send(());
62 });
63 if let Some(win) = web_sys::window() {
64 let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(
65 closure.as_ref().unchecked_ref(),
66 ms,
67 );
68 }
69 // Leak the closure so JS can call it after Rust drops ownership.
70 // Memory is reclaimed by JS GC once the callback fires.
71 closure.forget();
72
73 Box::pin(async move {
74 // rx is Send; this future is Send.
75 let _ = rx.await;
76 })
77 }
78
79 fn next_tick(&self) -> BoxFuture<'static, ()> {
80 self.sleep(Duration::ZERO)
81 }
82}