Skip to main content

mobiler_web/
lib.rs

1//! `mobiler-web` — Mobiler's web shell.
2//!
3//! Renders **any** Mobiler app's `Widget` tree to the DOM (Leptos / WASM), driving
4//! the Rust core via crux's `Core` and fulfilling capabilities (HTTP) with the
5//! browser's `fetch`. The web twin of the generic Android/SwiftUI shells: write
6//! your app once as a `MobilerApp`, then
7//!
8//! ```ignore
9//! fn main() { mobiler_web::run::<my_app::App>(); }
10//! ```
11//!
12//! renders it on the web — fully styled, no CSS required: the shell ships its own
13//! theme (`mobiler.css`) and injects it on mount, and `Scaffold.dark_mode` flips
14//! the whole theme. Your crate only supplies a minimal `index.html` with the Trunk
15//! entry point; an app may add its own stylesheet to override any widget class.
16
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::rc::Rc;
20use std::sync::Arc;
21
22use crux_core::{App, Core, Request};
23use leptos::prelude::*;
24use mobiler_core::{
25    A11yRole, Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
26    ChartSeries, ChartStyle, ChartTick, Corner, Density, Effect, FieldKind, FontFamily, HttpHeader, HttpOutcome, Icon,
27    ImageRatio, ImageShape, InputValue, PluginCall, PluginNotify, PluginResponse, PluginStreamCall, ProjectColor,
28    Rgb, Spacing, TextStyle, Theme, Tone, TransferEvent, Widget,
29};
30use wasm_bindgen_futures::spawn_local;
31
32/// The shell's own stylesheet — the web twin of the look the Android/SwiftUI shells
33/// decide in code. Shipped with the crate and injected on mount, so `run::<App>()`
34/// renders a fully styled, themeable app with no CSS required from the consuming
35/// app (it can still override any class). Uses CSS variables so `Scaffold.dark_mode`
36/// flips the whole theme by toggling one class.
37const STYLE: &str = include_str!("mobiler.css");
38
39/// Cloneable handle for sending an `Action` into the core. Leptos 0.7 view closures
40/// require `Send`, so this is `Arc` + `Send + Sync` (the crux `Core` is both).
41type Dispatch = Arc<dyn Fn(Action) + Send + Sync>;
42
43/// What a Mobiler app must be to render on the web: a crux `App` speaking the fixed
44/// ABI (`Action` in, `Widget` out, `Effect` for capabilities). `MobilerShell<_>`
45/// satisfies this automatically.
46pub trait WebApp:
47    App<Event = Action, ViewModel = Widget, Effect = Effect> + Default + Send + Sync + 'static
48where
49    Self::Model: Default + Send + Sync,
50{
51}
52impl<T> WebApp for T
53where
54    T: App<Event = Action, ViewModel = Widget, Effect = Effect> + Default + Send + Sync + 'static,
55    T::Model: Default + Send + Sync,
56{
57}
58
59/// Mount a Mobiler app into the document body. Call from your wasm `main`.
60pub fn run<A: WebApp>()
61where
62    A::Model: Default + Send + Sync,
63{
64    console_error_panic_hook::set_once();
65    inject_default_style();
66    inject_hls_support();
67    inject_maplibre_support();
68    leptos::mount::mount_to_body(shell::<A>);
69}
70
71/// hls.js bootstrap for HLS (`.m3u8`) playback in browsers without native HLS
72/// (Chrome/Firefox — Safari/iOS play HLS natively). A `<video>` whose source is an
73/// `.m3u8` is rendered with `data-hls-src` and no `src`; this self-contained script
74/// watches the DOM (a `MutationObserver`, so it also catches elements re-rendered on
75/// each `update`) and, for each such `<video>`, either sets `src` directly (native
76/// HLS, e.g. Safari) or lazily loads hls.js from a CDN and attaches it. If the CDN
77/// fails it falls back to a plain `src`. Inert until an `.m3u8` `Video` appears, so
78/// MP4/Bunny content (and non-video apps) pay nothing. Bunny content keeps using its
79/// own player via `WebView`; this is for raw non-Bunny `.m3u8` on Chrome/Firefox.
80fn inject_hls_support() {
81    const BOOTSTRAP: &str = r#"(function(){
82  function ensureHls(cb){
83    if(window.Hls){return cb();}
84    if(window.__mobilerHlsLoading){(window.__mobilerHlsCbs=window.__mobilerHlsCbs||[]).push(cb);return;}
85    window.__mobilerHlsLoading=true;window.__mobilerHlsCbs=[cb];
86    var s=document.createElement('script');
87    s.src='https://cdn.jsdelivr.net/npm/hls.js@1';
88    var flush=function(){var cbs=window.__mobilerHlsCbs||[];window.__mobilerHlsCbs=[];cbs.forEach(function(f){f();});};
89    s.onload=flush;s.onerror=flush;
90    document.head.appendChild(s);
91  }
92  function attach(v){
93    if(v.__mobilerHlsDone){return;}v.__mobilerHlsDone=true;
94    var url=v.getAttribute('data-hls-src');if(!url){return;}
95    if(v.canPlayType('application/vnd.apple.mpegurl')){v.src=url;return;}
96    ensureHls(function(){
97      if(window.Hls&&window.Hls.isSupported()){var h=new window.Hls();h.loadSource(url);h.attachMedia(v);v.__mobilerHls=h;}
98      else{v.src=url;}
99    });
100  }
101  function scan(root){if(root&&root.querySelectorAll){root.querySelectorAll('video[data-hls-src]').forEach(attach);}}
102  new MutationObserver(function(muts){muts.forEach(function(m){m.addedNodes.forEach(function(n){if(n.nodeType===1){if(n.matches&&n.matches('video[data-hls-src]')){attach(n);}scan(n);}});});}).observe(document.documentElement,{childList:true,subtree:true});
103  scan(document);
104})();"#;
105    let document = leptos::prelude::document();
106    let Some(head) = document.head() else { return };
107    let Ok(script) = document.create_element("script") else { return };
108    script.set_text_content(Some(BOOTSTRAP));
109    let _ = head.append_child(&script);
110}
111
112/// MapLibre-GL bootstrap for [`Widget::Map`]. A self-contained script (mirrors `inject_hls_support`):
113/// lazily loads maplibre-gl (JS + CSS) from a CDN the first time a `.mobiler-map` div appears, then for
114/// each one inits a `maplibregl.Map` from its `data-*` attributes (center/zoom/style/markers/interactive)
115/// and wires taps. The Rust render arm re-creates the map div on every `update`, so a `MutationObserver`
116/// also REMOVES the map (`.remove()`) when its node is dropped — no leaked WebGL contexts. Map/marker
117/// taps are reported to the core by writing `"tap|lat,lng"` / `"marker|id"` into the hidden sibling
118/// `.mobiler-map-sink` input and firing its `input` event, which the render arm's `on:input` forwards as
119/// `Action::Input`. Inert (and the CDN is never fetched) until a `Map` widget appears.
120fn inject_maplibre_support() {
121    const BOOTSTRAP: &str = r#"(function(){
122  function ensureML(cb){
123    if(window.maplibregl){return cb();}
124    if(window.__mobilerMlLoading){(window.__mobilerMlCbs=window.__mobilerMlCbs||[]).push(cb);return;}
125    window.__mobilerMlLoading=true;window.__mobilerMlCbs=[cb];
126    var l=document.createElement('link');l.rel='stylesheet';l.href='https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.css';document.head.appendChild(l);
127    var s=document.createElement('script');s.src='https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js';
128    var flush=function(){var cbs=window.__mobilerMlCbs||[];window.__mobilerMlCbs=[];cbs.forEach(function(f){f();});};
129    s.onload=flush;s.onerror=flush;document.head.appendChild(s);
130  }
131  function emit(el,payload){
132    var sink=el.parentElement&&el.parentElement.querySelector('.mobiler-map-sink');
133    if(sink){sink.value=payload;sink.dispatchEvent(new Event('input',{bubbles:true}));}
134  }
135  function init(el){
136    if(el.__mobilerMap){return;}el.__mobilerMap=true;
137    ensureML(function(){
138      try{
139        var c=(el.getAttribute('data-center')||'0,0').split(',');
140        var center=[parseFloat(c[1])||0,parseFloat(c[0])||0];
141        var zoom=parseFloat(el.getAttribute('data-zoom'))||2;
142        var style=el.getAttribute('data-style')||'https://tiles.openfreemap.org/styles/liberty';
143        var interactive=el.getAttribute('data-interactive')!=='false';
144        var map=new maplibregl.Map({container:el,style:style,center:center,zoom:zoom,interactive:interactive});
145        el.__mobilerMapInstance=map;
146        map.on('click',function(e){emit(el,'tap|'+e.lngLat.lat.toFixed(6)+','+e.lngLat.lng.toFixed(6));});
147        var markers=[];try{markers=JSON.parse(el.getAttribute('data-markers')||'[]');}catch(_){}
148        markers.forEach(function(mk){
149          var m=new maplibregl.Marker().setLngLat([mk.lng,mk.lat]);
150          if(mk.title){m.setPopup(new maplibregl.Popup({offset:24}).setText(mk.title));}
151          m.addTo(map);
152          m.getElement().addEventListener('click',function(ev){ev.stopPropagation();emit(el,'marker|'+mk.id);});
153        });
154      }catch(_){}
155    });
156  }
157  function scan(root){if(root&&root.querySelectorAll){root.querySelectorAll('.mobiler-map[data-map]').forEach(init);}}
158  new MutationObserver(function(muts){muts.forEach(function(m){
159    m.addedNodes.forEach(function(n){if(n.nodeType===1){if(n.matches&&n.matches('.mobiler-map[data-map]')){init(n);}scan(n);}});
160    m.removedNodes.forEach(function(n){if(n.nodeType===1){
161      if(n.__mobilerMapInstance){try{n.__mobilerMapInstance.remove();}catch(_){}}
162      if(n.querySelectorAll){n.querySelectorAll('.mobiler-map').forEach(function(x){if(x.__mobilerMapInstance){try{x.__mobilerMapInstance.remove();}catch(_){}}});}
163    }});
164  });}).observe(document.documentElement,{childList:true,subtree:true});
165  scan(document);
166})();"#;
167    let document = leptos::prelude::document();
168    let Some(head) = document.head() else { return };
169    let Ok(script) = document.create_element("script") else { return };
170    script.set_text_content(Some(BOOTSTRAP));
171    let _ = head.append_child(&script);
172}
173
174/// Inject the shell's default stylesheet at the **front** of `<head>` so it's the
175/// lowest-precedence baseline: an app that ships its own CSS (later in the document)
176/// overrides any of these classes, while an app with no CSS still gets a full theme.
177fn inject_default_style() {
178    let document = leptos::prelude::document();
179    let Some(head) = document.head() else { return };
180    let Ok(style) = document.create_element("style") else { return };
181    let _ = style.set_attribute("data-mobiler", "shell");
182    style.set_text_content(Some(STYLE));
183    let _ = head.insert_before(&style, head.first_child().as_ref());
184}
185
186fn shell<A: WebApp>() -> impl IntoView
187where
188    A::Model: Default + Send + Sync,
189{
190    let core = Arc::new(Core::<A>::new());
191    let (view, set_view) = signal(core.view());
192
193    let send: Dispatch = {
194        let core = core.clone();
195        Arc::new(move |action: Action| {
196            let effects = core.process_event(action);
197            drive(&core, set_view, effects);
198        })
199    };
200
201    // Restore persisted state (localStorage), then fire Start — mirrors the native
202    // shells (which restore before Start so the app sees its saved Model on launch).
203    let saved = local_storage().and_then(|s| s.get_item(STORAGE_KEY).ok().flatten()).unwrap_or_default();
204    if !saved.is_empty() {
205        send(Action::Restore { data: saved });
206    }
207    send(Action::Start);
208
209    let send_for_view = send.clone();
210    view! {
211        <div class="app">
212            {move || render(&view.get(), &send_for_view)}
213        </div>
214    }
215}
216
217/// Process effects: re-read the view on Render; fulfil HTTP via fetch and resolve.
218fn drive<A: WebApp>(core: &Arc<Core<A>>, set_view: WriteSignal<Widget>, effects: Vec<Effect>)
219where
220    A::Model: Default + Send + Sync,
221{
222    for effect in effects {
223        match effect {
224            Effect::Render(_) => set_view.set(core.view()),
225            Effect::PluginNotify(notify) => perform_notify(&notify.operation),
226            Effect::Plugin(mut request) => {
227                let core = core.clone();
228                spawn_local(async move {
229                    let response = perform(&request.operation).await;
230                    if let Ok(next) = core.resolve(&mut request, response) {
231                        drive(&core, set_view, next);
232                    }
233                });
234            }
235            // Long-lived subscription: start a native source that resolves the same
236            // request repeatedly (one event per `core.resolve`). See `start_stream`.
237            Effect::PluginStream(request) => start_stream(core, set_view, request),
238        }
239    }
240}
241
242/// Start a streaming subscription ([`Effect::PluginStream`]): begin a native source
243/// that resolves `request` **repeatedly** (a [`PluginResponse`] per event), each
244/// resolution re-entering the core. The source handle is parked in a per-key
245/// registry so [`unsubscribe`](mobiler_core::Cx::unsubscribe) can stop it.
246///
247/// Web sources: `ticker`/`start` (a `setInterval` emitting an incrementing counter
248/// every `input` ms — the deterministic demonstrator) and `websocket`/`stream`
249/// (a `WebSocket`, a frame per `onmessage`).
250fn start_stream<A: WebApp>(
251    core: &Arc<Core<A>>,
252    set_view: WriteSignal<Widget>,
253    request: Request<PluginStreamCall>,
254) where
255    A::Model: Default + Send + Sync,
256{
257    use wasm_bindgen::{closure::Closure, JsCast};
258
259    let call = request.operation.clone();
260
261    // Each resolution of a `resolves_many_times` request yields the next stream item;
262    // share the request across event closures via Rc<RefCell<_>>.
263    let request = Rc::new(RefCell::new(request));
264    let core = core.clone();
265    let emit = move |resp: PluginResponse| {
266        if let Ok(next) = core.resolve(&mut *request.borrow_mut(), resp) {
267            drive(&core, set_view, next);
268        }
269    };
270
271    let handle = match (call.plugin.as_str(), call.op.as_str()) {
272        // Built-in deterministic demonstrator: emit an incrementing counter every
273        // `input` ms. Dropping the Interval (on unsubscribe) stops it.
274        ("ticker", "start") => {
275            let ms: u32 = call.input.parse().unwrap_or(1000);
276            let count = std::cell::Cell::new(0u32);
277            let interval = gloo_timers::callback::Interval::new(ms, move || {
278                count.set(count.get() + 1);
279                emit(PluginResponse::text(true, count.get().to_string()));
280            });
281            StreamHandle::Ticker { _interval: interval }
282        }
283        ("websocket", "stream") => {
284            let Ok(ws) = web_sys::WebSocket::new(&call.input) else { return };
285            let onmessage = {
286                let emit = emit.clone();
287                Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
288                    emit(PluginResponse::text(true, e.data().as_string().unwrap_or_default()));
289                })
290            };
291            let onclose = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_e| {
292                emit(PluginResponse::text(false, "closed"));
293            });
294            ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
295            ws.set_onclose(Some(onclose.as_ref().unchecked_ref()));
296            StreamHandle::Ws(WsStream { ws, _onmessage: onmessage, _onclose: onclose })
297        }
298        // Built-in `system` source: deep-link URLs + app lifecycle. On the web a "deep link" is the
299        // current URL (delivered on subscribe + on `popstate`) and "lifecycle" maps to page
300        // visibility (`visibilitychange`). Listeners are dropped (removed) on unsubscribe.
301        ("system", "events") => {
302            let win = web_sys::window().expect("window");
303            let doc = win.document().expect("document");
304            // Initial: the current URL as a deeplink + current visibility as lifecycle.
305            if let Ok(href) = win.location().href() {
306                emit(PluginResponse::text(true, system_deeplink(&href)));
307            }
308            emit(PluginResponse::text(true, system_lifecycle(&doc)));
309            let onpop = {
310                let (emit, win) = (emit.clone(), win.clone());
311                Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
312                    if let Ok(href) = win.location().href() {
313                        emit(PluginResponse::text(true, system_deeplink(&href)));
314                    }
315                })
316            };
317            let onvis = {
318                let (emit, doc) = (emit.clone(), doc.clone());
319                Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
320                    emit(PluginResponse::text(true, system_lifecycle(&doc)));
321                })
322            };
323            let _ = win.add_event_listener_with_callback("popstate", onpop.as_ref().unchecked_ref());
324            let _ = doc.add_event_listener_with_callback("visibilitychange", onvis.as_ref().unchecked_ref());
325            StreamHandle::System(SystemStream { win, doc, _onpop: onpop, _onvis: onvis })
326        }
327        // Streaming file transfer (`cx.upload` / `cx.download`, Release B). See
328        // `start_web_upload` / `start_web_download` for the WEB ASYMMETRY: upload uses
329        // XHR (the only web API with upload-progress events), download uses fetch +
330        // ReadableStream (progress) and hands the app back a `blob:` handle.
331        ("transfer", op @ ("upload" | "download")) => {
332            let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
333            let url = v.get("url").and_then(|x| x.as_str()).unwrap_or("").to_string();
334            let headers: Vec<(String, String)> = v
335                .get("headers")
336                .and_then(|x| x.as_array())
337                .map(|hs| {
338                    hs.iter()
339                        .filter_map(|h| Some((h.get("name")?.as_str()?.to_string(), h.get("value")?.as_str()?.to_string())))
340                        .collect()
341                })
342                .unwrap_or_default();
343
344            if op == "upload" {
345                let method = v.get("method").and_then(|x| x.as_str()).unwrap_or("PUT").to_string();
346                let source = v.get("source").and_then(|x| x.as_str()).unwrap_or("").to_string();
347                start_web_upload(url, method, headers, source, emit.clone())
348            } else {
349                start_web_download(url, headers, emit.clone())
350            }
351        }
352        _ => return, // unknown / native-only source — ignore on web
353    };
354
355    STREAMS.with(|m| {
356        m.borrow_mut().insert(call.key.clone(), handle);
357    });
358}
359
360/// Monotonic milliseconds, for the ~10/sec progress throttle (`performance.now()`).
361fn js_now() -> f64 {
362    web_sys::window().and_then(|w| w.performance()).map(|p| p.now()).unwrap_or(0.0)
363}
364
365/// Start a web upload via `XMLHttpRequest`.
366///
367/// DELIBERATE WEB ASYMMETRY (see `start_web_download` for the other half): upload uses
368/// XHR because it is the *only* web API that reports upload progress
369/// (`xhr.upload().onprogress`) — `fetch()` has no upload-progress signal at all. Do not
370/// "unify" this with fetch; there is no fetch-based way to get upload progress in a
371/// browser today.
372fn start_web_upload(
373    url: String,
374    method: String,
375    headers: Vec<(String, String)>,
376    source: String,
377    emit: impl Fn(PluginResponse) + Clone + 'static,
378) -> StreamHandle {
379    use wasm_bindgen::{closure::Closure, JsCast};
380    let xhr = web_sys::XmlHttpRequest::new().expect("xhr");
381    let _ = xhr.open_with_async(&method, &url, true);
382    for (n, val) in &headers {
383        let _ = xhr.set_request_header(n, val);
384    }
385
386    // ~10/sec progress throttling, purely on elapsed time. (Gating on `loaded < total`
387    // as well would be a no-op when `!length_computable`, since `total()` is then 0 and
388    // `loaded() < 0` is always false.) The terminal Done is emitted by the
389    // separate onload/onerror/onabort closures below, unthrottled, so completion is always
390    // seen regardless of this gate.
391    let last = std::rc::Rc::new(std::cell::Cell::new(0.0f64));
392    let on_prog = {
393        let (emit, last) = (emit.clone(), last.clone());
394        Closure::<dyn FnMut(web_sys::ProgressEvent)>::new(move |e: web_sys::ProgressEvent| {
395            let now = js_now();
396            if now - last.get() < 100.0 {
397                return;
398            }
399            last.set(now);
400            let total = if e.length_computable() { Some(e.total() as u64) } else { None };
401            emit(transfer_response(&TransferEvent::Progress { transferred: e.loaded() as u64, total }));
402        })
403    };
404    if let Ok(upload) = xhr.upload() {
405        upload.set_onprogress(Some(on_prog.as_ref().unchecked_ref()));
406    }
407
408    // Terminal event: a response (even non-2xx) is `Done { Response }`; only a failure
409    // to obtain a response at all is `Done { TransportError }`.
410    let on_done = {
411        let (emit, xhr_c) = (emit.clone(), xhr.clone());
412        Closure::<dyn FnMut()>::new(move || {
413            let status = xhr_c.status().unwrap_or(0);
414            let outcome = if status == 0 {
415                HttpOutcome::TransportError { message: "upload failed".into() }
416            } else {
417                HttpOutcome::Response { status, headers: vec![], body: vec![] }
418            };
419            emit(transfer_response(&TransferEvent::Done { outcome, handle: None }));
420        })
421    };
422    xhr.set_onload(Some(on_done.as_ref().unchecked_ref()));
423    let on_err = {
424        let emit = emit.clone();
425        Closure::<dyn FnMut()>::new(move || {
426            emit(transfer_response(&TransferEvent::Done {
427                outcome: HttpOutcome::TransportError { message: "upload error".into() },
428                handle: None,
429            }));
430        })
431    };
432    xhr.set_onerror(Some(on_err.as_ref().unchecked_ref()));
433    let on_abort = {
434        let emit = emit.clone();
435        Closure::<dyn FnMut()>::new(move || {
436            emit(transfer_response(&TransferEvent::Done {
437                outcome: HttpOutcome::TransportError { message: "upload aborted".into() },
438                handle: None,
439            }));
440        })
441    };
442    xhr.set_onabort(Some(on_abort.as_ref().unchecked_ref()));
443
444    // The upload `source` is itself a `blob:` URL (e.g. produced by `photo`/`camera` or
445    // `files`), so fetch it back into a `Blob` before sending — same shape a native
446    // shell would read a file handle. A missing/unreadable source sends no body.
447    //
448    // Cancel race (see `TransferHandle::drop`): `open_with_async` above has already run,
449    // but `send`/`send_with_opt_blob` is deferred behind the `fetch_blob` await. Per the
450    // XHR spec, `abort()` before the send-flag is set (i.e. before `send` is called) is a
451    // no-op, so if `cx.unsubscribe` fires in this window, `xhr.abort()` alone would not
452    // stop the request from going out. `cancelled` is the second half of that guarantee:
453    // it's checked right before `send`, after the await, so a drop that lands during the
454    // fetch is still honored.
455    let xhr_send = xhr.clone();
456    let cancelled = std::rc::Rc::new(std::cell::Cell::new(false));
457    let cancelled_send = cancelled.clone();
458    wasm_bindgen_futures::spawn_local(async move {
459        let blob = fetch_blob(&source).await;
460        if cancelled_send.get() {
461            return;
462        }
463        if let Some(blob) = blob {
464            let _ = xhr_send.send_with_opt_blob(Some(&blob));
465        } else {
466            let _ = xhr_send.send();
467        }
468    });
469
470    StreamHandle::Transfer(TransferHandle {
471        xhr: Some(xhr),
472        abort: None,
473        cancelled: Some(cancelled),
474        _on_prog: Some(on_prog),
475        _on_done: Some(on_done),
476        _on_err: Some(on_err),
477        _on_abort: Some(on_abort),
478    })
479}
480
481/// Fetch a `blob:` (or any) URL back into a `Blob`, for handing to
482/// `XmlHttpRequest::send_with_opt_blob`. `None` on any failure (network error, not a
483/// Blob-shaped response, …) — the caller falls back to sending no body.
484async fn fetch_blob(url: &str) -> Option<web_sys::Blob> {
485    use wasm_bindgen::JsCast;
486    let win = web_sys::window()?;
487    let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_str(url)).await.ok()?;
488    let resp: web_sys::Response = resp_value.dyn_into().ok()?;
489    let blob_promise = resp.blob().ok()?;
490    let blob_value = wasm_bindgen_futures::JsFuture::from(blob_promise).await.ok()?;
491    blob_value.dyn_into().ok()
492}
493
494/// Start a web download via `fetch` + a `ReadableStream` reader.
495///
496/// DELIBERATE WEB ASYMMETRY (see `start_web_upload` for the other half): download uses
497/// `fetch`'s streaming response body to report progress as chunks arrive, then hands
498/// the app back a `blob:` handle for the assembled bytes — the same handle shape
499/// `take_image`/`photo.pick` returns via `Url::create_object_url_with_blob`. (XHR could
500/// also do a download, but fetch + ReadableStream is the standard/ergonomic way to get
501/// mid-transfer download progress on the web.)
502fn start_web_download(
503    url: String,
504    headers: Vec<(String, String)>,
505    emit: impl Fn(PluginResponse) + Clone + 'static,
506) -> StreamHandle {
507    let ctrl = web_sys::AbortController::new().expect("abortcontroller");
508    let signal = ctrl.signal();
509    let emit2 = emit.clone();
510    wasm_bindgen_futures::spawn_local(async move {
511        match fetch_stream(&url, &headers, &signal).await {
512            Ok((status, resp_headers, total, mut reader)) => {
513                let mut got: u64 = 0;
514                let mut chunks: Vec<u8> = Vec::new();
515                let mut last = js_now();
516                loop {
517                    match reader.next().await {
518                        Ok(Some(chunk)) => {
519                            got += chunk.len() as u64;
520                            chunks.extend_from_slice(&chunk);
521                            let now = js_now();
522                            // ~10/sec progress throttling (see `start_web_upload`).
523                            if now - last >= 100.0 {
524                                last = now;
525                                emit2(transfer_response(&TransferEvent::Progress { transferred: got, total }));
526                            }
527                        }
528                        Ok(None) => break, // stream finished
529                        Err(msg) => {
530                            emit2(transfer_response(&TransferEvent::Done {
531                                outcome: HttpOutcome::TransportError { message: msg },
532                                handle: None,
533                            }));
534                            return;
535                        }
536                    }
537                }
538                let handle = make_blob_url(&chunks);
539                let outcome = HttpOutcome::Response { status, headers: resp_headers, body: vec![] };
540                emit2(transfer_response(&TransferEvent::Done { outcome, handle: Some(handle) }));
541            }
542            Err(msg) => emit2(transfer_response(&TransferEvent::Done {
543                outcome: HttpOutcome::TransportError { message: msg },
544                handle: None,
545            })),
546        }
547    });
548    StreamHandle::Transfer(TransferHandle {
549        xhr: None,
550        abort: Some(ctrl),
551        cancelled: None,
552        _on_prog: None,
553        _on_done: None,
554        _on_err: None,
555        _on_abort: None,
556    })
557}
558
559/// Begin a GET (with the given headers) via `fetch` under `signal` and return the
560/// response's status, headers, `Content-Length` (if present) and a chunk [`Reader`]
561/// over its body stream.
562async fn fetch_stream(
563    url: &str,
564    headers: &[(String, String)],
565    signal: &web_sys::AbortSignal,
566) -> Result<(u16, Vec<HttpHeader>, Option<u64>, Reader), String> {
567    use wasm_bindgen::JsCast;
568    let win = web_sys::window().ok_or_else(|| "no window".to_string())?;
569    let js_headers = web_sys::Headers::new().map_err(|e| js_err(&e))?;
570    for (n, v) in headers {
571        js_headers.append(n, v).map_err(|e| js_err(&e))?;
572    }
573    let init = web_sys::RequestInit::new();
574    init.set_method("GET");
575    init.set_headers_headers(&js_headers);
576    init.set_signal(Some(signal));
577    let request = web_sys::Request::new_with_str_and_init(url, &init).map_err(|e| js_err(&e))?;
578
579    let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_request(&request))
580        .await
581        .map_err(|e| js_err(&e))?;
582    let resp: web_sys::Response = resp_value.dyn_into().map_err(|_| "fetch: not a Response".to_string())?;
583    let status = resp.status();
584    let resp_headers = response_headers(&resp.headers());
585    let total = resp_headers
586        .iter()
587        .find(|h| h.name.eq_ignore_ascii_case("content-length"))
588        .and_then(|h| h.value.parse().ok());
589
590    let Some(stream) = resp.body() else {
591        // No body (e.g. 204/304, or a HEAD-like response) — an empty reader is correct:
592        // the caller's loop immediately sees "finished" and moves straight to Done.
593        return Ok((status, resp_headers, total, Reader::empty()));
594    };
595    let reader = web_sys::ReadableStreamDefaultReader::new(&stream).map_err(|e| js_err(&e))?;
596    Ok((status, resp_headers, total, Reader::new(reader)))
597}
598
599/// A `web_sys::Headers` iterable (Fetch's `Headers` implements `Symbol.iterator` over
600/// `[name, value]` pairs) collected into our wire [`HttpHeader`] shape.
601fn response_headers(headers: &web_sys::Headers) -> Vec<HttpHeader> {
602    use wasm_bindgen::JsCast;
603    let mut out = Vec::new();
604    if let Ok(Some(iter)) = js_sys::try_iter(headers) {
605        for entry in iter.flatten() {
606            let arr: js_sys::Array = entry.unchecked_into();
607            let name = arr.get(0).as_string().unwrap_or_default();
608            let value = arr.get(1).as_string().unwrap_or_default();
609            out.push(HttpHeader { name, value });
610        }
611    }
612    out
613}
614
615/// Best-effort stringification of a `JsValue` error (e.g. a `DOMException`) for
616/// `TransferEvent::Done { outcome: HttpOutcome::TransportError { message } }`.
617fn js_err(e: &wasm_bindgen::JsValue) -> String {
618    use wasm_bindgen::JsCast;
619    e.as_string()
620        .or_else(|| e.dyn_ref::<js_sys::Error>().map(|err| String::from(err.message())))
621        .unwrap_or_else(|| "transfer error".to_string())
622}
623
624/// A minimal async chunk reader over a `ReadableStreamDefaultReader`. `next()` resolves
625/// to `Ok(Some(bytes))` per chunk, `Ok(None)` when the stream is done, or `Err(message)`
626/// if the underlying `read()` rejects (e.g. the fetch was aborted mid-stream).
627struct Reader(Option<web_sys::ReadableStreamDefaultReader>);
628impl Reader {
629    fn new(reader: web_sys::ReadableStreamDefaultReader) -> Self {
630        Self(Some(reader))
631    }
632    /// A reader over no stream at all (e.g. a bodiless response) — always "done".
633    fn empty() -> Self {
634        Self(None)
635    }
636    async fn next(&mut self) -> Result<Option<Vec<u8>>, String> {
637        use wasm_bindgen::JsCast;
638        let Some(reader) = &self.0 else { return Ok(None) };
639        let result = wasm_bindgen_futures::JsFuture::from(reader.read()).await.map_err(|e| js_err(&e))?;
640        let result: web_sys::ReadableStreamReadResult = result.unchecked_into();
641        if result.get_done().unwrap_or(true) {
642            return Ok(None);
643        }
644        let value = result.get_value();
645        let bytes = js_sys::Uint8Array::new(&value).to_vec();
646        Ok(Some(bytes))
647    }
648}
649
650/// Assemble bytes into a `Blob` and return an object URL — the download's `handle`. The
651/// same shape [`take_image`]'s `Url::create_object_url_with_blob` returns for a picked
652/// photo, so an app can render/save a downloaded file the same way.
653fn make_blob_url(bytes: &[u8]) -> String {
654    let array = js_sys::Uint8Array::from(bytes);
655    let parts = js_sys::Array::new();
656    parts.push(&array);
657    web_sys::Blob::new_with_u8_array_sequence(&parts)
658        .ok()
659        .and_then(|blob| web_sys::Url::create_object_url_with_blob(&blob).ok())
660        .unwrap_or_default()
661}
662
663/// A `system` deeplink event payload (the push-style tagged JSON the app demuxes by `type`).
664fn system_deeplink(url: &str) -> String {
665    format!("{{\"type\":\"deeplink\",\"url\":{}}}", serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()))
666}
667/// A `system` lifecycle event payload — page visibility maps to active/background.
668fn system_lifecycle(doc: &web_sys::Document) -> String {
669    let state = if doc.visibility_state() == web_sys::VisibilityState::Visible { "active" } else { "background" };
670    format!("{{\"type\":\"lifecycle\",\"state\":\"{state}\"}}")
671}
672
673/// An open streaming source, parked by subscription key for teardown. Dropping the
674/// entry stops the source (the `Interval` cancels on drop; the `WebSocket` is closed
675/// explicitly in the `unsubscribe` handler and its closures drop here).
676enum StreamHandle {
677    /// A `ticker` interval — held only so dropping it (on unsubscribe) cancels it.
678    Ticker { _interval: gloo_timers::callback::Interval },
679    Ws(WsStream),
680    /// The built-in `system` source — holds its JS listeners alive; `Drop` removes them on
681    /// unsubscribe (the handle is dropped when removed from `STREAMS`). Never pattern-matched.
682    #[allow(dead_code)]
683    System(SystemStream),
684    /// An in-flight transfer — held so dropping it (on unsubscribe) aborts the XHR /
685    /// cancels the fetch reader. Never pattern-matched.
686    #[allow(dead_code)]
687    Transfer(TransferHandle),
688}
689
690/// Holds a web transfer so unsubscribe can abort it. For upload we keep the
691/// `XmlHttpRequest` (call `.abort()` on drop via the Drop impl); for download we keep an
692/// `AbortController` whose `.abort()` cancels the fetch + reader.
693struct TransferHandle {
694    xhr: Option<web_sys::XmlHttpRequest>,
695    abort: Option<web_sys::AbortController>,
696    // Upload-cancel race guard (see the comment at `start_web_upload`'s `spawn_local`):
697    // `xhr.abort()` before `send()` has been called is a spec no-op, so this flag is the
698    // half that actually stops a not-yet-sent upload. `None` for download, which has no
699    // such window (its `AbortController` is wired into the fetch before any async work).
700    cancelled: Option<std::rc::Rc<std::cell::Cell<bool>>>,
701    // Typed closure fields (not `Closure::into_js_value`, which leaks permanently — see
702    // `WsStream`/`SystemStream` above for the same pattern): held here so they free when
703    // the handle drops, on unsubscribe or transfer completion. Download wires no XHR
704    // event closures, so its fields are `None`.
705    _on_prog: Option<wasm_bindgen::closure::Closure<dyn FnMut(web_sys::ProgressEvent)>>,
706    _on_done: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
707    _on_err: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
708    _on_abort: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
709}
710impl Drop for TransferHandle {
711    fn drop(&mut self) {
712        if let Some(c) = &self.cancelled {
713            c.set(true);
714        }
715        if let Some(x) = &self.xhr {
716            let _ = x.abort();
717        }
718        if let Some(a) = &self.abort {
719            a.abort();
720        }
721    }
722}
723
724/// Bincode a `TransferEvent` into a stream `PluginResponse` (mirrors Release A's `http` encode).
725fn transfer_response(ev: &TransferEvent) -> PluginResponse {
726    PluginResponse {
727        ok: matches!(ev, TransferEvent::Done { outcome, .. } if outcome.is_success()),
728        output: ev.encode(),
729    }
730}
731
732/// The `system` subscription's event listeners — removed from the DOM when dropped (unsubscribe).
733struct SystemStream {
734    win: web_sys::Window,
735    doc: web_sys::Document,
736    _onpop: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
737    _onvis: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
738}
739impl Drop for SystemStream {
740    fn drop(&mut self) {
741        use wasm_bindgen::JsCast;
742        let _ = self.win.remove_event_listener_with_callback("popstate", self._onpop.as_ref().unchecked_ref());
743        let _ = self.doc.remove_event_listener_with_callback("visibilitychange", self._onvis.as_ref().unchecked_ref());
744    }
745}
746
747/// An open web `WebSocket` subscription — holds its JS closures so they stay alive.
748struct WsStream {
749    ws: web_sys::WebSocket,
750    _onmessage: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::MessageEvent)>,
751    _onclose: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::CloseEvent)>,
752}
753
754/// Fulfil a request/response capability. `http` via `fetch`; `device` via the
755/// browser's user-agent string (the web analogue of a device model).
756async fn perform(call: &PluginCall) -> PluginResponse {
757    if call.plugin == "device" {
758        let nav = web_sys::window().map(|w| w.navigator());
759        let output = if call.op == "locale" {
760            // The browser's preferred language as a BCP-47 tag (e.g. "de-CH").
761            nav.and_then(|n| n.language()).unwrap_or_else(|| "en-US".into())
762        } else {
763            nav.and_then(|n| n.user_agent().ok()).unwrap_or_default()
764        };
765        return PluginResponse::text(true, output);
766    }
767    if call.plugin == "photo" && call.op == "pick" {
768        return take_image(false).await;
769    }
770    if call.plugin == "camera" && call.op == "capture" {
771        return take_image(true).await;
772    }
773    if call.plugin == "datetime" {
774        return match call.op.as_str() {
775            "date" => take_datetime("date").await,
776            "time" => take_datetime("time").await,
777            other => PluginResponse::text(false, format!("unknown datetime op '{other}'")),
778        };
779    }
780    if call.plugin == "dialog" && call.op == "confirm" {
781        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
782        let title = v.get("title").and_then(serde_json::Value::as_str).unwrap_or("");
783        let message = v.get("message").and_then(serde_json::Value::as_str).unwrap_or("");
784        let prompt = if title.is_empty() { message.to_string() } else { format!("{title}\n\n{message}") };
785        let ok = web_sys::window()
786            .and_then(|w| w.confirm_with_message(&prompt).ok())
787            .unwrap_or(false);
788        return PluginResponse::text(ok, if ok { "ok" } else { "cancel" });
789    }
790    if call.plugin != "http" {
791        return PluginResponse::text(false, format!("plugin '{}' not available", call.plugin));
792    }
793    let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
794    let url = v.get("url").and_then(serde_json::Value::as_str).unwrap_or("");
795    let body = v.get("body").and_then(serde_json::Value::as_str);
796    let req_headers: Vec<(String, String)> = v
797        .get("headers")
798        .and_then(serde_json::Value::as_array)
799        .map(|hs| {
800            hs.iter()
801                .filter_map(|h| {
802                    Some((
803                        h.get("name")?.as_str()?.to_string(),
804                        h.get("value")?.as_str()?.to_string(),
805                    ))
806                })
807                .collect()
808        })
809        .unwrap_or_default();
810
811    use gloo_net::http::{Method, Request};
812
813    // Exhaustive: an unknown verb is an error, never a silent GET. The previous
814    // `_ => Request::get(url)` fallthrough turned every PUT into a GET.
815    let builder = match call.op.as_str() {
816        "GET" => Request::get(url),
817        "POST" => Request::post(url),
818        "PUT" => Request::put(url),
819        "PATCH" => Request::patch(url),
820        "DELETE" => Request::delete(url),
821        "HEAD" => Request::get(url).method(Method::HEAD),
822        "OPTIONS" => Request::get(url).method(Method::OPTIONS),
823        other => return http_transport_error(format!("unsupported HTTP method '{other}'")),
824    };
825
826    // Only default Content-Type when the caller did not set one.
827    let caller_set_content_type =
828        req_headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-type"));
829
830    // `RequestBuilder::header` maps to `web_sys::Headers::set`, which REPLACES
831    // any existing value for that name — unlike iOS's `addValue` and Android's
832    // `addHeader`, which both APPEND. Build a `gloo_net::http::Headers` and
833    // `append` into it instead, so repeated names (Set-Cookie, Accept) survive
834    // on web the same way they do on the native shells.
835    let gloo_headers = gloo_net::http::Headers::new();
836    for (name, value) in &req_headers {
837        gloo_headers.append(name, value);
838    }
839    if body.is_some() && !caller_set_content_type {
840        gloo_headers.append("Content-Type", "application/json");
841    }
842    let builder = builder.headers(gloo_headers);
843
844    let request = match body {
845        Some(b) => builder.body(b),
846        None => builder.build(),
847    };
848    let request = match request {
849        Ok(r) => r,
850        Err(e) => return http_transport_error(e.to_string()),
851    };
852
853    match request.send().await {
854        Ok(resp) => {
855            let status = resp.status();
856            let headers = resp
857                .headers()
858                .entries()
859                .map(|(name, value)| HttpHeader { name, value })
860                .collect();
861            match resp.binary().await {
862                Ok(bytes) => {
863                    let outcome = HttpOutcome::Response { status, headers, body: bytes };
864                    PluginResponse { ok: (200..300).contains(&status), output: outcome.encode() }
865                }
866                // A body-read failure (truncated/aborted stream) is a transport
867                // failure, not a successful empty response — match native shells.
868                Err(e) => http_transport_error(e.to_string()),
869            }
870        }
871        Err(e) => http_transport_error(e.to_string()),
872    }
873}
874
875/// A failure where no HTTP response was obtained. `ok` is false and there is no status.
876fn http_transport_error(message: String) -> PluginResponse {
877    PluginResponse { ok: false, output: HttpOutcome::TransportError { message }.encode() }
878}
879
880/// Pick or capture an image via a hidden `<input type=file accept=image/*>`, clicked
881/// to open the browser's file dialog — or, with `capture`, to hint the device camera on
882/// supporting mobile browsers (desktop falls back to the file dialog). Awaits the
883/// `change` event and returns a `blob:` object URL the `<img>` renderer loads. No
884/// permission needed (the picker/camera prompt is the browser's). Backs both the
885/// `photo`/`pick` and `camera`/`capture` capabilities.
886async fn take_image(capture: bool) -> PluginResponse {
887    use wasm_bindgen::{closure::Closure, JsCast};
888    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
889        return PluginResponse::text(false, "no document");
890    };
891    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
892        return PluginResponse::text(false, "no input element");
893    };
894    input.set_type("file");
895    input.set_accept("image/*");
896    if capture {
897        // Hints the environment-facing camera on mobile browsers that support it.
898        let _ = input.set_attribute("capture", "environment");
899    }
900
901    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
902    let tx = std::cell::RefCell::new(Some(tx));
903    let input_for_cb = input.clone();
904    let on_change = Closure::wrap(Box::new(move || {
905        let url = input_for_cb
906            .files()
907            .and_then(|files| files.get(0))
908            .and_then(|file| web_sys::Url::create_object_url_with_blob(&file).ok());
909        if let Some(tx) = tx.borrow_mut().take() {
910            let _ = tx.send(url);
911        }
912    }) as Box<dyn FnMut()>);
913    input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
914    input.click();
915    on_change.forget(); // keep the handler alive until `change` fires
916
917    match rx.await {
918        Ok(Some(url)) => PluginResponse::text(true, url),
919        _ => PluginResponse::text(false, "cancelled"),
920    }
921}
922
923/// Pick a date (`kind = "date"`) or time (`kind = "time"`) via a hidden native
924/// `<input>`, opening the browser's picker with `showPicker()`. Returns the value
925/// (`YYYY-MM-DD` for date, 24-hour `HH:MM` for time); `ok=false` on cancel/dismiss.
926/// Backs the `datetime` capability (`cx.pick_date` / `cx.pick_time`).
927async fn take_datetime(kind: &str) -> PluginResponse {
928    use wasm_bindgen::{closure::Closure, JsCast};
929    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
930        return PluginResponse::text(false, "no document");
931    };
932    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
933        return PluginResponse::text(false, "no input element");
934    };
935    input.set_type(kind); // "date" or "time"
936    // showPicker() needs a connected element; keep it in the DOM but out of sight.
937    let _ = input.set_attribute("style", "position:fixed;left:-9999px;opacity:0");
938    if let Some(body) = doc.body() {
939        let _ = body.append_child(&input);
940    }
941
942    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
943    let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
944    let input_for_change = input.clone();
945    let tx_change = tx.clone();
946    let on_change = Closure::wrap(Box::new(move || {
947        let v = input_for_change.value();
948        if let Some(tx) = tx_change.borrow_mut().take() {
949            let _ = tx.send(if v.is_empty() { None } else { Some(v) });
950        }
951    }) as Box<dyn FnMut()>);
952    let tx_cancel = tx.clone();
953    let on_cancel = Closure::wrap(Box::new(move || {
954        if let Some(tx) = tx_cancel.borrow_mut().take() {
955            let _ = tx.send(None);
956        }
957    }) as Box<dyn FnMut()>);
958    let _ = input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref());
959    let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref());
960    if input.show_picker().is_err() {
961        input.click(); // older browsers: focus the field so the user can type a value
962    }
963    on_change.forget(); // keep the handlers alive until an event fires
964    on_cancel.forget();
965
966    let result = rx.await;
967    input.remove();
968    match result {
969        Ok(Some(v)) => PluginResponse::text(true, v),
970        _ => PluginResponse::text(false, "cancelled"),
971    }
972}
973
974const STORAGE_KEY: &str = "mobiler.state";
975
976/// `window.localStorage`, if available.
977fn local_storage() -> Option<web_sys::Storage> {
978    web_sys::window()?.local_storage().ok().flatten()
979}
980
981/// Fulfil a fire-and-forget capability in the browser — the web twin of the native
982/// shells' notify handlers (storage/clipboard/share/browser). None block; an unknown
983/// capability is a graceful no-op.
984fn perform_notify(notify: &PluginNotify) {
985    let win = match web_sys::window() {
986        Some(w) => w,
987        None => return,
988    };
989    match (notify.plugin.as_str(), notify.op.as_str()) {
990        // Persist the state blob (paired with cx.save + restore-on-startup above).
991        ("storage", "save") => {
992            if let Some(s) = local_storage() {
993                let _ = s.set_item(STORAGE_KEY, &notify.input);
994            }
995        }
996        // Copy to the clipboard (write_text returns a Promise we let run).
997        ("clipboard", "copy") => {
998            let _ = win.navigator().clipboard().write_text(&notify.input);
999        }
1000        // Open a URL in a new tab.
1001        ("browser", "open") => {
1002            let _ = win.open_with_url_and_target(&notify.input, "_blank");
1003        }
1004        // No reliable cross-browser share sheet (navigator.share is mobile-only and
1005        // gesture-gated), so degrade to copying — a sane universal fallback.
1006        ("share", _) => {
1007            let _ = win.navigator().clipboard().write_text(&notify.input);
1008        }
1009        // Tear down a streaming subscription: close the WebSocket parked under this
1010        // key (input = the subscription key) and drop its closures. Paired with
1011        // cx.unsubscribe; the matching source was opened in `start_stream`.
1012        ("stream", "unsubscribe") => {
1013            // Removing the entry drops the source (a `ticker` Interval cancels on
1014            // drop); for a WebSocket we also close it explicitly.
1015            if let Some(StreamHandle::Ws(ws)) = STREAMS.with(|m| m.borrow_mut().remove(&notify.input)) {
1016                let _ = ws.ws.close();
1017            }
1018        }
1019        // Transient toast: a styled div appended to <body>, auto-removed after a beat.
1020        ("toast", _) => show_toast(&notify.input),
1021        // Haptic tap. navigator.vibrate is unsupported on iOS Safari (a graceful no-op).
1022        ("haptics", style) => {
1023            let ms = match style {
1024                "light" => 15,
1025                "heavy" => 50,
1026                _ => 30, // medium / unknown
1027            };
1028            let _ = win.navigator().vibrate_with_duration(ms);
1029        }
1030        _ => {} // unknown capability: ignore
1031    }
1032}
1033
1034/// Append a transient toast to `<body>` (styled by `.toast` in mobiler.css) and
1035/// remove it after ~2.6 s — the web twin of the native toast/snackbar.
1036fn show_toast(text: &str) {
1037    let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
1038    let (Ok(el), Some(body)) = (doc.create_element("div"), doc.body()) else { return };
1039    el.set_class_name("toast");
1040    el.set_text_content(Some(text));
1041    let _ = body.append_child(&el);
1042    gloo_timers::callback::Timeout::new(2600, move || el.remove()).forget();
1043}
1044
1045// ---------------- Widget → DOM ----------------
1046
1047/// `Widget` → DOM. **Exhaustive** by construction — the `match` has no catch-all,
1048/// so (like the Compose/SwiftUI shells) it won't compile until every `Widget`
1049/// variant is handled. Style *intent* (TextStyle, Tone, …) becomes a CSS class;
1050/// the concrete look lives in `mobiler.css`.
1051fn render(widget: &Widget, send: &Dispatch) -> AnyView {
1052    match widget {
1053        // ---- content ----
1054        Widget::Text { content, style } => {
1055            let (class, content) = (text_class(*style), content.clone());
1056            view! { <p class=class>{content}</p> }.into_any()
1057        }
1058        Widget::Image { source, shape, ratio } => {
1059            let (class, source) = (image_class(*shape, *ratio), source.clone());
1060            view! { <img class=class src=source /> }.into_any()
1061        }
1062        Widget::Badge { label, tone } => {
1063            let (class, label) = (format!("badge {}", tone_class(*tone)), label.clone());
1064            view! { <span class=class>{label}</span> }.into_any()
1065        }
1066        Widget::ColorDot { color } => {
1067            view! { <span class=format!("dot {}", dot_class(*color))></span> }.into_any()
1068        }
1069        Widget::Avatar { source, status } => {
1070            let dot = status.map(|t| view! { <span class=format!("avatar-status {}", tone_class(t))></span> });
1071            view! {
1072                <span class="avatar">
1073                    <img class="avatar-img" src=source.clone() />
1074                    {dot}
1075                </span>
1076            }
1077            .into_any()
1078        }
1079        Widget::PdfView { url } => {
1080            // Browsers render PDFs natively in an iframe (remote URL or local blob/file URL).
1081            view! { <iframe class="pdfview" src=url.clone() title="PDF"></iframe> }.into_any()
1082        }
1083        Widget::WebView { url } => {
1084            // General embedded web content (incl. hosted player embeds like Bunny.net). `allow`
1085            // permits autoplay / fullscreen / PiP / encrypted-media so hosted players work.
1086            view! {
1087                <iframe
1088                    class="webview"
1089                    src=url.clone()
1090                    title="Web"
1091                    allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
1092                    allowfullscreen=true
1093                ></iframe>
1094            }.into_any()
1095        }
1096        // Interactive map (MapLibre-GL, no key). The div carries the config as data-* attrs;
1097        // `inject_maplibre_support` inits the map + reports taps by firing `input` on the hidden sink,
1098        // which this `on:input` forwards as Action::Input { "{id}.tap" | "{id}.marker", Text(...) }.
1099        Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive } => {
1100            let send = send.clone();
1101            let id = id.clone();
1102            let center = format!("{center_lat},{center_lng}");
1103            let markers_json = serde_json::to_string(markers).unwrap_or_else(|_| "[]".to_string());
1104            let style = style_url.clone().unwrap_or_default();
1105            view! {
1106                <div class="mobiler-map-wrap">
1107                    <div
1108                        class="mobiler-map"
1109                        data-map="1"
1110                        data-center=center
1111                        data-zoom=zoom.to_string()
1112                        data-style=style
1113                        data-markers=markers_json
1114                        data-interactive=interactive.to_string()
1115                    ></div>
1116                    <input
1117                        class="mobiler-map-sink"
1118                        type="text"
1119                        tabindex="-1"
1120                        aria-hidden="true"
1121                        on:input=move |ev| {
1122                            let raw = event_target_value(&ev);
1123                            if let Some((suffix, value)) = raw.split_once('|') {
1124                                send(Action::Input {
1125                                    id: format!("{id}.{suffix}"),
1126                                    value: InputValue::Text(value.to_string()),
1127                                });
1128                            }
1129                        }
1130                    />
1131                </div>
1132            }.into_any()
1133        }
1134        Widget::Video { url, playing, controls, looping, muted, on_ended, poster, start_at_ms, captions, rate, volume, urls, start_index, .. } => {
1135            // Web = a native-controls `<video>`. App-driven play/pause + seek + position/state events
1136            // are iOS/Android only: the web shell rebuilds the whole tree on each `update`, which would
1137            // reset the element ~every tick — so we don't pump those here (poster/captions/rate/volume
1138            // ARE declarative attributes, so they're safe). `muted && playing` → autoplay. MP4 plays
1139            // everywhere; HLS (.m3u8) plays natively on Safari and, on Chrome/Firefox, via the hls.js
1140            // bootstrap (`inject_hls_support`). A non-empty `urls` is a playlist (best-effort: starts at
1141            // `start_index`, advances on `ended` within this element's lifetime — no index pump back).
1142            use wasm_bindgen::JsCast;
1143            let (send, ended) = (send.clone(), on_ended.clone());
1144            let autoplay = *playing && *muted;
1145            let playlist = urls.clone();
1146            let start_index = (*start_index).max(0) as usize;
1147            let effective = if playlist.is_empty() { url.clone() }
1148                else { playlist.get(start_index).cloned().unwrap_or_else(|| url.clone()) };
1149            let is_hls = effective.to_ascii_lowercase().ends_with(".m3u8");
1150            let src = (!is_hls).then(|| effective.clone());
1151            let hls_src = is_hls.then(|| effective.clone());
1152            let poster_attr = poster.clone();
1153            let start_at = *start_at_ms;
1154            let rate = *rate as f64;
1155            let volume = (*volume as f64).clamp(0.0, 1.0);
1156            let tracks: Vec<_> = captions.iter().map(|c| view! {
1157                <track kind="subtitles" src=c.url.clone() srclang=c.language.clone() label=c.label.clone() default=c.default_on />
1158            }).collect();
1159            let next_idx = std::rc::Rc::new(std::cell::Cell::new(start_index));
1160            view! {
1161                <video
1162                    class="video"
1163                    src=src
1164                    data-hls-src=hls_src
1165                    poster=poster_attr
1166                    controls=*controls
1167                    autoplay=autoplay
1168                    prop:loop=*looping
1169                    prop:playbackRate=rate
1170                    prop:volume=volume
1171                    muted=*muted
1172                    playsinline=true
1173                    on:loadedmetadata=move |ev| {
1174                        if start_at >= 0 {
1175                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1176                                v.set_current_time(start_at as f64 / 1000.0);
1177                            }
1178                        }
1179                    }
1180                    on:ended=move |ev| {
1181                        let nxt = next_idx.get() + 1;
1182                        if !playlist.is_empty() && nxt < playlist.len() {
1183                            next_idx.set(nxt);
1184                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1185                                v.set_src(&playlist[nxt]);
1186                                let _ = v.play();
1187                            }
1188                        } else if let Some(t) = ended.clone() {
1189                            send(Action::Fired { token: t });
1190                        }
1191                    }
1192                >{tracks}</video>
1193            }.into_any()
1194        }
1195        Widget::Rating { value, max, on_rate } => {
1196            let value = *value;
1197            let stars: Vec<AnyView> = (1..=*max)
1198                .map(|i| {
1199                    let threshold = u32::from(i) * 10;
1200                    // filled / half / empty by tenths.
1201                    let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
1202                    match on_rate {
1203                        Some(tokens) => {
1204                            let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
1205                            view! {
1206                                <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
1207                                    {glyph}
1208                                </button>
1209                            }
1210                            .into_any()
1211                        }
1212                        None => view! { <span class="star">{glyph}</span> }.into_any(),
1213                    }
1214                })
1215                .collect();
1216            view! { <span class="rating">{stars}</span> }.into_any()
1217        }
1218        Widget::Divider => view! { <hr class="divider" /> }.into_any(),
1219        Widget::Progress { value } => match value {
1220            Some(v) => {
1221                let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
1222                view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
1223            }
1224            None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
1225        },
1226        Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
1227        Widget::Chart { series, labels, style, axis, legend } => {
1228            chart_view(series, labels, *style, *axis, *legend)
1229        }
1230        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
1231            region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
1232        }
1233        Widget::Calendar { year, month, first_weekday, selected, on_day } => {
1234            const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June",
1235                "July", "August", "September", "October", "November", "December"];
1236            let head_label = format!("{} {year}", MONTHS.get((*month as usize).saturating_sub(1)).copied().unwrap_or(""));
1237            let weekdays = ["S", "M", "T", "W", "T", "F", "S"];
1238            let heads: Vec<_> = weekdays.iter().map(|w| view! { <div class="cal-head">{*w}</div> }).collect();
1239            let blanks: Vec<_> = (0..*first_weekday).map(|_| view! { <div class="cal-blank"></div> }).collect();
1240            let selected = *selected;
1241            let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
1242                let day = (i + 1) as u8;
1243                let token = token.clone();
1244                let send = send.clone();
1245                let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
1246                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}</button> }
1247            }).collect();
1248            view! {
1249                <div class="calendar">
1250                    <div class="cal-title">{head_label}</div>
1251                    <div class="cal-grid">{heads}{blanks}{days}</div>
1252                </div>
1253            }.into_any()
1254        }
1255        Widget::SwipeAction { child, actions } => {
1256            // Web has no swipe gesture — render the actions inline as a trailing button row.
1257            let acts: Vec<_> = actions.iter().map(|a| {
1258                let token = a.on_tap.clone();
1259                let send = send.clone();
1260                let cls = format!("swipe-act {}", tone_class(a.tone));
1261                let label = a.label.clone();
1262                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
1263            }).collect();
1264            view! {
1265                <div class="swipe-row">
1266                    <div class="swipe-content">{render(child, send)}</div>
1267                    <div class="swipe-actions">{acts}</div>
1268                </div>
1269            }.into_any()
1270        }
1271        Widget::Spacer { size } => {
1272            view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
1273        }
1274
1275        // ---- layout ----
1276        Widget::Row { children } => {
1277            let kids = render_all(children, send);
1278            view! { <div class="row">{kids}</div> }.into_any()
1279        }
1280        Widget::Column { children } => {
1281            let kids = render_all(children, send);
1282            view! { <div class="col">{kids}</div> }.into_any()
1283        }
1284        Widget::Card { child, style, on_press, on_long_press } => {
1285            let class = format!("card {}", card_class(*style));
1286            let body = render(child, send);
1287            match (on_press, on_long_press) {
1288                // Plain, non-interactive card.
1289                (None, None) => view! { <div class=class>{body}</div> }.into_any(),
1290                // Tappable and/or long-pressable — render a button with the relevant handlers.
1291                (tap, long) => {
1292                    let send = send.clone();
1293                    // Web has no native long-press; shim it with a pointer-hold timer (~500 ms),
1294                    // cancelled on pointerup/leave/cancel. A `long_fired` flag suppresses the
1295                    // click that follows a successful hold so it doesn't also fire the tap.
1296                    let timer: Rc<RefCell<Option<gloo_timers::callback::Timeout>>> =
1297                        Rc::new(RefCell::new(None));
1298                    let long_fired = Rc::new(RefCell::new(false));
1299
1300                    let on_pointerdown = {
1301                        let (send, long, timer, long_fired) =
1302                            (send.clone(), long.clone(), timer.clone(), long_fired.clone());
1303                        move |_: web_sys::PointerEvent| {
1304                            let Some(token) = long.clone() else { return };
1305                            *long_fired.borrow_mut() = false;
1306                            let (send, long_fired) = (send.clone(), long_fired.clone());
1307                            *timer.borrow_mut() = Some(gloo_timers::callback::Timeout::new(
1308                                500,
1309                                move || {
1310                                    *long_fired.borrow_mut() = true;
1311                                    send(Action::Fired { token: token.clone() });
1312                                },
1313                            ));
1314                        }
1315                    };
1316                    let cancel = {
1317                        let timer = timer.clone();
1318                        // Dropping the `Timeout` cancels the pending fire.
1319                        move |_: web_sys::PointerEvent| { timer.borrow_mut().take(); }
1320                    };
1321                    let on_click = {
1322                        let (send, tap, long_fired) = (send.clone(), tap.clone(), long_fired.clone());
1323                        move |_| {
1324                            // Suppress the tap that trails a long-press.
1325                            if std::mem::take(&mut *long_fired.borrow_mut()) {
1326                                return;
1327                            }
1328                            if let Some(token) = tap.clone() {
1329                                send(Action::Fired { token });
1330                            }
1331                        }
1332                    };
1333                    view! {
1334                        <button
1335                            class=format!("{class} card-tappable")
1336                            on:pointerdown=on_pointerdown
1337                            on:pointerup=cancel.clone()
1338                            on:pointerleave=cancel.clone()
1339                            on:pointercancel=cancel
1340                            on:click=on_click
1341                        >
1342                            {body}
1343                        </button>
1344                    }
1345                    .into_any()
1346                }
1347            }
1348        }
1349        // Z-stack. With `scrim`, the first child is a background image, darkened
1350        // by an overlay, and the rest layer on top in light content — the DOM twin
1351        // of the Compose `matchParentSize` scrim / SwiftUI `.overlay` on the image.
1352        Widget::Box { children, align, scrim } => {
1353            let acls = align_class(*align);
1354            if *scrim && children.len() > 1 {
1355                let bg = render(&children[0], send);
1356                let content = render_all(&children[1..], send);
1357                view! {
1358                    <div class=format!("box box-scrim {acls}")>
1359                        {bg}
1360                        <div class="scrim"></div>
1361                        <div class="box-content">{content}</div>
1362                    </div>
1363                }
1364                .into_any()
1365            } else {
1366                let kids = render_all(children, send);
1367                view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
1368            }
1369        }
1370        Widget::Grid { children } => {
1371            let kids = render_all(children, send);
1372            view! { <div class="grid">{kids}</div> }.into_any()
1373        }
1374        Widget::Scroller { children } => {
1375            let kids = render_all(children, send);
1376            view! { <div class="scroller">{kids}</div> }.into_any()
1377        }
1378        // Two-pane master-detail. CSS does the adapting: wide (`@media min-width:768px`) shows both
1379        // panes side-by-side (back hidden); narrow shows one — primary by default, or detail (+ a
1380        // back chevron) when `data-detail` is set. `show_detail`/`on_back` only matter when narrow.
1381        Widget::Split { primary, detail, show_detail, on_back } => {
1382            let p = render(primary, send);
1383            let d = render(detail, send);
1384            let back_btn = on_back.clone().map(|t| {
1385                let send = send.clone();
1386                view! { <button class="split-back" on:click=move |_| send(Action::Fired { token: t.clone() })>"‹ Back"</button> }
1387            });
1388            view! {
1389                <div class="split" data-detail=show_detail.then_some("1")>
1390                    <div class="split-primary">{p}</div>
1391                    <div class="split-detail">{back_btn}{d}</div>
1392                </div>
1393            }.into_any()
1394        }
1395        // Accessibility wrapper: name the subtree for a screen reader (aria-label), give it a role,
1396        // and the hint via `title`. Best-effort web mapping of iOS traits / Android semantics.
1397        Widget::A11y { child, label, hint, role } => {
1398            let body = render(child, send);
1399            let role_attr = role.map(a11y_role_aria).unwrap_or("group");
1400            view! {
1401                <div class="a11y" role=role_attr aria-label=label.clone() title=hint.clone()>
1402                    {body}
1403                </div>
1404            }.into_any()
1405        }
1406        // A long/paged feed. Web has no pull gesture or reliable infinite-scroll on a sub-container,
1407        // so (like Scaffold pull-to-refresh) the gestures degrade to controls: a top "↻ Refresh"
1408        // button (while `on_refresh`), and a bottom "Load more" button (while `has_more && !loading`)
1409        // / loading bar / "end" caption. iOS/Android do true pull + scroll-near-end detection.
1410        Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing } => {
1411            let kids = render_all(children, send);
1412            let refresh_btn = on_refresh.clone().map(|token| {
1413                let send = send.clone();
1414                view! { <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻ Refresh"</button> }
1415            });
1416            let refresh_bar = refreshing.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1417            let loading_bar = loading.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1418            let load_more_btn = (!*loading && *has_more)
1419                .then(|| on_load_more.clone())
1420                .flatten()
1421                .map(|token| {
1422                    let send = send.clone();
1423                    view! { <button class="btn btn-outlined lazylist-more" on:click=move |_| send(Action::Fired { token: token.clone() })>"Load more"</button> }
1424                });
1425            let end_cap = (!*has_more && on_load_more.is_some()).then(|| view! { <div class="lazylist-end">"End of list"</div> });
1426            view! {
1427                <div class="lazylist">
1428                    {refresh_btn}
1429                    {refresh_bar}
1430                    {kids}
1431                    {loading_bar}
1432                    {load_more_btn}
1433                    {end_cap}
1434                </div>
1435            }.into_any()
1436        }
1437
1438        // ---- input / actions ----
1439        Widget::Button { label, style, on_press } => {
1440            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1441            let class = format!("btn {}", button_class(*style));
1442            view! {
1443                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1444                    {label}
1445                </button>
1446            }
1447            .into_any()
1448        }
1449        Widget::IconButton { icon, on_press } => {
1450            let (send, token) = (send.clone(), on_press.clone());
1451            let glyph = icon_glyph(*icon);
1452            view! {
1453                <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
1454                    {glyph}
1455                </button>
1456            }
1457            .into_any()
1458        }
1459        Widget::Chip { label, selected, on_press } => {
1460            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1461            let class = if *selected { "chip selected" } else { "chip" };
1462            view! {
1463                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1464                    {label}
1465                </button>
1466            }
1467            .into_any()
1468        }
1469        Widget::TextField { id, placeholder, value, kind, error } => {
1470            let (send, id) = (send.clone(), id.clone());
1471            let (placeholder, value) = (placeholder.clone(), value.clone());
1472            let invalid = error.is_some();
1473            let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
1474            // (input type, inputmode) per FieldKind. Multiline renders a <textarea> below.
1475            let (itype, imode): (&str, &str) = match kind {
1476                FieldKind::Secure => ("password", ""),
1477                FieldKind::Email => ("email", "email"),
1478                FieldKind::Number => ("text", "numeric"),
1479                FieldKind::Decimal => ("text", "decimal"),
1480                FieldKind::Phone => ("tel", "tel"),
1481                FieldKind::Url => ("url", "url"),
1482                FieldKind::Text | FieldKind::Multiline => ("text", ""),
1483            };
1484            let field_class = if invalid { "field field-invalid" } else { "field" };
1485            let control = if matches!(kind, FieldKind::Multiline) {
1486                view! {
1487                    <textarea
1488                        class=field_class
1489                        rows="3"
1490                        placeholder=placeholder
1491                        prop:value=value
1492                        on:input=move |ev| send(Action::Input {
1493                            id: id.clone(),
1494                            value: InputValue::Text(event_target_value(&ev)),
1495                        })
1496                    ></textarea>
1497                }
1498                .into_any()
1499            } else {
1500                view! {
1501                    <input
1502                        class=field_class
1503                        r#type=itype
1504                        inputmode=imode
1505                        placeholder=placeholder
1506                        prop:value=value
1507                        on:input=move |ev| send(Action::Input {
1508                            id: id.clone(),
1509                            value: InputValue::Text(event_target_value(&ev)),
1510                        })
1511                    />
1512                }
1513                .into_any()
1514            };
1515            view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
1516        }
1517        Widget::SearchField { id, placeholder, value } => {
1518            let (send, id) = (send.clone(), id.clone());
1519            let (placeholder, value) = (placeholder.clone(), value.clone());
1520            view! {
1521                <div class="searchfield">
1522                    <span class="search-icon">{icon_glyph(Icon::Search)}</span>
1523                    <input
1524                        class="search-input"
1525                        placeholder=placeholder
1526                        prop:value=value
1527                        on:input=move |ev| send(Action::Input {
1528                            id: id.clone(),
1529                            value: InputValue::Text(event_target_value(&ev)),
1530                        })
1531                    />
1532                </div>
1533            }
1534            .into_any()
1535        }
1536        Widget::Segmented { segments } => {
1537            let segs: Vec<AnyView> = segments
1538                .iter()
1539                .map(|s| {
1540                    let (send, token) = (send.clone(), s.on_select.clone());
1541                    let class = if s.selected { "segment selected" } else { "segment" };
1542                    let label = s.label.clone();
1543                    view! {
1544                        <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1545                            {label}
1546                        </button>
1547                    }
1548                    .into_any()
1549                })
1550                .collect();
1551            view! { <div class="segmented">{segs}</div> }.into_any()
1552        }
1553        Widget::Toggle { id, label, value } => {
1554            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1555            view! {
1556                <label class="toggle">
1557                    {label}
1558                    <input
1559                        type="checkbox"
1560                        role="switch"
1561                        prop:checked=checked
1562                        on:change=move |ev| send(Action::Input {
1563                            id: id.clone(),
1564                            value: InputValue::Bool(event_target_checked(&ev)),
1565                        })
1566                    />
1567                </label>
1568            }
1569            .into_any()
1570        }
1571        Widget::Checkbox { id, label, value } => {
1572            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1573            view! {
1574                <label class="check">
1575                    <input
1576                        type="checkbox"
1577                        prop:checked=checked
1578                        on:change=move |ev| send(Action::Input {
1579                            id: id.clone(),
1580                            value: InputValue::Bool(event_target_checked(&ev)),
1581                        })
1582                    />
1583                    {label}
1584                </label>
1585            }
1586            .into_any()
1587        }
1588        Widget::Slider { id, value, max } => {
1589            let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
1590            view! {
1591                <input
1592                    class="slider"
1593                    type="range"
1594                    min="0"
1595                    max=max
1596                    prop:value=value
1597                    on:input=move |ev| send(Action::Input {
1598                        id: id.clone(),
1599                        value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
1600                    })
1601                />
1602            }
1603            .into_any()
1604        }
1605        Widget::Stepper { value, on_decrement, on_increment } => {
1606            let send_dec = send.clone();
1607            let send_inc = send.clone();
1608            let (dec, inc) = (on_decrement.clone(), on_increment.clone());
1609            view! {
1610                <div class="stepper">
1611                    <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
1612                    <span class="stepper-value">{*value}</span>
1613                    <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
1614                </div>
1615            }
1616            .into_any()
1617        }
1618
1619        // ---- shell ----
1620        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth } => {
1621            let back_btn = back.clone().map(|token| {
1622                let send = send.clone();
1623                view! {
1624                    <button class="back" on:click=move |_| send(Action::Fired { token: token.clone() })>
1625                        "‹"
1626                    </button>
1627                }
1628            });
1629            let tabbar = (!tabs.is_empty()).then(|| {
1630                let tabs: Vec<AnyView> = tabs
1631                    .iter()
1632                    .map(|tab| {
1633                        let (send, token) = (send.clone(), tab.on_select.clone());
1634                        let class = if tab.selected { "tab selected" } else { "tab" };
1635                        let label = tab.label.clone();
1636                        // Optional leading icon → glyph above the label (icon tab bar).
1637                        let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
1638                        view! {
1639                            <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1640                                {icon}
1641                                <span class="tab-label">{label}</span>
1642                            </button>
1643                        }
1644                        .into_any()
1645                    })
1646                    .collect();
1647                view! { <div class="tabbar">{tabs}</div> }
1648            });
1649            // Floating action button — the raised primary action, anchored over the body.
1650            let fab_btn = fab.clone().map(|f| {
1651                let (send, token) = (send.clone(), f.on_press.clone());
1652                view! {
1653                    <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
1654                        {icon_glyph(f.icon)}
1655                    </button>
1656                }
1657            });
1658            // Modal bottom sheet — a scrim (tap to dismiss) + a panel rising from the bottom.
1659            let sheet_overlay = sheet.as_ref().map(|s| {
1660                let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
1661                let (title, child) = (s.title.clone(), render(&s.child, send));
1662                view! {
1663                    <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
1664                    <div class="sheet">
1665                        <div class="sheet-handle"></div>
1666                        <div class="sheet-title">{title}</div>
1667                        {child}
1668                    </div>
1669                }
1670            });
1671            // `theme-dark` flips the CSS variables for the whole shell — theme-as-data,
1672            // the web twin of the native shells' `preferredColorScheme`/Material theme.
1673            let class = if *dark_mode { "scaffold theme-dark" } else { "scaffold" };
1674            // Pull-to-refresh — web has no pull gesture, so expose a top-bar refresh button +
1675            // an indeterminate bar at the top of the body while `refreshing`.
1676            let refresh_btn = on_refresh.clone().map(|token| {
1677                let send = send.clone();
1678                view! {
1679                    <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
1680                }
1681            });
1682            let refresh_bar = refreshing.then(|| {
1683                view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
1684            });
1685            let body_class = format!("scaffold-body {}", nav_class(route, *depth));
1686            // An app `Theme` overrides the CSS variables inline (brand color, corner, density,
1687            // font) — the web twin of the native shells' brand/tint + shape + spacing + font.
1688            let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
1689            let (title, body) = (title.clone(), render(body, send));
1690            view! {
1691                <div class=class style=theme_style>
1692                    <div class="topbar">
1693                        {back_btn}
1694                        <span class="title">{title}</span>
1695                        {refresh_btn}
1696                    </div>
1697                    <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
1698                    {fab_btn}
1699                    {tabbar}
1700                    {sheet_overlay}
1701                </div>
1702            }
1703            .into_any()
1704        }
1705    }
1706}
1707
1708/// Render a slice of children as sibling views.
1709fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
1710    children.iter().map(|c| render(c, send)).collect()
1711}
1712
1713thread_local! {
1714    /// (previous route key, previous depth, alternating toggle). The render is a
1715    /// stateless whole-tree rebuild, so nav state lives here (wasm is single-
1716    /// threaded). Lets the Scaffold body animate on navigation — the web twin of
1717    /// the native shells keying their body on `route`.
1718    static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
1719
1720    /// Open streaming subscriptions keyed by subscription key (wasm is single-
1721    /// threaded). Each [`Effect::PluginStream`] parks its source here so
1722    /// `cx.unsubscribe(key)` can stop it; dropping the entry stops the source.
1723    static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
1724}
1725
1726/// Render an app [`Theme`] as inline CSS custom properties on the scaffold root — the web
1727/// twin of the native brand/tint + shape + spacing + font. Overrides `mobiler.css`'s defaults
1728/// (its rules read these via `var(--…)`); dark mode still works (it only swaps the colors the
1729/// seed doesn't pin).
1730fn theme_css(t: &Theme) -> String {
1731    let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
1732    let radius = match t.corner {
1733        Corner::None => "0px",
1734        Corner::Small => "8px",
1735        Corner::Medium => "14px",
1736        Corner::Large => "22px",
1737    };
1738    let (gap, pad) = match t.density {
1739        Density::Compact => ("8px", "10px"),
1740        Density::Comfortable => ("12px", "14px"),
1741    };
1742    let font = match t.font {
1743        FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
1744        FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
1745        FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
1746        FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
1747    };
1748    // Secondary brand color (for the CardStyle::Brand gradient); falls back to the seed.
1749    let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
1750    format!(
1751        "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
1752         --accent2:rgb({ar},{ag},{ab});\
1753         --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
1754         --gap:{gap};--pad:{pad};--font:{font};"
1755    )
1756}
1757
1758/// Pick the Scaffold body's transition class for this render. Returns `""` for a
1759/// same-route data update (re-render in place, no transition). On a route change it
1760/// returns a directional class — slide-in from the right when `depth` grew (push),
1761/// from the left when it shrank (pop), a crossfade for a lateral move — and *alternates*
1762/// the `-a`/`-b` suffix each navigation so the CSS animation restarts even though
1763/// Leptos reuses the same DOM node.
1764fn nav_class(route: &str, depth: u32) -> &'static str {
1765    NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
1766        if route == prev_route {
1767            return "";
1768        }
1769        let dir = if depth > *prev_depth {
1770            ["nav-push-a", "nav-push-b"]
1771        } else if depth < *prev_depth {
1772            ["nav-pop-a", "nav-pop-b"]
1773        } else {
1774            ["nav-fade-a", "nav-fade-b"]
1775        };
1776        *toggle = !*toggle;
1777        *prev_route = route.to_string();
1778        *prev_depth = depth;
1779        dir[usize::from(*toggle)]
1780    })
1781}
1782
1783// ---- style intent → CSS class / glyph (the only place that names the look) ----
1784
1785fn text_class(s: TextStyle) -> &'static str {
1786    match s {
1787        TextStyle::Title => "t-title",
1788        TextStyle::Subtitle => "t-subtitle",
1789        TextStyle::Caption => "t-caption",
1790        TextStyle::Emphasis => "t-emphasis",
1791        TextStyle::Body => "t-body",
1792    }
1793}
1794
1795fn button_class(s: ButtonStyle) -> &'static str {
1796    match s {
1797        ButtonStyle::Filled => "btn-filled",
1798        ButtonStyle::Outlined => "btn-outlined",
1799        ButtonStyle::Text => "btn-text",
1800    }
1801}
1802
1803fn card_class(s: CardStyle) -> &'static str {
1804    match s {
1805        CardStyle::Elevated => "card-elevated",
1806        CardStyle::Outlined => "card-outlined",
1807        CardStyle::Filled => "card-filled",
1808        CardStyle::Brand => "card-brand",
1809    }
1810}
1811
1812fn a11y_role_aria(role: A11yRole) -> &'static str {
1813    match role {
1814        A11yRole::Button => "button",
1815        A11yRole::Link => "link",
1816        A11yRole::Image => "img",
1817        A11yRole::Header => "heading",
1818        A11yRole::Adjustable => "slider",
1819    }
1820}
1821
1822fn tone_class(t: Tone) -> &'static str {
1823    match t {
1824        Tone::Neutral => "tone-neutral",
1825        Tone::Success => "tone-success",
1826        Tone::Warning => "tone-warning",
1827        Tone::Danger => "tone-danger",
1828        Tone::Info => "tone-info",
1829    }
1830}
1831
1832fn spacer_class(s: Spacing) -> &'static str {
1833    match s {
1834        Spacing::Xs => "sp-xs",
1835        Spacing::Sm => "sp-sm",
1836        Spacing::Md => "sp-md",
1837        Spacing::Lg => "sp-lg",
1838        Spacing::Xl => "sp-xl",
1839    }
1840}
1841
1842fn icon_glyph(i: Icon) -> &'static str {
1843    match i {
1844        Icon::Delete => "🗑",
1845        Icon::Add => "+",
1846        Icon::Edit => "✏️",
1847        Icon::Close => "✕",
1848        Icon::Settings => "⚙",
1849        Icon::Check => "✓",
1850        Icon::Star => "★",
1851        Icon::Info => "ℹ",
1852        Icon::Home => "⌂",
1853        Icon::Search => "🔍",
1854        Icon::Menu => "☰",
1855        Icon::Filter => "⚟",
1856        Icon::Back => "‹",
1857        Icon::Forward => "›",
1858        Icon::Down => "⌄",
1859        Icon::Bell => "🔔",
1860        Icon::Cart => "🛒",
1861        Icon::Share => "↗",
1862        Icon::Heart => "♡",
1863        Icon::HeartFilled => "♥",
1864        Icon::Person => "👤",
1865        Icon::People => "👥",
1866        Icon::Phone => "📞",
1867        Icon::Mail => "✉",
1868        Icon::Calendar => "📅",
1869        Icon::Clock => "🕑",
1870        Icon::MapPin => "📍",
1871        Icon::Camera => "📷",
1872        Icon::Photo => "🖼",
1873        Icon::Play => "▶",
1874        Icon::Scissors => "✂",
1875    }
1876}
1877
1878fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
1879    let shape = match shape {
1880        ImageShape::Square => "img-square",
1881        ImageShape::Rounded => "img-rounded",
1882        ImageShape::Circle => "img-circle",
1883    };
1884    let ratio = match ratio {
1885        ImageRatio::Wide => "ratio-wide",
1886        ImageRatio::Square => "ratio-square",
1887        ImageRatio::Tall => "ratio-tall",
1888    };
1889    format!("img {shape} {ratio}")
1890}
1891
1892fn dot_class(c: ProjectColor) -> &'static str {
1893    match c {
1894        ProjectColor::Indigo => "dot-indigo",
1895        ProjectColor::Teal => "dot-teal",
1896        ProjectColor::Coral => "dot-coral",
1897        ProjectColor::Amber => "dot-amber",
1898        ProjectColor::Lime => "dot-lime",
1899        ProjectColor::Pink => "dot-pink",
1900    }
1901}
1902
1903fn align_class(a: BoxAlign) -> &'static str {
1904    match a {
1905        BoxAlign::TopStart => "align-top-start",
1906        BoxAlign::TopEnd => "align-top-end",
1907        BoxAlign::Center => "align-center",
1908        BoxAlign::BottomStart => "align-bottom-start",
1909        BoxAlign::BottomCenter => "align-bottom-center",
1910        BoxAlign::BottomEnd => "align-bottom-end",
1911    }
1912}
1913
1914// ------------------------------- charts -------------------------------
1915
1916/// Distinct fallback colors for series 1.. (series 0 with no override rides the theme accent).
1917const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
1918
1919fn hex(c: Rgb) -> String {
1920    format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
1921}
1922
1923/// Color for series `i`: explicit override → theme accent (i==0) → palette.
1924fn chart_color(i: usize, s: &ChartSeries) -> String {
1925    match s.color {
1926        Some(c) => hex(c),
1927        None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
1928        None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
1929    }
1930}
1931
1932/// A series' single magnitude for circular charts (sum of its values).
1933fn chart_mag(s: &ChartSeries) -> f32 {
1934    s.values.iter().copied().sum()
1935}
1936
1937/// Point on a circle: `ang` in radians, 0 = top (12 o'clock), increasing clockwise.
1938fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
1939    (cx + r * ang.sin(), cy - r * ang.cos())
1940}
1941
1942/// An open arc path (for ring/donut/gauge strokes).
1943fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1944    let (x0, y0) = polar(cx, cy, r, a0);
1945    let (x1, y1) = polar(cx, cy, r, a1);
1946    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1947    format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
1948}
1949
1950/// A filled wedge from the center (for pie/donut slices).
1951fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1952    let (x0, y0) = polar(cx, cy, r, a0);
1953    let (x1, y1) = polar(cx, cy, r, a1);
1954    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1955    format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
1956}
1957
1958fn fmt_tick(v: f32) -> String {
1959    if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
1960}
1961
1962fn is_cartesian(style: ChartStyle) -> bool {
1963    matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
1964}
1965
1966/// The y-axis denominator for a cartesian chart.
1967fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
1968    match style {
1969        ChartStyle::StackedBar => (0..nslots)
1970            .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
1971            .fold(0.0, f32::max)
1972            .max(1e-6),
1973        ChartStyle::StackedBar100 => 1.0,
1974        _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
1975    }
1976}
1977
1978fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
1979    // plot area: y in [2, 48] of the 0..50 viewBox
1980    let mut nodes: Vec<AnyView> = Vec::new();
1981    if axis {
1982        for k in 0..=4 {
1983            let y = 2.0 + k as f32 * (46.0 / 4.0);
1984            nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
1985        }
1986    }
1987    match style {
1988        ChartStyle::Line => {
1989            for (i, s) in series.iter().enumerate() {
1990                let n = s.values.len().max(1);
1991                let pts = s.values.iter().enumerate().map(|(j, v)| {
1992                    let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
1993                    let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
1994                    format!("{x:.2},{y:.2}")
1995                }).collect::<Vec<_>>().join(" ");
1996                let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
1997                nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
1998            }
1999        }
2000        ChartStyle::Bar => {
2001            let sw = 100.0 / nslots as f32;
2002            let ns = series.len().max(1);
2003            for (i, s) in series.iter().enumerate() {
2004                let st = format!("fill:{}", chart_color(i, s));
2005                for (j, v) in s.values.iter().enumerate() {
2006                    let h = (v / max).clamp(0.0, 1.0) * 46.0;
2007                    let bw = sw * 0.8 / ns as f32;
2008                    let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
2009                    let y = 48.0 - h;
2010                    nodes.push(view! { <rect x=format!("{x:.2}") y=format!("{y:.2}") width=format!("{bw:.2}") height=format!("{h:.2}") style=st.clone()></rect> }.into_any());
2011                }
2012            }
2013        }
2014        ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
2015            let sw = 100.0 / nslots as f32;
2016            for j in 0..nslots {
2017                let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
2018                let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
2019                let mut acc = 0.0_f32;
2020                for (i, s) in series.iter().enumerate() {
2021                    let v = *s.values.get(j).unwrap_or(&0.0);
2022                    let h = (v / denom).clamp(0.0, 1.0) * 46.0;
2023                    let x = j as f32 * sw + sw * 0.15;
2024                    let bw = sw * 0.7;
2025                    let y = 48.0 - acc - h;
2026                    let st = format!("fill:{}", chart_color(i, s));
2027                    nodes.push(view! { <rect x=format!("{x:.2}") y=format!("{y:.2}") width=format!("{bw:.2}") height=format!("{h:.2}") style=st></rect> }.into_any());
2028                    acc += h;
2029                }
2030            }
2031        }
2032        _ => {}
2033    }
2034    view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
2035}
2036
2037fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
2038    use std::f32::consts::PI;
2039    let mut nodes: Vec<AnyView> = Vec::new();
2040    match style {
2041        ChartStyle::Pie | ChartStyle::Donut => {
2042            let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
2043            let mut a = 0.0_f32;
2044            for (i, s) in series.iter().enumerate() {
2045                let frac = chart_mag(s) / total;
2046                let st = format!("fill:{}", chart_color(i, s));
2047                if frac >= 0.999 {
2048                    nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
2049                } else if frac > 0.0 {
2050                    let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
2051                    nodes.push(view! { <path d=d style=st></path> }.into_any());
2052                }
2053                a += frac * 2.0 * PI;
2054            }
2055            if matches!(style, ChartStyle::Donut) {
2056                nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
2057            }
2058        }
2059        ChartStyle::Rings => {
2060            let n = series.len().max(1);
2061            for (i, s) in series.iter().enumerate() {
2062                let r = 45.0 - i as f32 * (34.0 / n as f32);
2063                let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2064                let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2065                nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style="fill:none;stroke:var(--border, #e6e6e6);stroke-width:6"></circle> }.into_any());
2066                let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
2067                if prog >= 0.999 {
2068                    nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
2069                } else if prog > 0.0 {
2070                    let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
2071                    nodes.push(view! { <path d=d style=st></path> }.into_any());
2072                }
2073            }
2074        }
2075        ChartStyle::Gauge => {
2076            let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
2077            let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2078            let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2079            let a0 = -0.75 * PI; // 270° sweep, gap at the bottom
2080            let a1 = 0.75 * PI;
2081            nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a1) style="fill:none;stroke:var(--border, #e6e6e6);stroke-width:8;stroke-linecap:round"></path> }.into_any());
2082            if prog > 0.0 {
2083                let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
2084                nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
2085            }
2086            let pct = format!("{}%", (prog * 100.0).round() as i64);
2087            nodes.push(view! { <text x="50" y="56" style="fill:var(--fg, #222);font-size:20px;font-weight:700;text-anchor:middle">{pct}</text> }.into_any());
2088        }
2089        _ => {}
2090    }
2091    view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
2092}
2093
2094fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
2095    let cartesian = is_cartesian(style);
2096    let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
2097    let max = cartesian_max(series, style, nslots);
2098
2099    let plot = if cartesian {
2100        let svg = cartesian_svg(series, style, axis, max, nslots);
2101        let yaxis = if axis {
2102            let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
2103                .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
2104                .collect();
2105            Some(view! { <div class="chart-yaxis">{ticks}</div> })
2106        } else {
2107            None
2108        };
2109        view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
2110    } else {
2111        circular_svg(series, style).into_any()
2112    };
2113
2114    let label_row = if cartesian && !labels.is_empty() {
2115        let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
2116        Some(view! { <div class="chart-labels">{items}</div> })
2117    } else {
2118        None
2119    };
2120
2121    let legend_row = if legend {
2122        let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
2123            let sw = format!("background:{}", chart_color(i, s));
2124            let name = s.name.clone();
2125            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2126        }).collect();
2127        Some(view! { <div class="chart-legend">{items}</div> })
2128    } else {
2129        None
2130    };
2131
2132    view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
2133}
2134
2135// --------------------------- region chart ---------------------------
2136
2137/// Palette as RGB (parallel to `CHART_PALETTE`) so region charts can compute label contrast.
2138const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
2139    [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
2140
2141/// The resolved fill RGB for region `i` (explicit override → palette).
2142fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
2143    match r.color {
2144        Some(c) => (c.r, c.g, c.b),
2145        None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
2146    }
2147}
2148
2149/// Black or white label text, whichever reads on the given fill (perceived luminance).
2150fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
2151    let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
2152    if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
2153}
2154
2155fn region_color(i: usize, r: &ChartRegion) -> String {
2156    let (r8, g8, b8) = region_rgb(i, r);
2157    format!("#{r8:02x}{g8:02x}{b8:02x}")
2158}
2159
2160// A variable-width stacked-region / coverage-gap chart: absolute-positioned region rectangles in
2161// the [0,x_max]×[0,y_max] plane, horizontal ref lines + chips, an irregular x-axis, an optional
2162// right-side bracket, and a legend. The web twin of the Compose/SwiftUI RegionChart renderers.
2163fn region_chart_view(
2164    regions: &[ChartRegion],
2165    ticks: &[ChartTick],
2166    x_max: f32,
2167    y_max: f32,
2168    ref_lines: &[ChartRefLine],
2169    bracket: &Option<ChartBracket>,
2170    legend: &[ChartLegendItem],
2171) -> AnyView {
2172    let xm = x_max.max(1e-6);
2173    let ym = y_max.max(1e-6);
2174
2175    let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
2176        let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
2177        let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
2178        let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
2179        let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
2180        let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
2181        let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
2182        let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
2183        let label = r.label.clone();
2184        view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
2185    }).collect();
2186
2187    // The reference lines span the full plot width; their value chips sit in the right margin
2188    // (outside the plot), like the original — so the line clearly runs to the plot's edge.
2189    let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
2190        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2191        let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
2192        view! { <div class=cls style=style></div> }
2193    }).collect();
2194    let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
2195        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2196        let label = rl.label.clone();
2197        view! { <div class="rchart-chip" style=style>{label}</div> }
2198    }).collect();
2199
2200    let bracket_div = bracket.as_ref().map(|b| {
2201        let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
2202        let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
2203        let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
2204        let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
2205        view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
2206    });
2207
2208    let yticks: Vec<_> = (0..=4).rev().map(|k| {
2209        let v = ym * k as f32 / 4.0;
2210        view! { <span class="chart-tick">{fmt_tick(v)}</span> }
2211    }).collect();
2212
2213    let xticks: Vec<_> = ticks.iter().map(|t| {
2214        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2215        let label = t.label.clone();
2216        view! { <span class="rchart-xtick" style=style>{label}</span> }
2217    }).collect();
2218
2219    // Axis tick marks (notches on the L-shaped axis): horizontal on the y-axis at each value,
2220    // vertical on the x-axis at each irregular break — drawn over the bands at the plot edges.
2221    let ytick_marks: Vec<_> = (0..=4).map(|k| {
2222        let style = format!("bottom:{:.3}%", k as f32 * 25.0);
2223        view! { <div class="rchart-ytick" style=style></div> }
2224    }).collect();
2225    let xtick_marks: Vec<_> = ticks.iter().map(|t| {
2226        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2227        view! { <div class="rchart-xtickmark" style=style></div> }
2228    }).collect();
2229
2230    let legend_row = if legend.is_empty() {
2231        None
2232    } else {
2233        let items: Vec<_> = legend.iter().map(|l| {
2234            let sw = format!("background:{}", hex(l.color));
2235            let name = l.label.clone();
2236            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2237        }).collect();
2238        Some(view! { <div class="chart-legend">{items}</div> })
2239    };
2240
2241    view! {
2242        <div class="rchart">
2243            <div class="rchart-row">
2244                <div class="rchart-yaxis">{yticks}</div>
2245                <div class="rchart-plotwrap">
2246                    <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
2247                    {chip_divs}{bracket_div}
2248                </div>
2249            </div>
2250            <div class="rchart-xaxis">{xticks}</div>
2251            {legend_row}
2252        </div>
2253    }.into_any()
2254}