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                let multipart = v.get("multipart").map(|m| WebMultipart {
348                    field: m.get("field").and_then(|x| x.as_str()).unwrap_or("").to_string(),
349                    filename: m.get("filename").and_then(|x| x.as_str()).map(|s| s.to_string()),
350                    fields: m
351                        .get("fields")
352                        .and_then(|x| x.as_array())
353                        .map(|fs| {
354                            fs.iter()
355                                .filter_map(|f| Some((f.get("name")?.as_str()?.to_string(), f.get("value")?.as_str()?.to_string())))
356                                .collect()
357                        })
358                        .unwrap_or_default(),
359                });
360                start_web_upload(url, method, headers, source, multipart, emit.clone())
361            } else {
362                start_web_download(url, headers, emit.clone())
363            }
364        }
365        _ => return, // unknown / native-only source — ignore on web
366    };
367
368    STREAMS.with(|m| {
369        m.borrow_mut().insert(call.key.clone(), handle);
370    });
371}
372
373/// Monotonic milliseconds, for the ~10/sec progress throttle (`performance.now()`).
374fn js_now() -> f64 {
375    web_sys::window().and_then(|w| w.performance()).map(|p| p.now()).unwrap_or(0.0)
376}
377
378/// Parsed `multipart` envelope config (Task 1's `cx.upload(...).multipart(...)`), threaded
379/// into `start_web_upload` the same way `headers`/`method`/`source` are. `file_content_type`
380/// is deliberately NOT carried here — it's a native-only override; on web the browser derives
381/// the file part's `Content-Type` from the `Blob` itself.
382struct WebMultipart {
383    /// The file part's field name.
384    field: String,
385    /// Override for the file part's `filename=`; `None` -> infer from the source handle.
386    filename: Option<String>,
387    /// Text fields, in order, emitted before the file part.
388    fields: Vec<(String, String)>,
389}
390
391/// Last `/`-segment of a handle, `?query`/`#fragment` stripped; empty -> "file".
392fn infer_filename(source: &str) -> String {
393    let s = source.split(['?', '#']).next().unwrap_or(source);
394    let name = s.rsplit('/').next().unwrap_or("");
395    if name.is_empty() {
396        "file".to_string()
397    } else {
398        name.to_string()
399    }
400}
401
402/// Parse the CRLF-separated block from `XmlHttpRequest::get_all_response_headers` into
403/// `HttpHeader`s. Each line is `name: value`; a value never contains CRLF (XHR spec), so
404/// splitting on `\r\n` then on the first `:` is sufficient. Blank lines are skipped.
405fn parse_header_block(raw: &str) -> Vec<HttpHeader> {
406    raw.split("\r\n")
407        .filter_map(|line| {
408            let (name, value) = line.split_once(':')?;
409            let name = name.trim();
410            if name.is_empty() {
411                return None;
412            }
413            Some(HttpHeader { name: name.to_string(), value: value.trim().to_string() })
414        })
415        .collect()
416}
417
418/// Start a web upload via `XMLHttpRequest`.
419///
420/// DELIBERATE WEB ASYMMETRY (see `start_web_download` for the other half): upload uses
421/// XHR because it is the *only* web API that reports upload progress
422/// (`xhr.upload().onprogress`) — `fetch()` has no upload-progress signal at all. Do not
423/// "unify" this with fetch; there is no fetch-based way to get upload progress in a
424/// browser today.
425fn start_web_upload(
426    url: String,
427    method: String,
428    headers: Vec<(String, String)>,
429    source: String,
430    multipart: Option<WebMultipart>,
431    emit: impl Fn(PluginResponse) + Clone + 'static,
432) -> StreamHandle {
433    use wasm_bindgen::{closure::Closure, JsCast};
434    let xhr = web_sys::XmlHttpRequest::new().expect("xhr");
435    let _ = xhr.open_with_async(&method, &url, true);
436    for (n, val) in &headers {
437        // In multipart mode, the browser sets `Content-Type: multipart/form-data;
438        // boundary=...` itself when sending a `FormData` body; a caller-supplied
439        // `Content-Type` header would clobber that boundary and break the request. Other
440        // headers (Authorization, etc.) still apply.
441        if multipart.is_some() && n.eq_ignore_ascii_case("content-type") {
442            continue;
443        }
444        let _ = xhr.set_request_header(n, val);
445    }
446
447    // ~10/sec progress throttling, purely on elapsed time. (Gating on `loaded < total`
448    // as well would be a no-op when `!length_computable`, since `total()` is then 0 and
449    // `loaded() < 0` is always false.) The terminal Done is emitted by the
450    // separate onload/onerror/onabort closures below, unthrottled, so completion is always
451    // seen regardless of this gate.
452    let last = std::rc::Rc::new(std::cell::Cell::new(0.0f64));
453    let on_prog = {
454        let (emit, last) = (emit.clone(), last.clone());
455        Closure::<dyn FnMut(web_sys::ProgressEvent)>::new(move |e: web_sys::ProgressEvent| {
456            let now = js_now();
457            if now - last.get() < 100.0 {
458                return;
459            }
460            last.set(now);
461            let total = if e.length_computable() { Some(e.total() as u64) } else { None };
462            emit(transfer_response(&TransferEvent::Progress { transferred: e.loaded() as u64, total }));
463        })
464    };
465    if let Ok(upload) = xhr.upload() {
466        upload.set_onprogress(Some(on_prog.as_ref().unchecked_ref()));
467    }
468
469    // Terminal event: a response (even non-2xx) is `Done { Response }`; only a failure
470    // to obtain a response at all is `Done { TransportError }`.
471    let on_done = {
472        let (emit, xhr_c) = (emit.clone(), xhr.clone());
473        Closure::<dyn FnMut()>::new(move || {
474            let status = xhr_c.status().unwrap_or(0);
475            let outcome = if status == 0 {
476                HttpOutcome::TransportError { message: "upload failed".into() }
477            } else {
478                // Carry the response headers, like the download path and both native shells
479                // do — an upload caller may need ETag / Location. `getAllResponseHeaders`
480                // returns a CRLF-separated block (and, cross-origin, only the
481                // CORS-exposed headers — a browser limit the web download path shares; the
482                // native shells read the full header set).
483                let headers = xhr_c
484                    .get_all_response_headers()
485                    .ok()
486                    .map(|raw| parse_header_block(&raw))
487                    .unwrap_or_default();
488                HttpOutcome::Response { status, headers, body: vec![] }
489            };
490            emit(transfer_response(&TransferEvent::Done { outcome, handle: None }));
491        })
492    };
493    xhr.set_onload(Some(on_done.as_ref().unchecked_ref()));
494    let on_err = {
495        let emit = emit.clone();
496        Closure::<dyn FnMut()>::new(move || {
497            emit(transfer_response(&TransferEvent::Done {
498                outcome: HttpOutcome::TransportError { message: "upload error".into() },
499                handle: None,
500            }));
501        })
502    };
503    xhr.set_onerror(Some(on_err.as_ref().unchecked_ref()));
504    let on_abort = {
505        let emit = emit.clone();
506        Closure::<dyn FnMut()>::new(move || {
507            emit(transfer_response(&TransferEvent::Done {
508                outcome: HttpOutcome::TransportError { message: "upload aborted".into() },
509                handle: None,
510            }));
511        })
512    };
513    xhr.set_onabort(Some(on_abort.as_ref().unchecked_ref()));
514
515    // The upload `source` is itself a `blob:` URL (e.g. produced by `photo`/`camera` or
516    // `files`), so fetch it back into a `Blob` before sending — same shape a native
517    // shell would read a file handle. A missing/unreadable source sends no body.
518    //
519    // Cancel race (see `TransferHandle::drop`): `open_with_async` above has already run,
520    // but `send`/`send_with_opt_blob` is deferred behind the `fetch_blob` await. Per the
521    // XHR spec, `abort()` before the send-flag is set (i.e. before `send` is called) is a
522    // no-op, so if `cx.unsubscribe` fires in this window, `xhr.abort()` alone would not
523    // stop the request from going out. `cancelled` is the second half of that guarantee:
524    // it's checked right before `send`, after the await, so a drop that lands during the
525    // fetch is still honored.
526    let xhr_send = xhr.clone();
527    let cancelled = std::rc::Rc::new(std::cell::Cell::new(false));
528    let cancelled_send = cancelled.clone();
529    wasm_bindgen_futures::spawn_local(async move {
530        let blob = fetch_blob(&source).await;
531        if cancelled_send.get() {
532            return;
533        }
534        match (blob, &multipart) {
535            (Some(blob), Some(mp)) => {
536                // Text fields first, file part LAST (multipart/form-data ordering).
537                let form = web_sys::FormData::new().expect("FormData");
538                for (name, value) in &mp.fields {
539                    let _ = form.append_with_str(name, value);
540                }
541                let filename = mp.filename.clone().unwrap_or_else(|| infer_filename(&source));
542                let _ = form.append_with_blob_and_filename(&mp.field, &blob, &filename);
543                let _ = xhr_send.send_with_opt_form_data(Some(&form));
544            }
545            (Some(blob), None) => {
546                let _ = xhr_send.send_with_opt_blob(Some(&blob));
547            }
548            (None, _) => {
549                let _ = xhr_send.send();
550            }
551        }
552    });
553
554    StreamHandle::Transfer(TransferHandle {
555        xhr: Some(xhr),
556        abort: None,
557        cancelled: Some(cancelled),
558        _on_prog: Some(on_prog),
559        _on_done: Some(on_done),
560        _on_err: Some(on_err),
561        _on_abort: Some(on_abort),
562    })
563}
564
565/// Fetch a `blob:` (or any) URL back into a `Blob`, for handing to
566/// `XmlHttpRequest::send_with_opt_blob`. `None` on any failure (network error, not a
567/// Blob-shaped response, …) — the caller falls back to sending no body.
568async fn fetch_blob(url: &str) -> Option<web_sys::Blob> {
569    use wasm_bindgen::JsCast;
570    let win = web_sys::window()?;
571    let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_str(url)).await.ok()?;
572    let resp: web_sys::Response = resp_value.dyn_into().ok()?;
573    let blob_promise = resp.blob().ok()?;
574    let blob_value = wasm_bindgen_futures::JsFuture::from(blob_promise).await.ok()?;
575    blob_value.dyn_into().ok()
576}
577
578/// Start a web download via `fetch` + a `ReadableStream` reader.
579///
580/// DELIBERATE WEB ASYMMETRY (see `start_web_upload` for the other half): download uses
581/// `fetch`'s streaming response body to report progress as chunks arrive, then hands
582/// the app back a `blob:` handle for the assembled bytes — the same handle shape
583/// `take_image`/`photo.pick` returns via `Url::create_object_url_with_blob`. (XHR could
584/// also do a download, but fetch + ReadableStream is the standard/ergonomic way to get
585/// mid-transfer download progress on the web.)
586fn start_web_download(
587    url: String,
588    headers: Vec<(String, String)>,
589    emit: impl Fn(PluginResponse) + Clone + 'static,
590) -> StreamHandle {
591    let ctrl = web_sys::AbortController::new().expect("abortcontroller");
592    let signal = ctrl.signal();
593    let emit2 = emit.clone();
594    wasm_bindgen_futures::spawn_local(async move {
595        match fetch_stream(&url, &headers, &signal).await {
596            Ok((status, resp_headers, total, mut reader)) => {
597                let mut got: u64 = 0;
598                let mut chunks: Vec<u8> = Vec::new();
599                let mut last = js_now();
600                loop {
601                    match reader.next().await {
602                        Ok(Some(chunk)) => {
603                            got += chunk.len() as u64;
604                            chunks.extend_from_slice(&chunk);
605                            let now = js_now();
606                            // ~10/sec progress throttling (see `start_web_upload`).
607                            if now - last >= 100.0 {
608                                last = now;
609                                emit2(transfer_response(&TransferEvent::Progress { transferred: got, total }));
610                            }
611                        }
612                        Ok(None) => break, // stream finished
613                        Err(msg) => {
614                            emit2(transfer_response(&TransferEvent::Done {
615                                outcome: HttpOutcome::TransportError { message: msg },
616                                handle: None,
617                            }));
618                            return;
619                        }
620                    }
621                }
622                let handle = make_blob_url(&chunks);
623                let outcome = HttpOutcome::Response { status, headers: resp_headers, body: vec![] };
624                emit2(transfer_response(&TransferEvent::Done { outcome, handle: Some(handle) }));
625            }
626            Err(msg) => emit2(transfer_response(&TransferEvent::Done {
627                outcome: HttpOutcome::TransportError { message: msg },
628                handle: None,
629            })),
630        }
631    });
632    StreamHandle::Transfer(TransferHandle {
633        xhr: None,
634        abort: Some(ctrl),
635        cancelled: None,
636        _on_prog: None,
637        _on_done: None,
638        _on_err: None,
639        _on_abort: None,
640    })
641}
642
643/// Begin a GET (with the given headers) via `fetch` under `signal` and return the
644/// response's status, headers, `Content-Length` (if present) and a chunk [`Reader`]
645/// over its body stream.
646async fn fetch_stream(
647    url: &str,
648    headers: &[(String, String)],
649    signal: &web_sys::AbortSignal,
650) -> Result<(u16, Vec<HttpHeader>, Option<u64>, Reader), String> {
651    use wasm_bindgen::JsCast;
652    let win = web_sys::window().ok_or_else(|| "no window".to_string())?;
653    let js_headers = web_sys::Headers::new().map_err(|e| js_err(&e))?;
654    for (n, v) in headers {
655        js_headers.append(n, v).map_err(|e| js_err(&e))?;
656    }
657    let init = web_sys::RequestInit::new();
658    init.set_method("GET");
659    init.set_headers_headers(&js_headers);
660    init.set_signal(Some(signal));
661    let request = web_sys::Request::new_with_str_and_init(url, &init).map_err(|e| js_err(&e))?;
662
663    let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_request(&request))
664        .await
665        .map_err(|e| js_err(&e))?;
666    let resp: web_sys::Response = resp_value.dyn_into().map_err(|_| "fetch: not a Response".to_string())?;
667    let status = resp.status();
668    let resp_headers = response_headers(&resp.headers());
669    let total = resp_headers
670        .iter()
671        .find(|h| h.name.eq_ignore_ascii_case("content-length"))
672        .and_then(|h| h.value.parse().ok());
673
674    let Some(stream) = resp.body() else {
675        // No body (e.g. 204/304, or a HEAD-like response) — an empty reader is correct:
676        // the caller's loop immediately sees "finished" and moves straight to Done.
677        return Ok((status, resp_headers, total, Reader::empty()));
678    };
679    let reader = web_sys::ReadableStreamDefaultReader::new(&stream).map_err(|e| js_err(&e))?;
680    Ok((status, resp_headers, total, Reader::new(reader)))
681}
682
683/// A `web_sys::Headers` iterable (Fetch's `Headers` implements `Symbol.iterator` over
684/// `[name, value]` pairs) collected into our wire [`HttpHeader`] shape.
685fn response_headers(headers: &web_sys::Headers) -> Vec<HttpHeader> {
686    use wasm_bindgen::JsCast;
687    let mut out = Vec::new();
688    if let Ok(Some(iter)) = js_sys::try_iter(headers) {
689        for entry in iter.flatten() {
690            let arr: js_sys::Array = entry.unchecked_into();
691            let name = arr.get(0).as_string().unwrap_or_default();
692            let value = arr.get(1).as_string().unwrap_or_default();
693            out.push(HttpHeader { name, value });
694        }
695    }
696    out
697}
698
699/// Best-effort stringification of a `JsValue` error (e.g. a `DOMException`) for
700/// `TransferEvent::Done { outcome: HttpOutcome::TransportError { message } }`.
701fn js_err(e: &wasm_bindgen::JsValue) -> String {
702    use wasm_bindgen::JsCast;
703    e.as_string()
704        .or_else(|| e.dyn_ref::<js_sys::Error>().map(|err| String::from(err.message())))
705        .unwrap_or_else(|| "transfer error".to_string())
706}
707
708/// A minimal async chunk reader over a `ReadableStreamDefaultReader`. `next()` resolves
709/// to `Ok(Some(bytes))` per chunk, `Ok(None)` when the stream is done, or `Err(message)`
710/// if the underlying `read()` rejects (e.g. the fetch was aborted mid-stream).
711struct Reader(Option<web_sys::ReadableStreamDefaultReader>);
712impl Reader {
713    fn new(reader: web_sys::ReadableStreamDefaultReader) -> Self {
714        Self(Some(reader))
715    }
716    /// A reader over no stream at all (e.g. a bodiless response) — always "done".
717    fn empty() -> Self {
718        Self(None)
719    }
720    async fn next(&mut self) -> Result<Option<Vec<u8>>, String> {
721        use wasm_bindgen::JsCast;
722        let Some(reader) = &self.0 else { return Ok(None) };
723        let result = wasm_bindgen_futures::JsFuture::from(reader.read()).await.map_err(|e| js_err(&e))?;
724        let result: web_sys::ReadableStreamReadResult = result.unchecked_into();
725        if result.get_done().unwrap_or(true) {
726            return Ok(None);
727        }
728        let value = result.get_value();
729        let bytes = js_sys::Uint8Array::new(&value).to_vec();
730        Ok(Some(bytes))
731    }
732}
733
734/// Assemble bytes into a `Blob` and return an object URL — the download's `handle`. The
735/// same shape [`take_image`]'s `Url::create_object_url_with_blob` returns for a picked
736/// photo, so an app can render/save a downloaded file the same way.
737fn make_blob_url(bytes: &[u8]) -> String {
738    let array = js_sys::Uint8Array::from(bytes);
739    let parts = js_sys::Array::new();
740    parts.push(&array);
741    web_sys::Blob::new_with_u8_array_sequence(&parts)
742        .ok()
743        .and_then(|blob| web_sys::Url::create_object_url_with_blob(&blob).ok())
744        .unwrap_or_default()
745}
746
747/// A `system` deeplink event payload (the push-style tagged JSON the app demuxes by `type`).
748fn system_deeplink(url: &str) -> String {
749    format!("{{\"type\":\"deeplink\",\"url\":{}}}", serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()))
750}
751/// A `system` lifecycle event payload — page visibility maps to active/background.
752fn system_lifecycle(doc: &web_sys::Document) -> String {
753    let state = if doc.visibility_state() == web_sys::VisibilityState::Visible { "active" } else { "background" };
754    format!("{{\"type\":\"lifecycle\",\"state\":\"{state}\"}}")
755}
756
757/// An open streaming source, parked by subscription key for teardown. Dropping the
758/// entry stops the source (the `Interval` cancels on drop; the `WebSocket` is closed
759/// explicitly in the `unsubscribe` handler and its closures drop here).
760enum StreamHandle {
761    /// A `ticker` interval — held only so dropping it (on unsubscribe) cancels it.
762    Ticker { _interval: gloo_timers::callback::Interval },
763    Ws(WsStream),
764    /// The built-in `system` source — holds its JS listeners alive; `Drop` removes them on
765    /// unsubscribe (the handle is dropped when removed from `STREAMS`). Never pattern-matched.
766    #[allow(dead_code)]
767    System(SystemStream),
768    /// An in-flight transfer — held so dropping it (on unsubscribe) aborts the XHR /
769    /// cancels the fetch reader. Never pattern-matched.
770    #[allow(dead_code)]
771    Transfer(TransferHandle),
772}
773
774/// Holds a web transfer so unsubscribe can abort it. For upload we keep the
775/// `XmlHttpRequest` (call `.abort()` on drop via the Drop impl); for download we keep an
776/// `AbortController` whose `.abort()` cancels the fetch + reader.
777struct TransferHandle {
778    xhr: Option<web_sys::XmlHttpRequest>,
779    abort: Option<web_sys::AbortController>,
780    // Upload-cancel race guard (see the comment at `start_web_upload`'s `spawn_local`):
781    // `xhr.abort()` before `send()` has been called is a spec no-op, so this flag is the
782    // half that actually stops a not-yet-sent upload. `None` for download, which has no
783    // such window (its `AbortController` is wired into the fetch before any async work).
784    cancelled: Option<std::rc::Rc<std::cell::Cell<bool>>>,
785    // Typed closure fields (not `Closure::into_js_value`, which leaks permanently — see
786    // `WsStream`/`SystemStream` above for the same pattern): held here so they free when
787    // the handle drops, on unsubscribe or transfer completion. Download wires no XHR
788    // event closures, so its fields are `None`.
789    _on_prog: Option<wasm_bindgen::closure::Closure<dyn FnMut(web_sys::ProgressEvent)>>,
790    _on_done: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
791    _on_err: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
792    _on_abort: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
793}
794impl Drop for TransferHandle {
795    fn drop(&mut self) {
796        if let Some(c) = &self.cancelled {
797            c.set(true);
798        }
799        if let Some(x) = &self.xhr {
800            let _ = x.abort();
801        }
802        if let Some(a) = &self.abort {
803            a.abort();
804        }
805    }
806}
807
808/// Bincode a `TransferEvent` into a stream `PluginResponse` (mirrors Release A's `http` encode).
809fn transfer_response(ev: &TransferEvent) -> PluginResponse {
810    PluginResponse {
811        ok: matches!(ev, TransferEvent::Done { outcome, .. } if outcome.is_success()),
812        output: ev.encode(),
813    }
814}
815
816/// The `system` subscription's event listeners — removed from the DOM when dropped (unsubscribe).
817struct SystemStream {
818    win: web_sys::Window,
819    doc: web_sys::Document,
820    _onpop: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
821    _onvis: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
822}
823impl Drop for SystemStream {
824    fn drop(&mut self) {
825        use wasm_bindgen::JsCast;
826        let _ = self.win.remove_event_listener_with_callback("popstate", self._onpop.as_ref().unchecked_ref());
827        let _ = self.doc.remove_event_listener_with_callback("visibilitychange", self._onvis.as_ref().unchecked_ref());
828    }
829}
830
831/// An open web `WebSocket` subscription — holds its JS closures so they stay alive.
832struct WsStream {
833    ws: web_sys::WebSocket,
834    _onmessage: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::MessageEvent)>,
835    _onclose: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::CloseEvent)>,
836}
837
838/// Fulfil a request/response capability. `http` via `fetch`; `device` via the
839/// browser's user-agent string (the web analogue of a device model).
840async fn perform(call: &PluginCall) -> PluginResponse {
841    if call.plugin == "device" {
842        let nav = web_sys::window().map(|w| w.navigator());
843        let output = if call.op == "locale" {
844            // The browser's preferred language as a BCP-47 tag (e.g. "de-CH").
845            nav.and_then(|n| n.language()).unwrap_or_else(|| "en-US".into())
846        } else {
847            nav.and_then(|n| n.user_agent().ok()).unwrap_or_default()
848        };
849        return PluginResponse::text(true, output);
850    }
851    if call.plugin == "photo" && call.op == "pick" {
852        return take_image(false).await;
853    }
854    if call.plugin == "camera" && call.op == "capture" {
855        return take_image(true).await;
856    }
857    if call.plugin == "datetime" {
858        return match call.op.as_str() {
859            "date" => take_datetime("date").await,
860            "time" => take_datetime("time").await,
861            other => PluginResponse::text(false, format!("unknown datetime op '{other}'")),
862        };
863    }
864    if call.plugin == "dialog" && call.op == "confirm" {
865        let ok = confirm_modal(ConfirmAsk::parse(&call.input)).await;
866        return PluginResponse::text(ok, if ok { "ok" } else { "cancel" });
867    }
868    if call.plugin != "http" {
869        return PluginResponse::text(false, format!("plugin '{}' not available", call.plugin));
870    }
871    let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
872    let url = v.get("url").and_then(serde_json::Value::as_str).unwrap_or("");
873    let body = v.get("body").and_then(serde_json::Value::as_str);
874    let req_headers: Vec<(String, String)> = v
875        .get("headers")
876        .and_then(serde_json::Value::as_array)
877        .map(|hs| {
878            hs.iter()
879                .filter_map(|h| {
880                    Some((
881                        h.get("name")?.as_str()?.to_string(),
882                        h.get("value")?.as_str()?.to_string(),
883                    ))
884                })
885                .collect()
886        })
887        .unwrap_or_default();
888
889    use gloo_net::http::{Method, Request};
890
891    // Exhaustive: an unknown verb is an error, never a silent GET. The previous
892    // `_ => Request::get(url)` fallthrough turned every PUT into a GET.
893    let builder = match call.op.as_str() {
894        "GET" => Request::get(url),
895        "POST" => Request::post(url),
896        "PUT" => Request::put(url),
897        "PATCH" => Request::patch(url),
898        "DELETE" => Request::delete(url),
899        "HEAD" => Request::get(url).method(Method::HEAD),
900        "OPTIONS" => Request::get(url).method(Method::OPTIONS),
901        other => return http_transport_error(format!("unsupported HTTP method '{other}'")),
902    };
903
904    // Only default Content-Type when the caller did not set one.
905    let caller_set_content_type =
906        req_headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-type"));
907
908    // `RequestBuilder::header` maps to `web_sys::Headers::set`, which REPLACES
909    // any existing value for that name — unlike iOS's `addValue` and Android's
910    // `addHeader`, which both APPEND. Build a `gloo_net::http::Headers` and
911    // `append` into it instead, so repeated names (Set-Cookie, Accept) survive
912    // on web the same way they do on the native shells.
913    let gloo_headers = gloo_net::http::Headers::new();
914    for (name, value) in &req_headers {
915        gloo_headers.append(name, value);
916    }
917    if body.is_some() && !caller_set_content_type {
918        gloo_headers.append("Content-Type", "application/json");
919    }
920    let builder = builder.headers(gloo_headers);
921
922    let request = match body {
923        Some(b) => builder.body(b),
924        None => builder.build(),
925    };
926    let request = match request {
927        Ok(r) => r,
928        Err(e) => return http_transport_error(e.to_string()),
929    };
930
931    match request.send().await {
932        Ok(resp) => {
933            let status = resp.status();
934            let headers = resp
935                .headers()
936                .entries()
937                .map(|(name, value)| HttpHeader { name, value })
938                .collect();
939            match resp.binary().await {
940                Ok(bytes) => {
941                    let outcome = HttpOutcome::Response { status, headers, body: bytes };
942                    PluginResponse { ok: (200..300).contains(&status), output: outcome.encode() }
943                }
944                // A body-read failure (truncated/aborted stream) is a transport
945                // failure, not a successful empty response — match native shells.
946                Err(e) => http_transport_error(e.to_string()),
947            }
948        }
949        Err(e) => http_transport_error(e.to_string()),
950    }
951}
952
953/// A failure where no HTTP response was obtained. `ok` is false and there is no status.
954fn http_transport_error(message: String) -> PluginResponse {
955    PluginResponse { ok: false, output: HttpOutcome::TransportError { message }.encode() }
956}
957
958/// Pick or capture an image via a hidden `<input type=file accept=image/*>`, clicked
959/// to open the browser's file dialog — or, with `capture`, to hint the device camera on
960/// supporting mobile browsers (desktop falls back to the file dialog). Awaits the
961/// `change` event and returns a `blob:` object URL the `<img>` renderer loads. No
962/// permission needed (the picker/camera prompt is the browser's). Backs both the
963/// `photo`/`pick` and `camera`/`capture` capabilities.
964async fn take_image(capture: bool) -> PluginResponse {
965    use wasm_bindgen::{closure::Closure, JsCast};
966    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
967        return PluginResponse::text(false, "no document");
968    };
969    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
970        return PluginResponse::text(false, "no input element");
971    };
972    input.set_type("file");
973    input.set_accept("image/*");
974    if capture {
975        // Hints the environment-facing camera on mobile browsers that support it.
976        let _ = input.set_attribute("capture", "environment");
977    }
978
979    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
980    let tx = std::cell::RefCell::new(Some(tx));
981    let input_for_cb = input.clone();
982    let on_change = Closure::wrap(Box::new(move || {
983        let url = input_for_cb
984            .files()
985            .and_then(|files| files.get(0))
986            .and_then(|file| web_sys::Url::create_object_url_with_blob(&file).ok());
987        if let Some(tx) = tx.borrow_mut().take() {
988            let _ = tx.send(url);
989        }
990    }) as Box<dyn FnMut()>);
991    input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
992    input.click();
993    on_change.forget(); // keep the handler alive until `change` fires
994
995    match rx.await {
996        Ok(Some(url)) => PluginResponse::text(true, url),
997        _ => PluginResponse::text(false, "cancelled"),
998    }
999}
1000
1001/// Pick a date (`kind = "date"`) or time (`kind = "time"`) via a hidden native
1002/// `<input>`, opening the browser's picker with `showPicker()`. Returns the value
1003/// (`YYYY-MM-DD` for date, 24-hour `HH:MM` for time); `ok=false` on cancel/dismiss.
1004/// Backs the `datetime` capability (`cx.pick_date` / `cx.pick_time`).
1005async fn take_datetime(kind: &str) -> PluginResponse {
1006    use wasm_bindgen::{closure::Closure, JsCast};
1007    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
1008        return PluginResponse::text(false, "no document");
1009    };
1010    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
1011        return PluginResponse::text(false, "no input element");
1012    };
1013    input.set_type(kind); // "date" or "time"
1014    // showPicker() needs a connected element; keep it in the DOM but out of sight.
1015    let _ = input.set_attribute("style", "position:fixed;left:-9999px;opacity:0");
1016    if let Some(body) = doc.body() {
1017        let _ = body.append_child(&input);
1018    }
1019
1020    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
1021    let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
1022    let input_for_change = input.clone();
1023    let tx_change = tx.clone();
1024    let on_change = Closure::wrap(Box::new(move || {
1025        let v = input_for_change.value();
1026        if let Some(tx) = tx_change.borrow_mut().take() {
1027            let _ = tx.send(if v.is_empty() { None } else { Some(v) });
1028        }
1029    }) as Box<dyn FnMut()>);
1030    let tx_cancel = tx.clone();
1031    let on_cancel = Closure::wrap(Box::new(move || {
1032        if let Some(tx) = tx_cancel.borrow_mut().take() {
1033            let _ = tx.send(None);
1034        }
1035    }) as Box<dyn FnMut()>);
1036    let _ = input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref());
1037    let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref());
1038    if input.show_picker().is_err() {
1039        input.click(); // older browsers: focus the field so the user can type a value
1040    }
1041    on_change.forget(); // keep the handlers alive until an event fires
1042    on_cancel.forget();
1043
1044    let result = rx.await;
1045    input.remove();
1046    match result {
1047        Ok(Some(v)) => PluginResponse::text(true, v),
1048        _ => PluginResponse::text(false, "cancelled"),
1049    }
1050}
1051
1052const STORAGE_KEY: &str = "mobiler.state";
1053
1054/// `window.localStorage`, if available.
1055fn local_storage() -> Option<web_sys::Storage> {
1056    web_sys::window()?.local_storage().ok().flatten()
1057}
1058
1059/// Fulfil a fire-and-forget capability in the browser — the web twin of the native
1060/// shells' notify handlers (storage/clipboard/share/browser). None block; an unknown
1061/// capability is a graceful no-op.
1062fn perform_notify(notify: &PluginNotify) {
1063    let win = match web_sys::window() {
1064        Some(w) => w,
1065        None => return,
1066    };
1067    match (notify.plugin.as_str(), notify.op.as_str()) {
1068        // Persist the state blob (paired with cx.save + restore-on-startup above).
1069        ("storage", "save") => {
1070            if let Some(s) = local_storage() {
1071                let _ = s.set_item(STORAGE_KEY, &notify.input);
1072            }
1073        }
1074        // Copy to the clipboard (write_text returns a Promise we let run).
1075        ("clipboard", "copy") => {
1076            let _ = win.navigator().clipboard().write_text(&notify.input);
1077        }
1078        // Open a URL in a new tab.
1079        ("browser", "open") => {
1080            let _ = win.open_with_url_and_target(&notify.input, "_blank");
1081        }
1082        // No reliable cross-browser share sheet (navigator.share is mobile-only and
1083        // gesture-gated), so degrade to copying — a sane universal fallback.
1084        ("share", _) => {
1085            let _ = win.navigator().clipboard().write_text(&notify.input);
1086        }
1087        // Tear down a streaming subscription: close the WebSocket parked under this
1088        // key (input = the subscription key) and drop its closures. Paired with
1089        // cx.unsubscribe; the matching source was opened in `start_stream`.
1090        ("stream", "unsubscribe") => {
1091            // Removing the entry drops the source (a `ticker` Interval cancels on
1092            // drop); for a WebSocket we also close it explicitly.
1093            if let Some(StreamHandle::Ws(ws)) = STREAMS.with(|m| m.borrow_mut().remove(&notify.input)) {
1094                let _ = ws.ws.close();
1095            }
1096        }
1097        // Transient toast: a styled div appended to <body>, auto-removed after a beat.
1098        ("toast", _) => show_toast(&notify.input),
1099        // Haptic tap. navigator.vibrate is unsupported on iOS Safari (a graceful no-op).
1100        ("haptics", style) => {
1101            let ms = match style {
1102                "light" => 15,
1103                "heavy" => 50,
1104                _ => 30, // medium / unknown
1105            };
1106            let _ = win.navigator().vibrate_with_duration(ms);
1107        }
1108        _ => {} // unknown capability: ignore
1109    }
1110}
1111
1112/// Append a transient toast to `<body>` (styled by `.toast` in mobiler.css) and
1113/// remove it after ~2.6 s — the web twin of the native toast/snackbar.
1114fn show_toast(text: &str) {
1115    let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
1116    let (Ok(el), Some(body)) = (doc.create_element("div"), doc.body()) else { return };
1117    el.set_class_name("toast");
1118    el.set_text_content(Some(text));
1119    let _ = body.append_child(&el);
1120    gloo_timers::callback::Timeout::new(2600, move || el.remove()).forget();
1121}
1122
1123/// What the `dialog`/`confirm` request asks for (see `mobiler_core::Confirm`); missing fields keep
1124/// the defaults, so a plain `cx.confirm` shows OK / Cancel.
1125struct ConfirmAsk {
1126    title: String,
1127    message: String,
1128    confirm_label: String,
1129    cancel_label: String,
1130    destructive: bool,
1131}
1132
1133impl ConfirmAsk {
1134    fn parse(input: &str) -> Self {
1135        let v: serde_json::Value = serde_json::from_str(input).unwrap_or(serde_json::Value::Null);
1136        let s = |k: &str, d: &str| v.get(k).and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()).unwrap_or(d).to_string();
1137        Self {
1138            title: s("title", ""),
1139            message: s("message", ""),
1140            confirm_label: s("confirm_label", "OK"),
1141            cancel_label: s("cancel_label", "Cancel"),
1142            destructive: v.get("destructive").and_then(serde_json::Value::as_bool).unwrap_or(false),
1143        }
1144    }
1145}
1146
1147/// Per-call counter so the title/message get unique DOM ids for `aria-labelledby` /
1148/// `aria-describedby` to point at, even if a dialog somehow opens while another is still closing.
1149static CONFIRM_DIALOG_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1150
1151/// The web confirm dialog: a modal card on `<body>` that resolves `true` on the confirm button and
1152/// `false` on the cancel button, Escape, or a press-and-release on the backdrop itself (a drag
1153/// that starts on the card and releases over the backdrop does not count). Enter activates the
1154/// focused button (focus starts on cancel for a destructive dialog, else on confirm); whatever had
1155/// focus before the dialog opened gets it back afterwards. Labelled for assistive tech via
1156/// `aria-labelledby`/`aria-describedby` when a title/message is present. Replaces
1157/// `window.confirm`, which can't be relabelled, styled or made accessible this way.
1158async fn confirm_modal(ask: ConfirmAsk) -> bool {
1159    use wasm_bindgen::{closure::Closure, JsCast};
1160    let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return false };
1161    let Some(body) = doc.body() else { return false };
1162    let previously_focused = doc.active_element();
1163    let el = |tag: &str, class: &str| -> Option<web_sys::HtmlElement> {
1164        let e = doc.create_element(tag).ok()?.dyn_into::<web_sys::HtmlElement>().ok()?;
1165        e.set_class_name(class);
1166        Some(e)
1167    };
1168    let confirm_class = if ask.destructive { "btn btn-filled btn-danger" } else { "btn btn-filled" };
1169    let (Some(scrim), Some(card), Some(actions), Some(cancel), Some(confirm)) = (
1170        el("div", "confirm-scrim"),
1171        el("div", "confirm-card"),
1172        el("div", "confirm-actions"),
1173        el("button", "btn btn-text"),
1174        el("button", confirm_class),
1175    ) else {
1176        return false;
1177    };
1178
1179    // Inherit the scaffold's theme: brand vars (inline style) + dark / Large-density classes.
1180    if let Some(scaffold) = doc.query_selector(".scaffold").ok().flatten() {
1181        if let Some(style) = scaffold.get_attribute("style") {
1182            let _ = scrim.set_attribute("style", &style);
1183        }
1184        let classes = scaffold.class_list();
1185        for c in ["theme-dark", "density-large"] {
1186            if classes.contains(c) {
1187                let _ = scrim.class_list().add_1(c);
1188            }
1189        }
1190    }
1191
1192    let _ = card.set_attribute("role", "alertdialog");
1193    let _ = card.set_attribute("aria-modal", "true");
1194    let call_id = CONFIRM_DIALOG_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1195    if !ask.title.is_empty() {
1196        if let Some(title) = el("div", "confirm-title") {
1197            let title_id = format!("mobiler-confirm-title-{call_id}");
1198            title.set_text_content(Some(&ask.title));
1199            let _ = title.set_attribute("id", &title_id);
1200            let _ = card.append_child(&title);
1201            let _ = card.set_attribute("aria-labelledby", &title_id);
1202        }
1203    }
1204    // No message element at all when there's nothing to say — an empty <p> would still get read
1205    // out by a screen reader and wired up as the description.
1206    if !ask.message.is_empty() {
1207        if let Some(message) = el("p", "confirm-message") {
1208            let msg_id = format!("mobiler-confirm-msg-{call_id}");
1209            message.set_text_content(Some(&ask.message));
1210            let _ = message.set_attribute("id", &msg_id);
1211            let _ = card.append_child(&message);
1212            let _ = card.set_attribute("aria-describedby", &msg_id);
1213        }
1214    }
1215    cancel.set_text_content(Some(&ask.cancel_label));
1216    confirm.set_text_content(Some(&ask.confirm_label));
1217    let _ = actions.append_child(&cancel);
1218    let _ = actions.append_child(&confirm);
1219    let _ = card.append_child(&actions);
1220    let _ = scrim.append_child(&card);
1221    let _ = body.append_child(&scrim);
1222    let _ = if ask.destructive { cancel.focus() } else { confirm.focus() };
1223
1224    let (tx, rx) = futures_channel::oneshot::channel::<bool>();
1225    let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
1226    let answer = move |tx: &std::rc::Rc<std::cell::RefCell<Option<futures_channel::oneshot::Sender<bool>>>>, ok: bool| {
1227        if let Some(tx) = tx.borrow_mut().take() {
1228            let _ = tx.send(ok);
1229        }
1230    };
1231    let (t1, t2, t3, t4) = (tx.clone(), tx.clone(), tx.clone(), tx.clone());
1232    let on_cancel = Closure::wrap(Box::new(move || answer(&t1, false)) as Box<dyn FnMut()>);
1233    let on_confirm = Closure::wrap(Box::new(move || answer(&t2, true)) as Box<dyn FnMut()>);
1234
1235    // A drag that starts inside the card and releases over the backdrop (e.g. overshooting while
1236    // selecting the message text) must not read as a backdrop dismiss. `pointerdown` records
1237    // whether the press itself landed on the scrim; `click` (which fires on release, and bubbles
1238    // from whatever was under the pointer) only cancels when both the press and the click target
1239    // were the scrim itself, never a bubbled child.
1240    let press_started_on_scrim = std::rc::Rc::new(std::cell::Cell::new(false));
1241    let scrim_node: web_sys::EventTarget = scrim.clone().into();
1242    let press_flag = press_started_on_scrim.clone();
1243    let pointerdown_target = scrim_node.clone();
1244    let on_pointerdown = Closure::wrap(Box::new(move |e: web_sys::Event| {
1245        press_flag.set(e.target().as_ref() == Some(&pointerdown_target));
1246    }) as Box<dyn FnMut(web_sys::Event)>);
1247    let on_backdrop = Closure::wrap(Box::new(move |e: web_sys::Event| {
1248        if press_started_on_scrim.get() && e.target().as_ref() == Some(&scrim_node) {
1249            answer(&t3, false);
1250        }
1251    }) as Box<dyn FnMut(web_sys::Event)>);
1252    let on_key = Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
1253        if e.key() == "Escape" {
1254            answer(&t4, false);
1255        }
1256    }) as Box<dyn FnMut(web_sys::KeyboardEvent)>);
1257    cancel.set_onclick(Some(on_cancel.as_ref().unchecked_ref()));
1258    confirm.set_onclick(Some(on_confirm.as_ref().unchecked_ref()));
1259    let _ = scrim.add_event_listener_with_callback("pointerdown", on_pointerdown.as_ref().unchecked_ref());
1260    let _ = scrim.add_event_listener_with_callback("click", on_backdrop.as_ref().unchecked_ref());
1261    let _ = doc.add_event_listener_with_callback("keydown", on_key.as_ref().unchecked_ref());
1262
1263    let ok = rx.await.unwrap_or(false);
1264    // A real click sends on `tx` and `confirm_modal` resumes through a microtask while the click
1265    // is still bubbling toward the scrim — the spec runs a microtask checkpoint between listeners
1266    // during a user-initiated dispatch. A listener removed during dispatch is not invoked, so
1267    // detach every one of them (and null out the onclick handlers) before their closures drop
1268    // below; otherwise a click still in flight calls into an already-dropped closure and
1269    // wasm-bindgen throws "closure invoked recursively or after being dropped".
1270    let _ = doc.remove_event_listener_with_callback("keydown", on_key.as_ref().unchecked_ref());
1271    let _ = scrim.remove_event_listener_with_callback("click", on_backdrop.as_ref().unchecked_ref());
1272    let _ = scrim.remove_event_listener_with_callback("pointerdown", on_pointerdown.as_ref().unchecked_ref());
1273    cancel.set_onclick(None);
1274    confirm.set_onclick(None);
1275    scrim.remove();
1276    if let Some(focus_target) = previously_focused.and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok()) {
1277        let _ = focus_target.focus();
1278    }
1279    ok
1280}
1281
1282// ---------------- Widget → DOM ----------------
1283
1284/// `Widget` → DOM. **Exhaustive** by construction — the `match` has no catch-all,
1285/// so (like the Compose/SwiftUI shells) it won't compile until every `Widget`
1286/// variant is handled. Style *intent* (TextStyle, Tone, …) becomes a CSS class;
1287/// the concrete look lives in `mobiler.css`.
1288fn render(widget: &Widget, send: &Dispatch) -> AnyView {
1289    match widget {
1290        // ---- content ----
1291        Widget::Text { content, style } => {
1292            let (class, content) = (text_class(*style), content.clone());
1293            view! { <p class=class>{content}</p> }.into_any()
1294        }
1295        Widget::Image { source, shape, ratio } => {
1296            let (class, source) = (image_class(*shape, *ratio), source.clone());
1297            view! { <img class=class src=source /> }.into_any()
1298        }
1299        Widget::Badge { label, tone } => {
1300            let (class, label) = (format!("badge {}", tone_class(*tone)), label.clone());
1301            view! { <span class=class>{label}</span> }.into_any()
1302        }
1303        Widget::ColorDot { color } => {
1304            view! { <span class=format!("dot {}", dot_class(*color))></span> }.into_any()
1305        }
1306        Widget::Avatar { source, status } => {
1307            let dot = status.map(|t| view! { <span class=format!("avatar-status {}", tone_class(t))></span> });
1308            view! {
1309                <span class="avatar">
1310                    <img class="avatar-img" src=source.clone() />
1311                    {dot}
1312                </span>
1313            }
1314            .into_any()
1315        }
1316        Widget::PdfView { url } => {
1317            // Browsers render PDFs natively in an iframe (remote URL or local blob/file URL).
1318            view! { <iframe class="pdfview" src=url.clone() title="PDF"></iframe> }.into_any()
1319        }
1320        Widget::WebView { url } => {
1321            // General embedded web content (incl. hosted player embeds like Bunny.net). `allow`
1322            // permits autoplay / fullscreen / PiP / encrypted-media so hosted players work.
1323            view! {
1324                <iframe
1325                    class="webview"
1326                    src=url.clone()
1327                    title="Web"
1328                    allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
1329                    allowfullscreen=true
1330                ></iframe>
1331            }.into_any()
1332        }
1333        // Interactive map (MapLibre-GL, no key). The div carries the config as data-* attrs;
1334        // `inject_maplibre_support` inits the map + reports taps by firing `input` on the hidden sink,
1335        // which this `on:input` forwards as Action::Input { "{id}.tap" | "{id}.marker", Text(...) }.
1336        Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive } => {
1337            let send = send.clone();
1338            let id = id.clone();
1339            let center = format!("{center_lat},{center_lng}");
1340            let markers_json = serde_json::to_string(markers).unwrap_or_else(|_| "[]".to_string());
1341            let style = style_url.clone().unwrap_or_default();
1342            view! {
1343                <div class="mobiler-map-wrap">
1344                    <div
1345                        class="mobiler-map"
1346                        data-map="1"
1347                        data-center=center
1348                        data-zoom=zoom.to_string()
1349                        data-style=style
1350                        data-markers=markers_json
1351                        data-interactive=interactive.to_string()
1352                    ></div>
1353                    <input
1354                        class="mobiler-map-sink"
1355                        type="text"
1356                        tabindex="-1"
1357                        aria-hidden="true"
1358                        on:input=move |ev| {
1359                            let raw = event_target_value(&ev);
1360                            if let Some((suffix, value)) = raw.split_once('|') {
1361                                send(Action::Input {
1362                                    id: format!("{id}.{suffix}"),
1363                                    value: InputValue::Text(value.to_string()),
1364                                });
1365                            }
1366                        }
1367                    />
1368                </div>
1369            }.into_any()
1370        }
1371        Widget::Video { url, playing, controls, looping, muted, on_ended, poster, start_at_ms, captions, rate, volume, urls, start_index, .. } => {
1372            // Web = a native-controls `<video>`. App-driven play/pause + seek + position/state events
1373            // are iOS/Android only: the web shell rebuilds the whole tree on each `update`, which would
1374            // reset the element ~every tick — so we don't pump those here (poster/captions/rate/volume
1375            // ARE declarative attributes, so they're safe). `muted && playing` → autoplay. MP4 plays
1376            // everywhere; HLS (.m3u8) plays natively on Safari and, on Chrome/Firefox, via the hls.js
1377            // bootstrap (`inject_hls_support`). A non-empty `urls` is a playlist (best-effort: starts at
1378            // `start_index`, advances on `ended` within this element's lifetime — no index pump back).
1379            use wasm_bindgen::JsCast;
1380            let (send, ended) = (send.clone(), on_ended.clone());
1381            let autoplay = *playing && *muted;
1382            let playlist = urls.clone();
1383            let start_index = (*start_index).max(0) as usize;
1384            let effective = if playlist.is_empty() { url.clone() }
1385                else { playlist.get(start_index).cloned().unwrap_or_else(|| url.clone()) };
1386            let is_hls = effective.to_ascii_lowercase().ends_with(".m3u8");
1387            let src = (!is_hls).then(|| effective.clone());
1388            let hls_src = is_hls.then(|| effective.clone());
1389            let poster_attr = poster.clone();
1390            let start_at = *start_at_ms;
1391            let rate = *rate as f64;
1392            let volume = (*volume as f64).clamp(0.0, 1.0);
1393            let tracks: Vec<_> = captions.iter().map(|c| view! {
1394                <track kind="subtitles" src=c.url.clone() srclang=c.language.clone() label=c.label.clone() default=c.default_on />
1395            }).collect();
1396            let next_idx = std::rc::Rc::new(std::cell::Cell::new(start_index));
1397            view! {
1398                <video
1399                    class="video"
1400                    src=src
1401                    data-hls-src=hls_src
1402                    poster=poster_attr
1403                    controls=*controls
1404                    autoplay=autoplay
1405                    prop:loop=*looping
1406                    prop:playbackRate=rate
1407                    prop:volume=volume
1408                    muted=*muted
1409                    playsinline=true
1410                    on:loadedmetadata=move |ev| {
1411                        if start_at >= 0 {
1412                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1413                                v.set_current_time(start_at as f64 / 1000.0);
1414                            }
1415                        }
1416                    }
1417                    on:ended=move |ev| {
1418                        let nxt = next_idx.get() + 1;
1419                        if !playlist.is_empty() && nxt < playlist.len() {
1420                            next_idx.set(nxt);
1421                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1422                                v.set_src(&playlist[nxt]);
1423                                let _ = v.play();
1424                            }
1425                        } else if let Some(t) = ended.clone() {
1426                            send(Action::Fired { token: t });
1427                        }
1428                    }
1429                >{tracks}</video>
1430            }.into_any()
1431        }
1432        Widget::Rating { value, max, on_rate } => {
1433            let value = *value;
1434            let stars: Vec<AnyView> = (1..=*max)
1435                .map(|i| {
1436                    let threshold = u32::from(i) * 10;
1437                    // filled / half / empty by tenths.
1438                    let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
1439                    match on_rate {
1440                        Some(tokens) => {
1441                            let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
1442                            view! {
1443                                <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
1444                                    {glyph}
1445                                </button>
1446                            }
1447                            .into_any()
1448                        }
1449                        None => view! { <span class="star">{glyph}</span> }.into_any(),
1450                    }
1451                })
1452                .collect();
1453            view! { <span class="rating">{stars}</span> }.into_any()
1454        }
1455        Widget::Divider => view! { <hr class="divider" /> }.into_any(),
1456        Widget::Progress { value } => match value {
1457            Some(v) => {
1458                let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
1459                view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
1460            }
1461            None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
1462        },
1463        Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
1464        Widget::Chart { series, labels, style, axis, legend } => {
1465            chart_view(series, labels, *style, *axis, *legend)
1466        }
1467        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
1468            region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
1469        }
1470        Widget::Calendar { title, weekday_labels, leading_blanks, selected, on_day, markers, .. } => {
1471            let heads: Vec<_> = weekday_labels.iter().map(|w| view! { <div class="cal-head">{w.clone()}</div> }).collect();
1472            let blanks: Vec<_> = (0..*leading_blanks).map(|_| view! { <div class="cal-blank"></div> }).collect();
1473            let selected = *selected;
1474            let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
1475                let day = (i + 1) as u8;
1476                let token = token.clone();
1477                let send = send.clone();
1478                let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
1479                // 0–3 busy-dots under the number; nothing at all for level 0 / no markers.
1480                let level = markers.get(i).copied().unwrap_or(0).min(3);
1481                let dots = (level > 0).then(|| {
1482                    let d: Vec<_> = (0..level).map(|_| view! { <span class="cal-dot"></span> }).collect();
1483                    view! { <span class="cal-dots">{d}</span> }
1484                });
1485                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}{dots}</button> }
1486            }).collect();
1487            view! {
1488                <div class="calendar">
1489                    <div class="cal-title">{title.clone()}</div>
1490                    <div class="cal-grid">{heads}{blanks}{days}</div>
1491                </div>
1492            }.into_any()
1493        }
1494        Widget::SwipeAction { child, actions } => {
1495            // Web has no swipe gesture — render the actions inline as a trailing button row.
1496            let acts: Vec<_> = actions.iter().map(|a| {
1497                let token = a.on_tap.clone();
1498                let send = send.clone();
1499                let cls = format!("swipe-act {}", tone_class(a.tone));
1500                let label = a.label.clone();
1501                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
1502            }).collect();
1503            view! {
1504                <div class="swipe-row">
1505                    <div class="swipe-content">{render(child, send)}</div>
1506                    <div class="swipe-actions">{acts}</div>
1507                </div>
1508            }.into_any()
1509        }
1510        Widget::Spacer { size } => {
1511            view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
1512        }
1513
1514        // ---- layout ----
1515        Widget::Row { children } => {
1516            let kids = render_all(children, send);
1517            view! { <div class="row">{kids}</div> }.into_any()
1518        }
1519        Widget::Column { children } => {
1520            let kids = render_all(children, send);
1521            view! { <div class="col">{kids}</div> }.into_any()
1522        }
1523        Widget::Card { child, style, on_press, on_long_press } => {
1524            let class = format!("card {}", card_class(*style));
1525            let body = render(child, send);
1526            match (on_press, on_long_press) {
1527                // Plain, non-interactive card.
1528                (None, None) => view! { <div class=class>{body}</div> }.into_any(),
1529                // Tappable and/or long-pressable — render a button with the relevant handlers.
1530                (tap, long) => {
1531                    let send = send.clone();
1532                    // Web has no native long-press; shim it with a pointer-hold timer (~500 ms),
1533                    // cancelled on pointerup/leave/cancel. A `long_fired` flag suppresses the
1534                    // click that follows a successful hold so it doesn't also fire the tap.
1535                    let timer: Rc<RefCell<Option<gloo_timers::callback::Timeout>>> =
1536                        Rc::new(RefCell::new(None));
1537                    let long_fired = Rc::new(RefCell::new(false));
1538
1539                    let on_pointerdown = {
1540                        let (send, long, timer, long_fired) =
1541                            (send.clone(), long.clone(), timer.clone(), long_fired.clone());
1542                        move |_: web_sys::PointerEvent| {
1543                            let Some(token) = long.clone() else { return };
1544                            *long_fired.borrow_mut() = false;
1545                            let (send, long_fired) = (send.clone(), long_fired.clone());
1546                            *timer.borrow_mut() = Some(gloo_timers::callback::Timeout::new(
1547                                500,
1548                                move || {
1549                                    *long_fired.borrow_mut() = true;
1550                                    send(Action::Fired { token: token.clone() });
1551                                },
1552                            ));
1553                        }
1554                    };
1555                    let cancel = {
1556                        let timer = timer.clone();
1557                        // Dropping the `Timeout` cancels the pending fire.
1558                        move |_: web_sys::PointerEvent| { timer.borrow_mut().take(); }
1559                    };
1560                    let on_click = {
1561                        let (send, tap, long_fired) = (send.clone(), tap.clone(), long_fired.clone());
1562                        move |_| {
1563                            // Suppress the tap that trails a long-press.
1564                            if std::mem::take(&mut *long_fired.borrow_mut()) {
1565                                return;
1566                            }
1567                            if let Some(token) = tap.clone() {
1568                                send(Action::Fired { token });
1569                            }
1570                        }
1571                    };
1572                    view! {
1573                        <button
1574                            class=format!("{class} card-tappable")
1575                            on:pointerdown=on_pointerdown
1576                            on:pointerup=cancel.clone()
1577                            on:pointerleave=cancel.clone()
1578                            on:pointercancel=cancel
1579                            on:click=on_click
1580                        >
1581                            {body}
1582                        </button>
1583                    }
1584                    .into_any()
1585                }
1586            }
1587        }
1588        // Z-stack. With `scrim`, the first child is a background image, darkened
1589        // by an overlay, and the rest layer on top in light content — the DOM twin
1590        // of the Compose `matchParentSize` scrim / SwiftUI `.overlay` on the image.
1591        Widget::Box { children, align, scrim } => {
1592            let acls = align_class(*align);
1593            if *scrim && children.len() > 1 {
1594                let bg = render(&children[0], send);
1595                let content = render_all(&children[1..], send);
1596                view! {
1597                    <div class=format!("box box-scrim {acls}")>
1598                        {bg}
1599                        <div class="scrim"></div>
1600                        <div class="box-content">{content}</div>
1601                    </div>
1602                }
1603                .into_any()
1604            } else {
1605                let kids = render_all(children, send);
1606                view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
1607            }
1608        }
1609        Widget::Grid { children } => {
1610            let kids = render_all(children, send);
1611            view! { <div class="grid">{kids}</div> }.into_any()
1612        }
1613        Widget::Scroller { children, edge_fade } => {
1614            let kids = render_all(children, send);
1615            if *edge_fade {
1616                view! { <div class="scroller scroller-fade">{kids}<div class="scroller-end"></div></div> }.into_any()
1617            } else {
1618                view! { <div class="scroller">{kids}</div> }.into_any()
1619            }
1620        }
1621        // Two-pane master-detail. CSS does the adapting: wide (`@media min-width:768px`) shows both
1622        // panes side-by-side (back hidden); narrow shows one — primary by default, or detail (+ a
1623        // back chevron) when `data-detail` is set. `show_detail`/`on_back` only matter when narrow.
1624        Widget::Split { primary, detail, show_detail, on_back } => {
1625            let p = render(primary, send);
1626            let d = render(detail, send);
1627            let back_btn = on_back.clone().map(|t| {
1628                let send = send.clone();
1629                view! { <button class="split-back" on:click=move |_| send(Action::Fired { token: t.clone() })>"‹ Back"</button> }
1630            });
1631            view! {
1632                <div class="split" data-detail=show_detail.then_some("1")>
1633                    <div class="split-primary">{p}</div>
1634                    <div class="split-detail">{back_btn}{d}</div>
1635                </div>
1636            }.into_any()
1637        }
1638        // Accessibility wrapper: name the subtree for a screen reader (aria-label), give it a role,
1639        // and the hint via `title`. Best-effort web mapping of iOS traits / Android semantics.
1640        Widget::A11y { child, label, hint, role } => {
1641            let body = render(child, send);
1642            let role_attr = role.map(a11y_role_aria).unwrap_or("group");
1643            view! {
1644                <div class="a11y" role=role_attr aria-label=label.clone() title=hint.clone()>
1645                    {body}
1646                </div>
1647            }.into_any()
1648        }
1649        // A long/paged feed. Web has no pull gesture or reliable infinite-scroll on a sub-container,
1650        // so (like Scaffold pull-to-refresh) the gestures degrade to controls: a top "↻ Refresh"
1651        // button (while `on_refresh`), and a bottom "Load more" button (while `has_more && !loading`)
1652        // / loading bar / the app's end caption (if set). iOS/Android do true pull + scroll-near-end
1653        // detection.
1654        Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label } => {
1655            let kids = render_all(children, send);
1656            let refresh_btn = on_refresh.clone().map(|token| {
1657                let send = send.clone();
1658                view! { <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻ Refresh"</button> }
1659            });
1660            let refresh_bar = refreshing.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1661            let loading_bar = loading.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1662            let load_more_btn = (!*loading && *has_more)
1663                .then(|| on_load_more.clone())
1664                .flatten()
1665                .map(|token| {
1666                    let send = send.clone();
1667                    view! { <button class="btn btn-outlined lazylist-more" on:click=move |_| send(Action::Fired { token: token.clone() })>"Load more"</button> }
1668                });
1669            // The app's own end text (e.g. "Kraj liste"); nothing when it didn't set one.
1670            let end_cap = (!*has_more && on_load_more.is_some())
1671                .then(|| end_label.clone())
1672                .flatten()
1673                .map(|label| view! { <div class="lazylist-end">{label}</div> });
1674            view! {
1675                <div class="lazylist">
1676                    {refresh_btn}
1677                    {refresh_bar}
1678                    {kids}
1679                    {loading_bar}
1680                    {load_more_btn}
1681                    {end_cap}
1682                </div>
1683            }.into_any()
1684        }
1685
1686        // ---- input / actions ----
1687        Widget::Button { label, style, on_press, tone, icon, wide } => {
1688            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1689            // Neutral + not wide keeps the exact original class string.
1690            let mut class = format!("btn {}", button_class(*style));
1691            if *tone != Tone::Neutral {
1692                class.push(' ');
1693                class.push_str(button_tone_class(*tone));
1694            }
1695            if *wide {
1696                class.push_str(" btn-wide");
1697            }
1698            let glyph = icon.map(|i| view! { <span class="btn-icon">{icon_glyph(i)}</span> });
1699            view! {
1700                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1701                    {glyph}
1702                    {label}
1703                </button>
1704            }
1705            .into_any()
1706        }
1707        Widget::IconButton { icon, on_press } => {
1708            let (send, token) = (send.clone(), on_press.clone());
1709            let glyph = icon_glyph(*icon);
1710            view! {
1711                <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
1712                    {glyph}
1713                </button>
1714            }
1715            .into_any()
1716        }
1717        Widget::Chip { label, selected, on_press } => {
1718            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1719            let class = if *selected { "chip selected" } else { "chip" };
1720            view! {
1721                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1722                    {label}
1723                </button>
1724            }
1725            .into_any()
1726        }
1727        Widget::TextField { id, placeholder, value, kind, error } => {
1728            let (send, id) = (send.clone(), id.clone());
1729            let (placeholder, value) = (placeholder.clone(), value.clone());
1730            let invalid = error.is_some();
1731            let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
1732            // (input type, inputmode) per FieldKind. Multiline renders a <textarea> below.
1733            let (itype, imode): (&str, &str) = match kind {
1734                FieldKind::Secure => ("password", ""),
1735                FieldKind::Email => ("email", "email"),
1736                FieldKind::Number => ("text", "numeric"),
1737                FieldKind::Decimal => ("text", "decimal"),
1738                FieldKind::Phone => ("tel", "tel"),
1739                FieldKind::Url => ("url", "url"),
1740                FieldKind::Text | FieldKind::Multiline => ("text", ""),
1741            };
1742            let field_class = if invalid { "field field-invalid" } else { "field" };
1743            let control = if matches!(kind, FieldKind::Multiline) {
1744                view! {
1745                    <textarea
1746                        class=field_class
1747                        rows="3"
1748                        placeholder=placeholder
1749                        prop:value=value
1750                        on:input=move |ev| send(Action::Input {
1751                            id: id.clone(),
1752                            value: InputValue::Text(event_target_value(&ev)),
1753                        })
1754                    ></textarea>
1755                }
1756                .into_any()
1757            } else {
1758                view! {
1759                    <input
1760                        class=field_class
1761                        r#type=itype
1762                        inputmode=imode
1763                        placeholder=placeholder
1764                        prop:value=value
1765                        on:input=move |ev| send(Action::Input {
1766                            id: id.clone(),
1767                            value: InputValue::Text(event_target_value(&ev)),
1768                        })
1769                    />
1770                }
1771                .into_any()
1772            };
1773            view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
1774        }
1775        Widget::SearchField { id, placeholder, value } => {
1776            let (send, id) = (send.clone(), id.clone());
1777            let (placeholder, value) = (placeholder.clone(), value.clone());
1778            view! {
1779                <div class="searchfield">
1780                    <span class="search-icon">{icon_glyph(Icon::Search)}</span>
1781                    <input
1782                        class="search-input"
1783                        placeholder=placeholder
1784                        prop:value=value
1785                        on:input=move |ev| send(Action::Input {
1786                            id: id.clone(),
1787                            value: InputValue::Text(event_target_value(&ev)),
1788                        })
1789                    />
1790                </div>
1791            }
1792            .into_any()
1793        }
1794        Widget::Segmented { segments } => {
1795            let segs: Vec<AnyView> = segments
1796                .iter()
1797                .map(|s| {
1798                    let (send, token) = (send.clone(), s.on_select.clone());
1799                    let class = if s.selected { "segment selected" } else { "segment" };
1800                    let label = s.label.clone();
1801                    view! {
1802                        <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1803                            {label}
1804                        </button>
1805                    }
1806                    .into_any()
1807                })
1808                .collect();
1809            view! { <div class="segmented">{segs}</div> }.into_any()
1810        }
1811        Widget::Toggle { id, label, value } => {
1812            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1813            view! {
1814                <label class="toggle">
1815                    {label}
1816                    <input
1817                        type="checkbox"
1818                        role="switch"
1819                        prop:checked=checked
1820                        on:change=move |ev| send(Action::Input {
1821                            id: id.clone(),
1822                            value: InputValue::Bool(event_target_checked(&ev)),
1823                        })
1824                    />
1825                </label>
1826            }
1827            .into_any()
1828        }
1829        Widget::Checkbox { id, label, value } => {
1830            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1831            view! {
1832                <label class="check">
1833                    <input
1834                        type="checkbox"
1835                        prop:checked=checked
1836                        on:change=move |ev| send(Action::Input {
1837                            id: id.clone(),
1838                            value: InputValue::Bool(event_target_checked(&ev)),
1839                        })
1840                    />
1841                    {label}
1842                </label>
1843            }
1844            .into_any()
1845        }
1846        Widget::Slider { id, value, max } => {
1847            let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
1848            view! {
1849                <input
1850                    class="slider"
1851                    type="range"
1852                    min="0"
1853                    max=max
1854                    prop:value=value
1855                    on:input=move |ev| send(Action::Input {
1856                        id: id.clone(),
1857                        value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
1858                    })
1859                />
1860            }
1861            .into_any()
1862        }
1863        Widget::Stepper { value, on_decrement, on_increment } => {
1864            let send_dec = send.clone();
1865            let send_inc = send.clone();
1866            let (dec, inc) = (on_decrement.clone(), on_increment.clone());
1867            view! {
1868                <div class="stepper">
1869                    <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
1870                    <span class="stepper-value">{*value}</span>
1871                    <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
1872                </div>
1873            }
1874            .into_any()
1875        }
1876
1877        // ---- shell ----
1878        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth } => {
1879            let back_btn = back.clone().map(|token| {
1880                let send = send.clone();
1881                view! {
1882                    <button class="back" on:click=move |_| send(Action::Fired { token: token.clone() })>
1883                        "‹"
1884                    </button>
1885                }
1886            });
1887            let tabbar = (!tabs.is_empty()).then(|| {
1888                let tabs: Vec<AnyView> = tabs
1889                    .iter()
1890                    .map(|tab| {
1891                        let (send, token) = (send.clone(), tab.on_select.clone());
1892                        let class = if tab.selected { "tab selected" } else { "tab" };
1893                        let label = tab.label.clone();
1894                        // Optional leading icon → glyph above the label (icon tab bar).
1895                        let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
1896                        view! {
1897                            <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1898                                {icon}
1899                                <span class="tab-label">{label}</span>
1900                            </button>
1901                        }
1902                        .into_any()
1903                    })
1904                    .collect();
1905                view! { <div class="tabbar">{tabs}</div> }
1906            });
1907            // Floating action button — the raised primary action, anchored over the body.
1908            let fab_btn = fab.clone().map(|f| {
1909                let (send, token) = (send.clone(), f.on_press.clone());
1910                view! {
1911                    <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
1912                        {icon_glyph(f.icon)}
1913                    </button>
1914                }
1915            });
1916            // Modal bottom sheet — a scrim (tap to dismiss) + a panel rising from the bottom.
1917            let sheet_overlay = sheet.as_ref().map(|s| {
1918                let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
1919                let (title, child) = (s.title.clone(), render(&s.child, send));
1920                view! {
1921                    <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
1922                    <div class="sheet">
1923                        <div class="sheet-handle"></div>
1924                        <div class="sheet-title">{title}</div>
1925                        {child}
1926                    </div>
1927                }
1928            });
1929            // `theme-dark` flips the CSS variables for the whole shell — theme-as-data,
1930            // the web twin of the native shells' `preferredColorScheme`/Material theme.
1931            // `density-large` scopes the Density::Large control sizes in mobiler.css.
1932            let large = theme.as_ref().is_some_and(|t| t.density == Density::Large);
1933            let class = format!("scaffold{}{}", if *dark_mode { " theme-dark" } else { "" }, if large { " density-large" } else { "" });
1934            // Pull-to-refresh — web has no pull gesture, so expose a top-bar refresh button +
1935            // an indeterminate bar at the top of the body while `refreshing`.
1936            let refresh_btn = on_refresh.clone().map(|token| {
1937                let send = send.clone();
1938                view! {
1939                    <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
1940                }
1941            });
1942            let refresh_bar = refreshing.then(|| {
1943                view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
1944            });
1945            let body_class = format!("scaffold-body {}", nav_class(route, *depth));
1946            // An app `Theme` overrides the CSS variables inline (brand color, corner, density,
1947            // font) — the web twin of the native shells' brand/tint + shape + spacing + font.
1948            let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
1949            let (title, body) = (title.clone(), render(body, send));
1950            view! {
1951                <div class=class style=theme_style>
1952                    <div class="topbar">
1953                        {back_btn}
1954                        <span class="title">{title}</span>
1955                        {refresh_btn}
1956                    </div>
1957                    <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
1958                    {fab_btn}
1959                    {tabbar}
1960                    {sheet_overlay}
1961                </div>
1962            }
1963            .into_any()
1964        }
1965    }
1966}
1967
1968/// Render a slice of children as sibling views.
1969fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
1970    children.iter().map(|c| render(c, send)).collect()
1971}
1972
1973thread_local! {
1974    /// (previous route key, previous depth, alternating toggle). The render is a
1975    /// stateless whole-tree rebuild, so nav state lives here (wasm is single-
1976    /// threaded). Lets the Scaffold body animate on navigation — the web twin of
1977    /// the native shells keying their body on `route`.
1978    static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
1979
1980    /// Open streaming subscriptions keyed by subscription key (wasm is single-
1981    /// threaded). Each [`Effect::PluginStream`] parks its source here so
1982    /// `cx.unsubscribe(key)` can stop it; dropping the entry stops the source.
1983    static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
1984}
1985
1986/// Render an app [`Theme`] as inline CSS custom properties on the scaffold root — the web
1987/// twin of the native brand/tint + shape + spacing + font. Overrides `mobiler.css`'s defaults
1988/// (its rules read these via `var(--…)`); dark mode still works (it only swaps the colors the
1989/// seed doesn't pin).
1990fn theme_css(t: &Theme) -> String {
1991    let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
1992    let radius = match t.corner {
1993        Corner::None => "0px",
1994        Corner::Small => "8px",
1995        Corner::Medium => "14px",
1996        Corner::Large => "22px",
1997    };
1998    let (gap, pad) = match t.density {
1999        Density::Compact => ("8px", "10px"),
2000        Density::Comfortable => ("12px", "14px"),
2001        Density::Large => ("16px", "18px"),
2002    };
2003    let font = match t.font {
2004        FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
2005        FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
2006        FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
2007        FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
2008    };
2009    // Secondary brand color (for the CardStyle::Brand gradient); falls back to the seed.
2010    let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
2011    format!(
2012        "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
2013         --accent2:rgb({ar},{ag},{ab});\
2014         --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
2015         --gap:{gap};--pad:{pad};--font:{font};"
2016    )
2017}
2018
2019/// Pick the Scaffold body's transition class for this render. Returns `""` for a
2020/// same-route data update (re-render in place, no transition). On a route change it
2021/// returns a directional class — slide-in from the right when `depth` grew (push),
2022/// from the left when it shrank (pop), a crossfade for a lateral move — and *alternates*
2023/// the `-a`/`-b` suffix each navigation so the CSS animation restarts even though
2024/// Leptos reuses the same DOM node.
2025fn nav_class(route: &str, depth: u32) -> &'static str {
2026    NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
2027        if route == prev_route {
2028            return "";
2029        }
2030        let dir = if depth > *prev_depth {
2031            ["nav-push-a", "nav-push-b"]
2032        } else if depth < *prev_depth {
2033            ["nav-pop-a", "nav-pop-b"]
2034        } else {
2035            ["nav-fade-a", "nav-fade-b"]
2036        };
2037        *toggle = !*toggle;
2038        *prev_route = route.to_string();
2039        *prev_depth = depth;
2040        dir[usize::from(*toggle)]
2041    })
2042}
2043
2044// ---- style intent → CSS class / glyph (the only place that names the look) ----
2045
2046fn text_class(s: TextStyle) -> &'static str {
2047    match s {
2048        TextStyle::Title => "t-title",
2049        TextStyle::Subtitle => "t-subtitle",
2050        TextStyle::Caption => "t-caption",
2051        TextStyle::Emphasis => "t-emphasis",
2052        TextStyle::Body => "t-body",
2053    }
2054}
2055
2056fn button_class(s: ButtonStyle) -> &'static str {
2057    match s {
2058        ButtonStyle::Filled => "btn-filled",
2059        ButtonStyle::Outlined => "btn-outlined",
2060        ButtonStyle::Text => "btn-text",
2061        ButtonStyle::Tonal => "btn-tonal",
2062    }
2063}
2064
2065fn button_tone_class(t: Tone) -> &'static str {
2066    match t {
2067        Tone::Neutral => "",
2068        Tone::Success => "btn-success",
2069        Tone::Warning => "btn-warning",
2070        Tone::Danger => "btn-danger",
2071        Tone::Info => "btn-info",
2072    }
2073}
2074
2075fn card_class(s: CardStyle) -> &'static str {
2076    match s {
2077        CardStyle::Elevated => "card-elevated",
2078        CardStyle::Outlined => "card-outlined",
2079        CardStyle::Filled => "card-filled",
2080        CardStyle::Brand => "card-brand",
2081    }
2082}
2083
2084fn a11y_role_aria(role: A11yRole) -> &'static str {
2085    match role {
2086        A11yRole::Button => "button",
2087        A11yRole::Link => "link",
2088        A11yRole::Image => "img",
2089        A11yRole::Header => "heading",
2090        A11yRole::Adjustable => "slider",
2091    }
2092}
2093
2094fn tone_class(t: Tone) -> &'static str {
2095    match t {
2096        Tone::Neutral => "tone-neutral",
2097        Tone::Success => "tone-success",
2098        Tone::Warning => "tone-warning",
2099        Tone::Danger => "tone-danger",
2100        Tone::Info => "tone-info",
2101    }
2102}
2103
2104fn spacer_class(s: Spacing) -> &'static str {
2105    match s {
2106        Spacing::Xs => "sp-xs",
2107        Spacing::Sm => "sp-sm",
2108        Spacing::Md => "sp-md",
2109        Spacing::Lg => "sp-lg",
2110        Spacing::Xl => "sp-xl",
2111    }
2112}
2113
2114fn icon_glyph(i: Icon) -> &'static str {
2115    match i {
2116        Icon::Delete => "🗑",
2117        Icon::Add => "+",
2118        Icon::Edit => "✏️",
2119        Icon::Close => "✕",
2120        Icon::Settings => "⚙",
2121        Icon::Check => "✓",
2122        Icon::Star => "★",
2123        Icon::Info => "ℹ",
2124        Icon::Home => "⌂",
2125        Icon::Search => "🔍",
2126        Icon::Menu => "☰",
2127        Icon::Filter => "⚟",
2128        Icon::Back => "‹",
2129        Icon::Forward => "›",
2130        Icon::Down => "⌄",
2131        Icon::Bell => "🔔",
2132        Icon::Cart => "🛒",
2133        Icon::Share => "↗",
2134        Icon::Heart => "♡",
2135        Icon::HeartFilled => "♥",
2136        Icon::Person => "👤",
2137        Icon::People => "👥",
2138        Icon::Phone => "📞",
2139        Icon::Mail => "✉",
2140        Icon::Calendar => "📅",
2141        Icon::Clock => "🕑",
2142        Icon::MapPin => "📍",
2143        Icon::Camera => "📷",
2144        Icon::Photo => "🖼",
2145        Icon::Play => "▶",
2146        Icon::Scissors => "✂",
2147    }
2148}
2149
2150fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
2151    let shape = match shape {
2152        ImageShape::Square => "img-square",
2153        ImageShape::Rounded => "img-rounded",
2154        ImageShape::Circle => "img-circle",
2155    };
2156    let ratio = match ratio {
2157        ImageRatio::Wide => "ratio-wide",
2158        ImageRatio::Square => "ratio-square",
2159        ImageRatio::Tall => "ratio-tall",
2160    };
2161    format!("img {shape} {ratio}")
2162}
2163
2164fn dot_class(c: ProjectColor) -> &'static str {
2165    match c {
2166        ProjectColor::Indigo => "dot-indigo",
2167        ProjectColor::Teal => "dot-teal",
2168        ProjectColor::Coral => "dot-coral",
2169        ProjectColor::Amber => "dot-amber",
2170        ProjectColor::Lime => "dot-lime",
2171        ProjectColor::Pink => "dot-pink",
2172    }
2173}
2174
2175fn align_class(a: BoxAlign) -> &'static str {
2176    match a {
2177        BoxAlign::TopStart => "align-top-start",
2178        BoxAlign::TopEnd => "align-top-end",
2179        BoxAlign::Center => "align-center",
2180        BoxAlign::BottomStart => "align-bottom-start",
2181        BoxAlign::BottomCenter => "align-bottom-center",
2182        BoxAlign::BottomEnd => "align-bottom-end",
2183    }
2184}
2185
2186// ------------------------------- charts -------------------------------
2187
2188/// Distinct fallback colors for series 1.. (series 0 with no override rides the theme accent).
2189const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
2190
2191fn hex(c: Rgb) -> String {
2192    format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
2193}
2194
2195/// Color for series `i`: explicit override → theme accent (i==0) → palette.
2196fn chart_color(i: usize, s: &ChartSeries) -> String {
2197    match s.color {
2198        Some(c) => hex(c),
2199        None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
2200        None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
2201    }
2202}
2203
2204/// A series' single magnitude for circular charts (sum of its values).
2205fn chart_mag(s: &ChartSeries) -> f32 {
2206    s.values.iter().copied().sum()
2207}
2208
2209/// Point on a circle: `ang` in radians, 0 = top (12 o'clock), increasing clockwise.
2210fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
2211    (cx + r * ang.sin(), cy - r * ang.cos())
2212}
2213
2214/// An open arc path (for ring/donut/gauge strokes).
2215fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
2216    let (x0, y0) = polar(cx, cy, r, a0);
2217    let (x1, y1) = polar(cx, cy, r, a1);
2218    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
2219    format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
2220}
2221
2222/// A filled wedge from the center (for pie/donut slices).
2223fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
2224    let (x0, y0) = polar(cx, cy, r, a0);
2225    let (x1, y1) = polar(cx, cy, r, a1);
2226    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
2227    format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
2228}
2229
2230fn fmt_tick(v: f32) -> String {
2231    if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
2232}
2233
2234fn is_cartesian(style: ChartStyle) -> bool {
2235    matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
2236}
2237
2238/// The y-axis denominator for a cartesian chart.
2239fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
2240    match style {
2241        ChartStyle::StackedBar => (0..nslots)
2242            .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
2243            .fold(0.0, f32::max)
2244            .max(1e-6),
2245        ChartStyle::StackedBar100 => 1.0,
2246        _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
2247    }
2248}
2249
2250fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
2251    // plot area: y in [2, 48] of the 0..50 viewBox
2252    let mut nodes: Vec<AnyView> = Vec::new();
2253    if axis {
2254        for k in 0..=4 {
2255            let y = 2.0 + k as f32 * (46.0 / 4.0);
2256            nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
2257        }
2258    }
2259    match style {
2260        ChartStyle::Line => {
2261            for (i, s) in series.iter().enumerate() {
2262                let n = s.values.len().max(1);
2263                let pts = s.values.iter().enumerate().map(|(j, v)| {
2264                    let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
2265                    let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
2266                    format!("{x:.2},{y:.2}")
2267                }).collect::<Vec<_>>().join(" ");
2268                let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
2269                nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
2270            }
2271        }
2272        ChartStyle::Bar => {
2273            let sw = 100.0 / nslots as f32;
2274            let ns = series.len().max(1);
2275            for (i, s) in series.iter().enumerate() {
2276                let st = format!("fill:{}", chart_color(i, s));
2277                for (j, v) in s.values.iter().enumerate() {
2278                    let h = (v / max).clamp(0.0, 1.0) * 46.0;
2279                    let bw = sw * 0.8 / ns as f32;
2280                    let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
2281                    let y = 48.0 - h;
2282                    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());
2283                }
2284            }
2285        }
2286        ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
2287            let sw = 100.0 / nslots as f32;
2288            for j in 0..nslots {
2289                let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
2290                let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
2291                let mut acc = 0.0_f32;
2292                for (i, s) in series.iter().enumerate() {
2293                    let v = *s.values.get(j).unwrap_or(&0.0);
2294                    let h = (v / denom).clamp(0.0, 1.0) * 46.0;
2295                    let x = j as f32 * sw + sw * 0.15;
2296                    let bw = sw * 0.7;
2297                    let y = 48.0 - acc - h;
2298                    let st = format!("fill:{}", chart_color(i, s));
2299                    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());
2300                    acc += h;
2301                }
2302            }
2303        }
2304        _ => {}
2305    }
2306    view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
2307}
2308
2309fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
2310    use std::f32::consts::PI;
2311    let mut nodes: Vec<AnyView> = Vec::new();
2312    match style {
2313        ChartStyle::Pie | ChartStyle::Donut => {
2314            let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
2315            let mut a = 0.0_f32;
2316            for (i, s) in series.iter().enumerate() {
2317                let frac = chart_mag(s) / total;
2318                let st = format!("fill:{}", chart_color(i, s));
2319                if frac >= 0.999 {
2320                    nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
2321                } else if frac > 0.0 {
2322                    let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
2323                    nodes.push(view! { <path d=d style=st></path> }.into_any());
2324                }
2325                a += frac * 2.0 * PI;
2326            }
2327            if matches!(style, ChartStyle::Donut) {
2328                nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
2329            }
2330        }
2331        ChartStyle::Rings => {
2332            let n = series.len().max(1);
2333            for (i, s) in series.iter().enumerate() {
2334                let r = 45.0 - i as f32 * (34.0 / n as f32);
2335                let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2336                let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2337                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());
2338                let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
2339                if prog >= 0.999 {
2340                    nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
2341                } else if prog > 0.0 {
2342                    let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
2343                    nodes.push(view! { <path d=d style=st></path> }.into_any());
2344                }
2345            }
2346        }
2347        ChartStyle::Gauge => {
2348            let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
2349            let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2350            let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2351            let a0 = -0.75 * PI; // 270° sweep, gap at the bottom
2352            let a1 = 0.75 * PI;
2353            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());
2354            if prog > 0.0 {
2355                let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
2356                nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
2357            }
2358            let pct = format!("{}%", (prog * 100.0).round() as i64);
2359            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());
2360        }
2361        _ => {}
2362    }
2363    view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
2364}
2365
2366fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
2367    let cartesian = is_cartesian(style);
2368    let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
2369    let max = cartesian_max(series, style, nslots);
2370
2371    let plot = if cartesian {
2372        let svg = cartesian_svg(series, style, axis, max, nslots);
2373        let yaxis = if axis {
2374            let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
2375                .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
2376                .collect();
2377            Some(view! { <div class="chart-yaxis">{ticks}</div> })
2378        } else {
2379            None
2380        };
2381        view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
2382    } else {
2383        circular_svg(series, style).into_any()
2384    };
2385
2386    let label_row = if cartesian && !labels.is_empty() {
2387        let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
2388        Some(view! { <div class="chart-labels">{items}</div> })
2389    } else {
2390        None
2391    };
2392
2393    let legend_row = if legend {
2394        let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
2395            let sw = format!("background:{}", chart_color(i, s));
2396            let name = s.name.clone();
2397            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2398        }).collect();
2399        Some(view! { <div class="chart-legend">{items}</div> })
2400    } else {
2401        None
2402    };
2403
2404    view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
2405}
2406
2407// --------------------------- region chart ---------------------------
2408
2409/// Palette as RGB (parallel to `CHART_PALETTE`) so region charts can compute label contrast.
2410const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
2411    [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
2412
2413/// The resolved fill RGB for region `i` (explicit override → palette).
2414fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
2415    match r.color {
2416        Some(c) => (c.r, c.g, c.b),
2417        None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
2418    }
2419}
2420
2421/// Black or white label text, whichever reads on the given fill (perceived luminance).
2422fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
2423    let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
2424    if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
2425}
2426
2427fn region_color(i: usize, r: &ChartRegion) -> String {
2428    let (r8, g8, b8) = region_rgb(i, r);
2429    format!("#{r8:02x}{g8:02x}{b8:02x}")
2430}
2431
2432// A variable-width stacked-region / coverage-gap chart: absolute-positioned region rectangles in
2433// the [0,x_max]×[0,y_max] plane, horizontal ref lines + chips, an irregular x-axis, an optional
2434// right-side bracket, and a legend. The web twin of the Compose/SwiftUI RegionChart renderers.
2435fn region_chart_view(
2436    regions: &[ChartRegion],
2437    ticks: &[ChartTick],
2438    x_max: f32,
2439    y_max: f32,
2440    ref_lines: &[ChartRefLine],
2441    bracket: &Option<ChartBracket>,
2442    legend: &[ChartLegendItem],
2443) -> AnyView {
2444    let xm = x_max.max(1e-6);
2445    let ym = y_max.max(1e-6);
2446
2447    let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
2448        let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
2449        let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
2450        let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
2451        let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
2452        let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
2453        let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
2454        let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
2455        let label = r.label.clone();
2456        view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
2457    }).collect();
2458
2459    // The reference lines span the full plot width; their value chips sit in the right margin
2460    // (outside the plot), like the original — so the line clearly runs to the plot's edge.
2461    let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
2462        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2463        let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
2464        view! { <div class=cls style=style></div> }
2465    }).collect();
2466    let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
2467        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2468        let label = rl.label.clone();
2469        view! { <div class="rchart-chip" style=style>{label}</div> }
2470    }).collect();
2471
2472    let bracket_div = bracket.as_ref().map(|b| {
2473        let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
2474        let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
2475        let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
2476        let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
2477        view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
2478    });
2479
2480    let yticks: Vec<_> = (0..=4).rev().map(|k| {
2481        let v = ym * k as f32 / 4.0;
2482        view! { <span class="chart-tick">{fmt_tick(v)}</span> }
2483    }).collect();
2484
2485    let xticks: Vec<_> = ticks.iter().map(|t| {
2486        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2487        let label = t.label.clone();
2488        view! { <span class="rchart-xtick" style=style>{label}</span> }
2489    }).collect();
2490
2491    // Axis tick marks (notches on the L-shaped axis): horizontal on the y-axis at each value,
2492    // vertical on the x-axis at each irregular break — drawn over the bands at the plot edges.
2493    let ytick_marks: Vec<_> = (0..=4).map(|k| {
2494        let style = format!("bottom:{:.3}%", k as f32 * 25.0);
2495        view! { <div class="rchart-ytick" style=style></div> }
2496    }).collect();
2497    let xtick_marks: Vec<_> = ticks.iter().map(|t| {
2498        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2499        view! { <div class="rchart-xtickmark" style=style></div> }
2500    }).collect();
2501
2502    let legend_row = if legend.is_empty() {
2503        None
2504    } else {
2505        let items: Vec<_> = legend.iter().map(|l| {
2506            let sw = format!("background:{}", hex(l.color));
2507            let name = l.label.clone();
2508            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2509        }).collect();
2510        Some(view! { <div class="chart-legend">{items}</div> })
2511    };
2512
2513    view! {
2514        <div class="rchart">
2515            <div class="rchart-row">
2516                <div class="rchart-yaxis">{yticks}</div>
2517                <div class="rchart-plotwrap">
2518                    <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
2519                    {chip_divs}{bracket_div}
2520                </div>
2521            </div>
2522            <div class="rchart-xaxis">{xticks}</div>
2523            {legend_row}
2524        </div>
2525    }.into_any()
2526}