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    Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
26    ChartSeries, ChartStyle, ChartTick, Corner, Density, Effect, FieldKind, FontFamily, Icon,
27    ImageRatio, ImageShape, InputValue, PluginCall, PluginNotify, PluginResponse, PluginStreamCall, ProjectColor,
28    Rgb, Spacing, TextStyle, Theme, Tone, 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    leptos::mount::mount_to_body(shell::<A>);
68}
69
70/// hls.js bootstrap for HLS (`.m3u8`) playback in browsers without native HLS
71/// (Chrome/Firefox — Safari/iOS play HLS natively). A `<video>` whose source is an
72/// `.m3u8` is rendered with `data-hls-src` and no `src`; this self-contained script
73/// watches the DOM (a `MutationObserver`, so it also catches elements re-rendered on
74/// each `update`) and, for each such `<video>`, either sets `src` directly (native
75/// HLS, e.g. Safari) or lazily loads hls.js from a CDN and attaches it. If the CDN
76/// fails it falls back to a plain `src`. Inert until an `.m3u8` `Video` appears, so
77/// MP4/Bunny content (and non-video apps) pay nothing. Bunny content keeps using its
78/// own player via `WebView`; this is for raw non-Bunny `.m3u8` on Chrome/Firefox.
79fn inject_hls_support() {
80    const BOOTSTRAP: &str = r#"(function(){
81  function ensureHls(cb){
82    if(window.Hls){return cb();}
83    if(window.__mobilerHlsLoading){(window.__mobilerHlsCbs=window.__mobilerHlsCbs||[]).push(cb);return;}
84    window.__mobilerHlsLoading=true;window.__mobilerHlsCbs=[cb];
85    var s=document.createElement('script');
86    s.src='https://cdn.jsdelivr.net/npm/hls.js@1';
87    var flush=function(){var cbs=window.__mobilerHlsCbs||[];window.__mobilerHlsCbs=[];cbs.forEach(function(f){f();});};
88    s.onload=flush;s.onerror=flush;
89    document.head.appendChild(s);
90  }
91  function attach(v){
92    if(v.__mobilerHlsDone){return;}v.__mobilerHlsDone=true;
93    var url=v.getAttribute('data-hls-src');if(!url){return;}
94    if(v.canPlayType('application/vnd.apple.mpegurl')){v.src=url;return;}
95    ensureHls(function(){
96      if(window.Hls&&window.Hls.isSupported()){var h=new window.Hls();h.loadSource(url);h.attachMedia(v);v.__mobilerHls=h;}
97      else{v.src=url;}
98    });
99  }
100  function scan(root){if(root&&root.querySelectorAll){root.querySelectorAll('video[data-hls-src]').forEach(attach);}}
101  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});
102  scan(document);
103})();"#;
104    let document = leptos::prelude::document();
105    let Some(head) = document.head() else { return };
106    let Ok(script) = document.create_element("script") else { return };
107    script.set_text_content(Some(BOOTSTRAP));
108    let _ = head.append_child(&script);
109}
110
111/// Inject the shell's default stylesheet at the **front** of `<head>` so it's the
112/// lowest-precedence baseline: an app that ships its own CSS (later in the document)
113/// overrides any of these classes, while an app with no CSS still gets a full theme.
114fn inject_default_style() {
115    let document = leptos::prelude::document();
116    let Some(head) = document.head() else { return };
117    let Ok(style) = document.create_element("style") else { return };
118    let _ = style.set_attribute("data-mobiler", "shell");
119    style.set_text_content(Some(STYLE));
120    let _ = head.insert_before(&style, head.first_child().as_ref());
121}
122
123fn shell<A: WebApp>() -> impl IntoView
124where
125    A::Model: Default + Send + Sync,
126{
127    let core = Arc::new(Core::<A>::new());
128    let (view, set_view) = signal(core.view());
129
130    let send: Dispatch = {
131        let core = core.clone();
132        Arc::new(move |action: Action| {
133            let effects = core.process_event(action);
134            drive(&core, set_view, effects);
135        })
136    };
137
138    // Restore persisted state (localStorage), then fire Start — mirrors the native
139    // shells (which restore before Start so the app sees its saved Model on launch).
140    let saved = local_storage().and_then(|s| s.get_item(STORAGE_KEY).ok().flatten()).unwrap_or_default();
141    if !saved.is_empty() {
142        send(Action::Restore { data: saved });
143    }
144    send(Action::Start);
145
146    let send_for_view = send.clone();
147    view! {
148        <div class="app">
149            {move || render(&view.get(), &send_for_view)}
150        </div>
151    }
152}
153
154/// Process effects: re-read the view on Render; fulfil HTTP via fetch and resolve.
155fn drive<A: WebApp>(core: &Arc<Core<A>>, set_view: WriteSignal<Widget>, effects: Vec<Effect>)
156where
157    A::Model: Default + Send + Sync,
158{
159    for effect in effects {
160        match effect {
161            Effect::Render(_) => set_view.set(core.view()),
162            Effect::PluginNotify(notify) => perform_notify(&notify.operation),
163            Effect::Plugin(mut request) => {
164                let core = core.clone();
165                spawn_local(async move {
166                    let response = perform(&request.operation).await;
167                    if let Ok(next) = core.resolve(&mut request, response) {
168                        drive(&core, set_view, next);
169                    }
170                });
171            }
172            // Long-lived subscription: start a native source that resolves the same
173            // request repeatedly (one event per `core.resolve`). See `start_stream`.
174            Effect::PluginStream(request) => start_stream(core, set_view, request),
175        }
176    }
177}
178
179/// Start a streaming subscription ([`Effect::PluginStream`]): begin a native source
180/// that resolves `request` **repeatedly** (a [`PluginResponse`] per event), each
181/// resolution re-entering the core. The source handle is parked in a per-key
182/// registry so [`unsubscribe`](mobiler_core::Cx::unsubscribe) can stop it.
183///
184/// Web sources: `ticker`/`start` (a `setInterval` emitting an incrementing counter
185/// every `input` ms — the deterministic demonstrator) and `websocket`/`stream`
186/// (a `WebSocket`, a frame per `onmessage`).
187fn start_stream<A: WebApp>(
188    core: &Arc<Core<A>>,
189    set_view: WriteSignal<Widget>,
190    request: Request<PluginStreamCall>,
191) where
192    A::Model: Default + Send + Sync,
193{
194    use wasm_bindgen::{closure::Closure, JsCast};
195
196    let call = request.operation.clone();
197
198    // Each resolution of a `resolves_many_times` request yields the next stream item;
199    // share the request across event closures via Rc<RefCell<_>>.
200    let request = Rc::new(RefCell::new(request));
201    let core = core.clone();
202    let emit = move |resp: PluginResponse| {
203        if let Ok(next) = core.resolve(&mut *request.borrow_mut(), resp) {
204            drive(&core, set_view, next);
205        }
206    };
207
208    let handle = match (call.plugin.as_str(), call.op.as_str()) {
209        // Built-in deterministic demonstrator: emit an incrementing counter every
210        // `input` ms. Dropping the Interval (on unsubscribe) stops it.
211        ("ticker", "start") => {
212            let ms: u32 = call.input.parse().unwrap_or(1000);
213            let count = std::cell::Cell::new(0u32);
214            let interval = gloo_timers::callback::Interval::new(ms, move || {
215                count.set(count.get() + 1);
216                emit(PluginResponse { ok: true, output: count.get().to_string() });
217            });
218            StreamHandle::Ticker { _interval: interval }
219        }
220        ("websocket", "stream") => {
221            let Ok(ws) = web_sys::WebSocket::new(&call.input) else { return };
222            let onmessage = {
223                let emit = emit.clone();
224                Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
225                    emit(PluginResponse { ok: true, output: e.data().as_string().unwrap_or_default() });
226                })
227            };
228            let onclose = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_e| {
229                emit(PluginResponse { ok: false, output: "closed".into() });
230            });
231            ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
232            ws.set_onclose(Some(onclose.as_ref().unchecked_ref()));
233            StreamHandle::Ws(WsStream { ws, _onmessage: onmessage, _onclose: onclose })
234        }
235        _ => return, // unknown / native-only source — ignore on web
236    };
237
238    STREAMS.with(|m| {
239        m.borrow_mut().insert(call.key.clone(), handle);
240    });
241}
242
243/// An open streaming source, parked by subscription key for teardown. Dropping the
244/// entry stops the source (the `Interval` cancels on drop; the `WebSocket` is closed
245/// explicitly in the `unsubscribe` handler and its closures drop here).
246enum StreamHandle {
247    /// A `ticker` interval — held only so dropping it (on unsubscribe) cancels it.
248    Ticker { _interval: gloo_timers::callback::Interval },
249    Ws(WsStream),
250}
251
252/// An open web `WebSocket` subscription — holds its JS closures so they stay alive.
253struct WsStream {
254    ws: web_sys::WebSocket,
255    _onmessage: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::MessageEvent)>,
256    _onclose: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::CloseEvent)>,
257}
258
259/// Fulfil a request/response capability. `http` via `fetch`; `device` via the
260/// browser's user-agent string (the web analogue of a device model).
261async fn perform(call: &PluginCall) -> PluginResponse {
262    if call.plugin == "device" {
263        let nav = web_sys::window().map(|w| w.navigator());
264        let output = if call.op == "locale" {
265            // The browser's preferred language as a BCP-47 tag (e.g. "de-CH").
266            nav.and_then(|n| n.language()).unwrap_or_else(|| "en-US".into())
267        } else {
268            nav.and_then(|n| n.user_agent().ok()).unwrap_or_default()
269        };
270        return PluginResponse { ok: true, output };
271    }
272    if call.plugin == "photo" && call.op == "pick" {
273        return take_image(false).await;
274    }
275    if call.plugin == "camera" && call.op == "capture" {
276        return take_image(true).await;
277    }
278    if call.plugin == "datetime" {
279        return match call.op.as_str() {
280            "date" => take_datetime("date").await,
281            "time" => take_datetime("time").await,
282            other => PluginResponse { ok: false, output: format!("unknown datetime op '{other}'") },
283        };
284    }
285    if call.plugin == "dialog" && call.op == "confirm" {
286        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
287        let title = v.get("title").and_then(serde_json::Value::as_str).unwrap_or("");
288        let message = v.get("message").and_then(serde_json::Value::as_str).unwrap_or("");
289        let prompt = if title.is_empty() { message.to_string() } else { format!("{title}\n\n{message}") };
290        let ok = web_sys::window()
291            .and_then(|w| w.confirm_with_message(&prompt).ok())
292            .unwrap_or(false);
293        return PluginResponse { ok, output: if ok { "ok".into() } else { "cancel".into() } };
294    }
295    if call.plugin != "http" {
296        return PluginResponse { ok: false, output: format!("plugin '{}' not available", call.plugin) };
297    }
298    let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
299    let url = v.get("url").and_then(serde_json::Value::as_str).unwrap_or("");
300    let body = v.get("body").and_then(serde_json::Value::as_str);
301
302    use gloo_net::http::Request;
303    let builder = match call.op.as_str() {
304        "POST" => Request::post(url),
305        "PATCH" => Request::patch(url),
306        "DELETE" => Request::delete(url),
307        _ => Request::get(url),
308    };
309    let request = match body {
310        Some(b) => builder.header("Content-Type", "application/json").body(b),
311        None => builder.build(),
312    };
313    let request = match request {
314        Ok(r) => r,
315        Err(e) => return PluginResponse { ok: false, output: e.to_string() },
316    };
317    match request.send().await {
318        Ok(resp) => PluginResponse { ok: resp.ok(), output: resp.text().await.unwrap_or_default() },
319        Err(e) => PluginResponse { ok: false, output: e.to_string() },
320    }
321}
322
323/// Pick or capture an image via a hidden `<input type=file accept=image/*>`, clicked
324/// to open the browser's file dialog — or, with `capture`, to hint the device camera on
325/// supporting mobile browsers (desktop falls back to the file dialog). Awaits the
326/// `change` event and returns a `blob:` object URL the `<img>` renderer loads. No
327/// permission needed (the picker/camera prompt is the browser's). Backs both the
328/// `photo`/`pick` and `camera`/`capture` capabilities.
329async fn take_image(capture: bool) -> PluginResponse {
330    use wasm_bindgen::{closure::Closure, JsCast};
331    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
332        return PluginResponse { ok: false, output: "no document".into() };
333    };
334    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
335        return PluginResponse { ok: false, output: "no input element".into() };
336    };
337    input.set_type("file");
338    input.set_accept("image/*");
339    if capture {
340        // Hints the environment-facing camera on mobile browsers that support it.
341        let _ = input.set_attribute("capture", "environment");
342    }
343
344    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
345    let tx = std::cell::RefCell::new(Some(tx));
346    let input_for_cb = input.clone();
347    let on_change = Closure::wrap(Box::new(move || {
348        let url = input_for_cb
349            .files()
350            .and_then(|files| files.get(0))
351            .and_then(|file| web_sys::Url::create_object_url_with_blob(&file).ok());
352        if let Some(tx) = tx.borrow_mut().take() {
353            let _ = tx.send(url);
354        }
355    }) as Box<dyn FnMut()>);
356    input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
357    input.click();
358    on_change.forget(); // keep the handler alive until `change` fires
359
360    match rx.await {
361        Ok(Some(url)) => PluginResponse { ok: true, output: url },
362        _ => PluginResponse { ok: false, output: "cancelled".into() },
363    }
364}
365
366/// Pick a date (`kind = "date"`) or time (`kind = "time"`) via a hidden native
367/// `<input>`, opening the browser's picker with `showPicker()`. Returns the value
368/// (`YYYY-MM-DD` for date, 24-hour `HH:MM` for time); `ok=false` on cancel/dismiss.
369/// Backs the `datetime` capability (`cx.pick_date` / `cx.pick_time`).
370async fn take_datetime(kind: &str) -> PluginResponse {
371    use wasm_bindgen::{closure::Closure, JsCast};
372    let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
373        return PluginResponse { ok: false, output: "no document".into() };
374    };
375    let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
376        return PluginResponse { ok: false, output: "no input element".into() };
377    };
378    input.set_type(kind); // "date" or "time"
379    // showPicker() needs a connected element; keep it in the DOM but out of sight.
380    let _ = input.set_attribute("style", "position:fixed;left:-9999px;opacity:0");
381    if let Some(body) = doc.body() {
382        let _ = body.append_child(&input);
383    }
384
385    let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
386    let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
387    let input_for_change = input.clone();
388    let tx_change = tx.clone();
389    let on_change = Closure::wrap(Box::new(move || {
390        let v = input_for_change.value();
391        if let Some(tx) = tx_change.borrow_mut().take() {
392            let _ = tx.send(if v.is_empty() { None } else { Some(v) });
393        }
394    }) as Box<dyn FnMut()>);
395    let tx_cancel = tx.clone();
396    let on_cancel = Closure::wrap(Box::new(move || {
397        if let Some(tx) = tx_cancel.borrow_mut().take() {
398            let _ = tx.send(None);
399        }
400    }) as Box<dyn FnMut()>);
401    let _ = input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref());
402    let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref());
403    if input.show_picker().is_err() {
404        input.click(); // older browsers: focus the field so the user can type a value
405    }
406    on_change.forget(); // keep the handlers alive until an event fires
407    on_cancel.forget();
408
409    let result = rx.await;
410    input.remove();
411    match result {
412        Ok(Some(v)) => PluginResponse { ok: true, output: v },
413        _ => PluginResponse { ok: false, output: "cancelled".into() },
414    }
415}
416
417const STORAGE_KEY: &str = "mobiler.state";
418
419/// `window.localStorage`, if available.
420fn local_storage() -> Option<web_sys::Storage> {
421    web_sys::window()?.local_storage().ok().flatten()
422}
423
424/// Fulfil a fire-and-forget capability in the browser — the web twin of the native
425/// shells' notify handlers (storage/clipboard/share/browser). None block; an unknown
426/// capability is a graceful no-op.
427fn perform_notify(notify: &PluginNotify) {
428    let win = match web_sys::window() {
429        Some(w) => w,
430        None => return,
431    };
432    match (notify.plugin.as_str(), notify.op.as_str()) {
433        // Persist the state blob (paired with cx.save + restore-on-startup above).
434        ("storage", "save") => {
435            if let Some(s) = local_storage() {
436                let _ = s.set_item(STORAGE_KEY, &notify.input);
437            }
438        }
439        // Copy to the clipboard (write_text returns a Promise we let run).
440        ("clipboard", "copy") => {
441            let _ = win.navigator().clipboard().write_text(&notify.input);
442        }
443        // Open a URL in a new tab.
444        ("browser", "open") => {
445            let _ = win.open_with_url_and_target(&notify.input, "_blank");
446        }
447        // No reliable cross-browser share sheet (navigator.share is mobile-only and
448        // gesture-gated), so degrade to copying — a sane universal fallback.
449        ("share", _) => {
450            let _ = win.navigator().clipboard().write_text(&notify.input);
451        }
452        // Tear down a streaming subscription: close the WebSocket parked under this
453        // key (input = the subscription key) and drop its closures. Paired with
454        // cx.unsubscribe; the matching source was opened in `start_stream`.
455        ("stream", "unsubscribe") => {
456            // Removing the entry drops the source (a `ticker` Interval cancels on
457            // drop); for a WebSocket we also close it explicitly.
458            if let Some(StreamHandle::Ws(ws)) = STREAMS.with(|m| m.borrow_mut().remove(&notify.input)) {
459                let _ = ws.ws.close();
460            }
461        }
462        // Transient toast: a styled div appended to <body>, auto-removed after a beat.
463        ("toast", _) => show_toast(&notify.input),
464        // Haptic tap. navigator.vibrate is unsupported on iOS Safari (a graceful no-op).
465        ("haptics", style) => {
466            let ms = match style {
467                "light" => 15,
468                "heavy" => 50,
469                _ => 30, // medium / unknown
470            };
471            let _ = win.navigator().vibrate_with_duration(ms);
472        }
473        _ => {} // unknown capability: ignore
474    }
475}
476
477/// Append a transient toast to `<body>` (styled by `.toast` in mobiler.css) and
478/// remove it after ~2.6 s — the web twin of the native toast/snackbar.
479fn show_toast(text: &str) {
480    let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
481    let (Ok(el), Some(body)) = (doc.create_element("div"), doc.body()) else { return };
482    el.set_class_name("toast");
483    el.set_text_content(Some(text));
484    let _ = body.append_child(&el);
485    gloo_timers::callback::Timeout::new(2600, move || el.remove()).forget();
486}
487
488// ---------------- Widget → DOM ----------------
489
490/// `Widget` → DOM. **Exhaustive** by construction — the `match` has no catch-all,
491/// so (like the Compose/SwiftUI shells) it won't compile until every `Widget`
492/// variant is handled. Style *intent* (TextStyle, Tone, …) becomes a CSS class;
493/// the concrete look lives in `mobiler.css`.
494fn render(widget: &Widget, send: &Dispatch) -> AnyView {
495    match widget {
496        // ---- content ----
497        Widget::Text { content, style } => {
498            let (class, content) = (text_class(*style), content.clone());
499            view! { <p class=class>{content}</p> }.into_any()
500        }
501        Widget::Image { source, shape, ratio } => {
502            let (class, source) = (image_class(*shape, *ratio), source.clone());
503            view! { <img class=class src=source /> }.into_any()
504        }
505        Widget::Badge { label, tone } => {
506            let (class, label) = (format!("badge {}", tone_class(*tone)), label.clone());
507            view! { <span class=class>{label}</span> }.into_any()
508        }
509        Widget::ColorDot { color } => {
510            view! { <span class=format!("dot {}", dot_class(*color))></span> }.into_any()
511        }
512        Widget::Avatar { source, status } => {
513            let dot = status.map(|t| view! { <span class=format!("avatar-status {}", tone_class(t))></span> });
514            view! {
515                <span class="avatar">
516                    <img class="avatar-img" src=source.clone() />
517                    {dot}
518                </span>
519            }
520            .into_any()
521        }
522        Widget::PdfView { url } => {
523            // Browsers render PDFs natively in an iframe (remote URL or local blob/file URL).
524            view! { <iframe class="pdfview" src=url.clone() title="PDF"></iframe> }.into_any()
525        }
526        Widget::WebView { url } => {
527            // General embedded web content (incl. hosted player embeds like Bunny.net). `allow`
528            // permits autoplay / fullscreen / PiP / encrypted-media so hosted players work.
529            view! {
530                <iframe
531                    class="webview"
532                    src=url.clone()
533                    title="Web"
534                    allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
535                    allowfullscreen=true
536                ></iframe>
537            }.into_any()
538        }
539        Widget::Video { url, playing, controls, looping, muted, on_ended, poster, start_at_ms, captions, rate, volume, urls, start_index, .. } => {
540            // Web = a native-controls `<video>`. App-driven play/pause + seek + position/state events
541            // are iOS/Android only: the web shell rebuilds the whole tree on each `update`, which would
542            // reset the element ~every tick — so we don't pump those here (poster/captions/rate/volume
543            // ARE declarative attributes, so they're safe). `muted && playing` → autoplay. MP4 plays
544            // everywhere; HLS (.m3u8) plays natively on Safari and, on Chrome/Firefox, via the hls.js
545            // bootstrap (`inject_hls_support`). A non-empty `urls` is a playlist (best-effort: starts at
546            // `start_index`, advances on `ended` within this element's lifetime — no index pump back).
547            use wasm_bindgen::JsCast;
548            let (send, ended) = (send.clone(), on_ended.clone());
549            let autoplay = *playing && *muted;
550            let playlist = urls.clone();
551            let start_index = (*start_index).max(0) as usize;
552            let effective = if playlist.is_empty() { url.clone() }
553                else { playlist.get(start_index).cloned().unwrap_or_else(|| url.clone()) };
554            let is_hls = effective.to_ascii_lowercase().ends_with(".m3u8");
555            let src = (!is_hls).then(|| effective.clone());
556            let hls_src = is_hls.then(|| effective.clone());
557            let poster_attr = poster.clone();
558            let start_at = *start_at_ms;
559            let rate = *rate as f64;
560            let volume = (*volume as f64).clamp(0.0, 1.0);
561            let tracks: Vec<_> = captions.iter().map(|c| view! {
562                <track kind="subtitles" src=c.url.clone() srclang=c.language.clone() label=c.label.clone() default=c.default_on />
563            }).collect();
564            let next_idx = std::rc::Rc::new(std::cell::Cell::new(start_index));
565            view! {
566                <video
567                    class="video"
568                    src=src
569                    data-hls-src=hls_src
570                    poster=poster_attr
571                    controls=*controls
572                    autoplay=autoplay
573                    prop:loop=*looping
574                    prop:playbackRate=rate
575                    prop:volume=volume
576                    muted=*muted
577                    playsinline=true
578                    on:loadedmetadata=move |ev| {
579                        if start_at >= 0 {
580                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
581                                v.set_current_time(start_at as f64 / 1000.0);
582                            }
583                        }
584                    }
585                    on:ended=move |ev| {
586                        let nxt = next_idx.get() + 1;
587                        if !playlist.is_empty() && nxt < playlist.len() {
588                            next_idx.set(nxt);
589                            if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
590                                v.set_src(&playlist[nxt]);
591                                let _ = v.play();
592                            }
593                        } else if let Some(t) = ended.clone() {
594                            send(Action::Fired { token: t });
595                        }
596                    }
597                >{tracks}</video>
598            }.into_any()
599        }
600        Widget::Rating { value, max, on_rate } => {
601            let value = *value;
602            let stars: Vec<AnyView> = (1..=*max)
603                .map(|i| {
604                    let threshold = u32::from(i) * 10;
605                    // filled / half / empty by tenths.
606                    let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
607                    match on_rate {
608                        Some(tokens) => {
609                            let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
610                            view! {
611                                <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
612                                    {glyph}
613                                </button>
614                            }
615                            .into_any()
616                        }
617                        None => view! { <span class="star">{glyph}</span> }.into_any(),
618                    }
619                })
620                .collect();
621            view! { <span class="rating">{stars}</span> }.into_any()
622        }
623        Widget::Divider => view! { <hr class="divider" /> }.into_any(),
624        Widget::Progress { value } => match value {
625            Some(v) => {
626                let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
627                view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
628            }
629            None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
630        },
631        Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
632        Widget::Chart { series, labels, style, axis, legend } => {
633            chart_view(series, labels, *style, *axis, *legend)
634        }
635        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
636            region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
637        }
638        Widget::Calendar { year, month, first_weekday, selected, on_day } => {
639            const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June",
640                "July", "August", "September", "October", "November", "December"];
641            let head_label = format!("{} {year}", MONTHS.get((*month as usize).saturating_sub(1)).copied().unwrap_or(""));
642            let weekdays = ["S", "M", "T", "W", "T", "F", "S"];
643            let heads: Vec<_> = weekdays.iter().map(|w| view! { <div class="cal-head">{*w}</div> }).collect();
644            let blanks: Vec<_> = (0..*first_weekday).map(|_| view! { <div class="cal-blank"></div> }).collect();
645            let selected = *selected;
646            let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
647                let day = (i + 1) as u8;
648                let token = token.clone();
649                let send = send.clone();
650                let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
651                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}</button> }
652            }).collect();
653            view! {
654                <div class="calendar">
655                    <div class="cal-title">{head_label}</div>
656                    <div class="cal-grid">{heads}{blanks}{days}</div>
657                </div>
658            }.into_any()
659        }
660        Widget::SwipeAction { child, actions } => {
661            // Web has no swipe gesture — render the actions inline as a trailing button row.
662            let acts: Vec<_> = actions.iter().map(|a| {
663                let token = a.on_tap.clone();
664                let send = send.clone();
665                let cls = format!("swipe-act {}", tone_class(a.tone));
666                let label = a.label.clone();
667                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
668            }).collect();
669            view! {
670                <div class="swipe-row">
671                    <div class="swipe-content">{render(child, send)}</div>
672                    <div class="swipe-actions">{acts}</div>
673                </div>
674            }.into_any()
675        }
676        Widget::Spacer { size } => {
677            view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
678        }
679
680        // ---- layout ----
681        Widget::Row { children } => {
682            let kids = render_all(children, send);
683            view! { <div class="row">{kids}</div> }.into_any()
684        }
685        Widget::Column { children } => {
686            let kids = render_all(children, send);
687            view! { <div class="col">{kids}</div> }.into_any()
688        }
689        Widget::Card { child, style, on_press } => {
690            let class = format!("card {}", card_class(*style));
691            let body = render(child, send);
692            match on_press {
693                Some(token) => {
694                    let (send, token) = (send.clone(), token.clone());
695                    view! {
696                        <button
697                            class=format!("{class} card-tappable")
698                            on:click=move |_| send(Action::Fired { token: token.clone() })
699                        >
700                            {body}
701                        </button>
702                    }
703                    .into_any()
704                }
705                None => view! { <div class=class>{body}</div> }.into_any(),
706            }
707        }
708        // Z-stack. With `scrim`, the first child is a background image, darkened
709        // by an overlay, and the rest layer on top in light content — the DOM twin
710        // of the Compose `matchParentSize` scrim / SwiftUI `.overlay` on the image.
711        Widget::Box { children, align, scrim } => {
712            let acls = align_class(*align);
713            if *scrim && children.len() > 1 {
714                let bg = render(&children[0], send);
715                let content = render_all(&children[1..], send);
716                view! {
717                    <div class=format!("box box-scrim {acls}")>
718                        {bg}
719                        <div class="scrim"></div>
720                        <div class="box-content">{content}</div>
721                    </div>
722                }
723                .into_any()
724            } else {
725                let kids = render_all(children, send);
726                view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
727            }
728        }
729        Widget::Grid { children } => {
730            let kids = render_all(children, send);
731            view! { <div class="grid">{kids}</div> }.into_any()
732        }
733        Widget::Scroller { children } => {
734            let kids = render_all(children, send);
735            view! { <div class="scroller">{kids}</div> }.into_any()
736        }
737        // A long/paged feed. Web has no pull gesture or reliable infinite-scroll on a sub-container,
738        // so (like Scaffold pull-to-refresh) the gestures degrade to controls: a top "↻ Refresh"
739        // button (while `on_refresh`), and a bottom "Load more" button (while `has_more && !loading`)
740        // / loading bar / "end" caption. iOS/Android do true pull + scroll-near-end detection.
741        Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing } => {
742            let kids = render_all(children, send);
743            let refresh_btn = on_refresh.clone().map(|token| {
744                let send = send.clone();
745                view! { <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻ Refresh"</button> }
746            });
747            let refresh_bar = refreshing.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
748            let loading_bar = loading.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
749            let load_more_btn = (!*loading && *has_more)
750                .then(|| on_load_more.clone())
751                .flatten()
752                .map(|token| {
753                    let send = send.clone();
754                    view! { <button class="btn btn-outlined lazylist-more" on:click=move |_| send(Action::Fired { token: token.clone() })>"Load more"</button> }
755                });
756            let end_cap = (!*has_more && on_load_more.is_some()).then(|| view! { <div class="lazylist-end">"End of list"</div> });
757            view! {
758                <div class="lazylist">
759                    {refresh_btn}
760                    {refresh_bar}
761                    {kids}
762                    {loading_bar}
763                    {load_more_btn}
764                    {end_cap}
765                </div>
766            }.into_any()
767        }
768
769        // ---- input / actions ----
770        Widget::Button { label, style, on_press } => {
771            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
772            let class = format!("btn {}", button_class(*style));
773            view! {
774                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
775                    {label}
776                </button>
777            }
778            .into_any()
779        }
780        Widget::IconButton { icon, on_press } => {
781            let (send, token) = (send.clone(), on_press.clone());
782            let glyph = icon_glyph(*icon);
783            view! {
784                <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
785                    {glyph}
786                </button>
787            }
788            .into_any()
789        }
790        Widget::Chip { label, selected, on_press } => {
791            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
792            let class = if *selected { "chip selected" } else { "chip" };
793            view! {
794                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
795                    {label}
796                </button>
797            }
798            .into_any()
799        }
800        Widget::TextField { id, placeholder, value, kind, error } => {
801            let (send, id) = (send.clone(), id.clone());
802            let (placeholder, value) = (placeholder.clone(), value.clone());
803            let invalid = error.is_some();
804            let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
805            // (input type, inputmode) per FieldKind. Multiline renders a <textarea> below.
806            let (itype, imode): (&str, &str) = match kind {
807                FieldKind::Secure => ("password", ""),
808                FieldKind::Email => ("email", "email"),
809                FieldKind::Number => ("text", "numeric"),
810                FieldKind::Decimal => ("text", "decimal"),
811                FieldKind::Phone => ("tel", "tel"),
812                FieldKind::Url => ("url", "url"),
813                FieldKind::Text | FieldKind::Multiline => ("text", ""),
814            };
815            let field_class = if invalid { "field field-invalid" } else { "field" };
816            let control = if matches!(kind, FieldKind::Multiline) {
817                view! {
818                    <textarea
819                        class=field_class
820                        rows="3"
821                        placeholder=placeholder
822                        prop:value=value
823                        on:input=move |ev| send(Action::Input {
824                            id: id.clone(),
825                            value: InputValue::Text(event_target_value(&ev)),
826                        })
827                    ></textarea>
828                }
829                .into_any()
830            } else {
831                view! {
832                    <input
833                        class=field_class
834                        r#type=itype
835                        inputmode=imode
836                        placeholder=placeholder
837                        prop:value=value
838                        on:input=move |ev| send(Action::Input {
839                            id: id.clone(),
840                            value: InputValue::Text(event_target_value(&ev)),
841                        })
842                    />
843                }
844                .into_any()
845            };
846            view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
847        }
848        Widget::SearchField { id, placeholder, value } => {
849            let (send, id) = (send.clone(), id.clone());
850            let (placeholder, value) = (placeholder.clone(), value.clone());
851            view! {
852                <div class="searchfield">
853                    <span class="search-icon">{icon_glyph(Icon::Search)}</span>
854                    <input
855                        class="search-input"
856                        placeholder=placeholder
857                        prop:value=value
858                        on:input=move |ev| send(Action::Input {
859                            id: id.clone(),
860                            value: InputValue::Text(event_target_value(&ev)),
861                        })
862                    />
863                </div>
864            }
865            .into_any()
866        }
867        Widget::Segmented { segments } => {
868            let segs: Vec<AnyView> = segments
869                .iter()
870                .map(|s| {
871                    let (send, token) = (send.clone(), s.on_select.clone());
872                    let class = if s.selected { "segment selected" } else { "segment" };
873                    let label = s.label.clone();
874                    view! {
875                        <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
876                            {label}
877                        </button>
878                    }
879                    .into_any()
880                })
881                .collect();
882            view! { <div class="segmented">{segs}</div> }.into_any()
883        }
884        Widget::Toggle { id, label, value } => {
885            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
886            view! {
887                <label class="toggle">
888                    {label}
889                    <input
890                        type="checkbox"
891                        role="switch"
892                        prop:checked=checked
893                        on:change=move |ev| send(Action::Input {
894                            id: id.clone(),
895                            value: InputValue::Bool(event_target_checked(&ev)),
896                        })
897                    />
898                </label>
899            }
900            .into_any()
901        }
902        Widget::Checkbox { id, label, value } => {
903            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
904            view! {
905                <label class="check">
906                    <input
907                        type="checkbox"
908                        prop:checked=checked
909                        on:change=move |ev| send(Action::Input {
910                            id: id.clone(),
911                            value: InputValue::Bool(event_target_checked(&ev)),
912                        })
913                    />
914                    {label}
915                </label>
916            }
917            .into_any()
918        }
919        Widget::Slider { id, value, max } => {
920            let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
921            view! {
922                <input
923                    class="slider"
924                    type="range"
925                    min="0"
926                    max=max
927                    prop:value=value
928                    on:input=move |ev| send(Action::Input {
929                        id: id.clone(),
930                        value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
931                    })
932                />
933            }
934            .into_any()
935        }
936        Widget::Stepper { value, on_decrement, on_increment } => {
937            let send_dec = send.clone();
938            let send_inc = send.clone();
939            let (dec, inc) = (on_decrement.clone(), on_increment.clone());
940            view! {
941                <div class="stepper">
942                    <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
943                    <span class="stepper-value">{*value}</span>
944                    <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
945                </div>
946            }
947            .into_any()
948        }
949
950        // ---- shell ----
951        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth } => {
952            let back_btn = back.clone().map(|token| {
953                let send = send.clone();
954                view! {
955                    <button class="back" on:click=move |_| send(Action::Fired { token: token.clone() })>
956                        "‹"
957                    </button>
958                }
959            });
960            let tabbar = (!tabs.is_empty()).then(|| {
961                let tabs: Vec<AnyView> = tabs
962                    .iter()
963                    .map(|tab| {
964                        let (send, token) = (send.clone(), tab.on_select.clone());
965                        let class = if tab.selected { "tab selected" } else { "tab" };
966                        let label = tab.label.clone();
967                        // Optional leading icon → glyph above the label (icon tab bar).
968                        let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
969                        view! {
970                            <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
971                                {icon}
972                                <span class="tab-label">{label}</span>
973                            </button>
974                        }
975                        .into_any()
976                    })
977                    .collect();
978                view! { <div class="tabbar">{tabs}</div> }
979            });
980            // Floating action button — the raised primary action, anchored over the body.
981            let fab_btn = fab.clone().map(|f| {
982                let (send, token) = (send.clone(), f.on_press.clone());
983                view! {
984                    <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
985                        {icon_glyph(f.icon)}
986                    </button>
987                }
988            });
989            // Modal bottom sheet — a scrim (tap to dismiss) + a panel rising from the bottom.
990            let sheet_overlay = sheet.as_ref().map(|s| {
991                let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
992                let (title, child) = (s.title.clone(), render(&s.child, send));
993                view! {
994                    <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
995                    <div class="sheet">
996                        <div class="sheet-handle"></div>
997                        <div class="sheet-title">{title}</div>
998                        {child}
999                    </div>
1000                }
1001            });
1002            // `theme-dark` flips the CSS variables for the whole shell — theme-as-data,
1003            // the web twin of the native shells' `preferredColorScheme`/Material theme.
1004            let class = if *dark_mode { "scaffold theme-dark" } else { "scaffold" };
1005            // Pull-to-refresh — web has no pull gesture, so expose a top-bar refresh button +
1006            // an indeterminate bar at the top of the body while `refreshing`.
1007            let refresh_btn = on_refresh.clone().map(|token| {
1008                let send = send.clone();
1009                view! {
1010                    <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
1011                }
1012            });
1013            let refresh_bar = refreshing.then(|| {
1014                view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
1015            });
1016            let body_class = format!("scaffold-body {}", nav_class(route, *depth));
1017            // An app `Theme` overrides the CSS variables inline (brand color, corner, density,
1018            // font) — the web twin of the native shells' brand/tint + shape + spacing + font.
1019            let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
1020            let (title, body) = (title.clone(), render(body, send));
1021            view! {
1022                <div class=class style=theme_style>
1023                    <div class="topbar">
1024                        {back_btn}
1025                        <span class="title">{title}</span>
1026                        {refresh_btn}
1027                    </div>
1028                    <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
1029                    {fab_btn}
1030                    {tabbar}
1031                    {sheet_overlay}
1032                </div>
1033            }
1034            .into_any()
1035        }
1036    }
1037}
1038
1039/// Render a slice of children as sibling views.
1040fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
1041    children.iter().map(|c| render(c, send)).collect()
1042}
1043
1044thread_local! {
1045    /// (previous route key, previous depth, alternating toggle). The render is a
1046    /// stateless whole-tree rebuild, so nav state lives here (wasm is single-
1047    /// threaded). Lets the Scaffold body animate on navigation — the web twin of
1048    /// the native shells keying their body on `route`.
1049    static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
1050
1051    /// Open streaming subscriptions keyed by subscription key (wasm is single-
1052    /// threaded). Each [`Effect::PluginStream`] parks its source here so
1053    /// `cx.unsubscribe(key)` can stop it; dropping the entry stops the source.
1054    static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
1055}
1056
1057/// Render an app [`Theme`] as inline CSS custom properties on the scaffold root — the web
1058/// twin of the native brand/tint + shape + spacing + font. Overrides `mobiler.css`'s defaults
1059/// (its rules read these via `var(--…)`); dark mode still works (it only swaps the colors the
1060/// seed doesn't pin).
1061fn theme_css(t: &Theme) -> String {
1062    let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
1063    let radius = match t.corner {
1064        Corner::None => "0px",
1065        Corner::Small => "8px",
1066        Corner::Medium => "14px",
1067        Corner::Large => "22px",
1068    };
1069    let (gap, pad) = match t.density {
1070        Density::Compact => ("8px", "10px"),
1071        Density::Comfortable => ("12px", "14px"),
1072    };
1073    let font = match t.font {
1074        FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
1075        FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
1076        FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
1077        FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
1078    };
1079    // Secondary brand color (for the CardStyle::Brand gradient); falls back to the seed.
1080    let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
1081    format!(
1082        "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
1083         --accent2:rgb({ar},{ag},{ab});\
1084         --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
1085         --gap:{gap};--pad:{pad};--font:{font};"
1086    )
1087}
1088
1089/// Pick the Scaffold body's transition class for this render. Returns `""` for a
1090/// same-route data update (re-render in place, no transition). On a route change it
1091/// returns a directional class — slide-in from the right when `depth` grew (push),
1092/// from the left when it shrank (pop), a crossfade for a lateral move — and *alternates*
1093/// the `-a`/`-b` suffix each navigation so the CSS animation restarts even though
1094/// Leptos reuses the same DOM node.
1095fn nav_class(route: &str, depth: u32) -> &'static str {
1096    NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
1097        if route == prev_route {
1098            return "";
1099        }
1100        let dir = if depth > *prev_depth {
1101            ["nav-push-a", "nav-push-b"]
1102        } else if depth < *prev_depth {
1103            ["nav-pop-a", "nav-pop-b"]
1104        } else {
1105            ["nav-fade-a", "nav-fade-b"]
1106        };
1107        *toggle = !*toggle;
1108        *prev_route = route.to_string();
1109        *prev_depth = depth;
1110        dir[usize::from(*toggle)]
1111    })
1112}
1113
1114// ---- style intent → CSS class / glyph (the only place that names the look) ----
1115
1116fn text_class(s: TextStyle) -> &'static str {
1117    match s {
1118        TextStyle::Title => "t-title",
1119        TextStyle::Subtitle => "t-subtitle",
1120        TextStyle::Caption => "t-caption",
1121        TextStyle::Emphasis => "t-emphasis",
1122        TextStyle::Body => "t-body",
1123    }
1124}
1125
1126fn button_class(s: ButtonStyle) -> &'static str {
1127    match s {
1128        ButtonStyle::Filled => "btn-filled",
1129        ButtonStyle::Outlined => "btn-outlined",
1130        ButtonStyle::Text => "btn-text",
1131    }
1132}
1133
1134fn card_class(s: CardStyle) -> &'static str {
1135    match s {
1136        CardStyle::Elevated => "card-elevated",
1137        CardStyle::Outlined => "card-outlined",
1138        CardStyle::Filled => "card-filled",
1139        CardStyle::Brand => "card-brand",
1140    }
1141}
1142
1143fn tone_class(t: Tone) -> &'static str {
1144    match t {
1145        Tone::Neutral => "tone-neutral",
1146        Tone::Success => "tone-success",
1147        Tone::Warning => "tone-warning",
1148        Tone::Danger => "tone-danger",
1149        Tone::Info => "tone-info",
1150    }
1151}
1152
1153fn spacer_class(s: Spacing) -> &'static str {
1154    match s {
1155        Spacing::Xs => "sp-xs",
1156        Spacing::Sm => "sp-sm",
1157        Spacing::Md => "sp-md",
1158        Spacing::Lg => "sp-lg",
1159        Spacing::Xl => "sp-xl",
1160    }
1161}
1162
1163fn icon_glyph(i: Icon) -> &'static str {
1164    match i {
1165        Icon::Delete => "🗑",
1166        Icon::Add => "+",
1167        Icon::Edit => "✏️",
1168        Icon::Close => "✕",
1169        Icon::Settings => "⚙",
1170        Icon::Check => "✓",
1171        Icon::Star => "★",
1172        Icon::Info => "ℹ",
1173        Icon::Home => "⌂",
1174        Icon::Search => "🔍",
1175        Icon::Menu => "☰",
1176        Icon::Filter => "⚟",
1177        Icon::Back => "‹",
1178        Icon::Forward => "›",
1179        Icon::Down => "⌄",
1180        Icon::Bell => "🔔",
1181        Icon::Cart => "🛒",
1182        Icon::Share => "↗",
1183        Icon::Heart => "♡",
1184        Icon::HeartFilled => "♥",
1185        Icon::Person => "👤",
1186        Icon::People => "👥",
1187        Icon::Phone => "📞",
1188        Icon::Mail => "✉",
1189        Icon::Calendar => "📅",
1190        Icon::Clock => "🕑",
1191        Icon::MapPin => "📍",
1192        Icon::Camera => "📷",
1193        Icon::Photo => "🖼",
1194        Icon::Play => "▶",
1195        Icon::Scissors => "✂",
1196    }
1197}
1198
1199fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
1200    let shape = match shape {
1201        ImageShape::Square => "img-square",
1202        ImageShape::Rounded => "img-rounded",
1203        ImageShape::Circle => "img-circle",
1204    };
1205    let ratio = match ratio {
1206        ImageRatio::Wide => "ratio-wide",
1207        ImageRatio::Square => "ratio-square",
1208        ImageRatio::Tall => "ratio-tall",
1209    };
1210    format!("img {shape} {ratio}")
1211}
1212
1213fn dot_class(c: ProjectColor) -> &'static str {
1214    match c {
1215        ProjectColor::Indigo => "dot-indigo",
1216        ProjectColor::Teal => "dot-teal",
1217        ProjectColor::Coral => "dot-coral",
1218        ProjectColor::Amber => "dot-amber",
1219        ProjectColor::Lime => "dot-lime",
1220        ProjectColor::Pink => "dot-pink",
1221    }
1222}
1223
1224fn align_class(a: BoxAlign) -> &'static str {
1225    match a {
1226        BoxAlign::TopStart => "align-top-start",
1227        BoxAlign::TopEnd => "align-top-end",
1228        BoxAlign::Center => "align-center",
1229        BoxAlign::BottomStart => "align-bottom-start",
1230        BoxAlign::BottomCenter => "align-bottom-center",
1231        BoxAlign::BottomEnd => "align-bottom-end",
1232    }
1233}
1234
1235// ------------------------------- charts -------------------------------
1236
1237/// Distinct fallback colors for series 1.. (series 0 with no override rides the theme accent).
1238const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
1239
1240fn hex(c: Rgb) -> String {
1241    format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
1242}
1243
1244/// Color for series `i`: explicit override → theme accent (i==0) → palette.
1245fn chart_color(i: usize, s: &ChartSeries) -> String {
1246    match s.color {
1247        Some(c) => hex(c),
1248        None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
1249        None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
1250    }
1251}
1252
1253/// A series' single magnitude for circular charts (sum of its values).
1254fn chart_mag(s: &ChartSeries) -> f32 {
1255    s.values.iter().copied().sum()
1256}
1257
1258/// Point on a circle: `ang` in radians, 0 = top (12 o'clock), increasing clockwise.
1259fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
1260    (cx + r * ang.sin(), cy - r * ang.cos())
1261}
1262
1263/// An open arc path (for ring/donut/gauge strokes).
1264fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1265    let (x0, y0) = polar(cx, cy, r, a0);
1266    let (x1, y1) = polar(cx, cy, r, a1);
1267    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1268    format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
1269}
1270
1271/// A filled wedge from the center (for pie/donut slices).
1272fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1273    let (x0, y0) = polar(cx, cy, r, a0);
1274    let (x1, y1) = polar(cx, cy, r, a1);
1275    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1276    format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
1277}
1278
1279fn fmt_tick(v: f32) -> String {
1280    if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
1281}
1282
1283fn is_cartesian(style: ChartStyle) -> bool {
1284    matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
1285}
1286
1287/// The y-axis denominator for a cartesian chart.
1288fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
1289    match style {
1290        ChartStyle::StackedBar => (0..nslots)
1291            .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
1292            .fold(0.0, f32::max)
1293            .max(1e-6),
1294        ChartStyle::StackedBar100 => 1.0,
1295        _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
1296    }
1297}
1298
1299fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
1300    // plot area: y in [2, 48] of the 0..50 viewBox
1301    let mut nodes: Vec<AnyView> = Vec::new();
1302    if axis {
1303        for k in 0..=4 {
1304            let y = 2.0 + k as f32 * (46.0 / 4.0);
1305            nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
1306        }
1307    }
1308    match style {
1309        ChartStyle::Line => {
1310            for (i, s) in series.iter().enumerate() {
1311                let n = s.values.len().max(1);
1312                let pts = s.values.iter().enumerate().map(|(j, v)| {
1313                    let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
1314                    let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
1315                    format!("{x:.2},{y:.2}")
1316                }).collect::<Vec<_>>().join(" ");
1317                let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
1318                nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
1319            }
1320        }
1321        ChartStyle::Bar => {
1322            let sw = 100.0 / nslots as f32;
1323            let ns = series.len().max(1);
1324            for (i, s) in series.iter().enumerate() {
1325                let st = format!("fill:{}", chart_color(i, s));
1326                for (j, v) in s.values.iter().enumerate() {
1327                    let h = (v / max).clamp(0.0, 1.0) * 46.0;
1328                    let bw = sw * 0.8 / ns as f32;
1329                    let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
1330                    let y = 48.0 - h;
1331                    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());
1332                }
1333            }
1334        }
1335        ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
1336            let sw = 100.0 / nslots as f32;
1337            for j in 0..nslots {
1338                let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
1339                let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
1340                let mut acc = 0.0_f32;
1341                for (i, s) in series.iter().enumerate() {
1342                    let v = *s.values.get(j).unwrap_or(&0.0);
1343                    let h = (v / denom).clamp(0.0, 1.0) * 46.0;
1344                    let x = j as f32 * sw + sw * 0.15;
1345                    let bw = sw * 0.7;
1346                    let y = 48.0 - acc - h;
1347                    let st = format!("fill:{}", chart_color(i, s));
1348                    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());
1349                    acc += h;
1350                }
1351            }
1352        }
1353        _ => {}
1354    }
1355    view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
1356}
1357
1358fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
1359    use std::f32::consts::PI;
1360    let mut nodes: Vec<AnyView> = Vec::new();
1361    match style {
1362        ChartStyle::Pie | ChartStyle::Donut => {
1363            let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
1364            let mut a = 0.0_f32;
1365            for (i, s) in series.iter().enumerate() {
1366                let frac = chart_mag(s) / total;
1367                let st = format!("fill:{}", chart_color(i, s));
1368                if frac >= 0.999 {
1369                    nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
1370                } else if frac > 0.0 {
1371                    let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
1372                    nodes.push(view! { <path d=d style=st></path> }.into_any());
1373                }
1374                a += frac * 2.0 * PI;
1375            }
1376            if matches!(style, ChartStyle::Donut) {
1377                nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
1378            }
1379        }
1380        ChartStyle::Rings => {
1381            let n = series.len().max(1);
1382            for (i, s) in series.iter().enumerate() {
1383                let r = 45.0 - i as f32 * (34.0 / n as f32);
1384                let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
1385                let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
1386                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());
1387                let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
1388                if prog >= 0.999 {
1389                    nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
1390                } else if prog > 0.0 {
1391                    let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
1392                    nodes.push(view! { <path d=d style=st></path> }.into_any());
1393                }
1394            }
1395        }
1396        ChartStyle::Gauge => {
1397            let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
1398            let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
1399            let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
1400            let a0 = -0.75 * PI; // 270° sweep, gap at the bottom
1401            let a1 = 0.75 * PI;
1402            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());
1403            if prog > 0.0 {
1404                let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
1405                nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
1406            }
1407            let pct = format!("{}%", (prog * 100.0).round() as i64);
1408            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());
1409        }
1410        _ => {}
1411    }
1412    view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
1413}
1414
1415fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
1416    let cartesian = is_cartesian(style);
1417    let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
1418    let max = cartesian_max(series, style, nslots);
1419
1420    let plot = if cartesian {
1421        let svg = cartesian_svg(series, style, axis, max, nslots);
1422        let yaxis = if axis {
1423            let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
1424                .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
1425                .collect();
1426            Some(view! { <div class="chart-yaxis">{ticks}</div> })
1427        } else {
1428            None
1429        };
1430        view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
1431    } else {
1432        circular_svg(series, style).into_any()
1433    };
1434
1435    let label_row = if cartesian && !labels.is_empty() {
1436        let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
1437        Some(view! { <div class="chart-labels">{items}</div> })
1438    } else {
1439        None
1440    };
1441
1442    let legend_row = if legend {
1443        let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
1444            let sw = format!("background:{}", chart_color(i, s));
1445            let name = s.name.clone();
1446            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
1447        }).collect();
1448        Some(view! { <div class="chart-legend">{items}</div> })
1449    } else {
1450        None
1451    };
1452
1453    view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
1454}
1455
1456// --------------------------- region chart ---------------------------
1457
1458/// Palette as RGB (parallel to `CHART_PALETTE`) so region charts can compute label contrast.
1459const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
1460    [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
1461
1462/// The resolved fill RGB for region `i` (explicit override → palette).
1463fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
1464    match r.color {
1465        Some(c) => (c.r, c.g, c.b),
1466        None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
1467    }
1468}
1469
1470/// Black or white label text, whichever reads on the given fill (perceived luminance).
1471fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
1472    let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
1473    if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
1474}
1475
1476fn region_color(i: usize, r: &ChartRegion) -> String {
1477    let (r8, g8, b8) = region_rgb(i, r);
1478    format!("#{r8:02x}{g8:02x}{b8:02x}")
1479}
1480
1481// A variable-width stacked-region / coverage-gap chart: absolute-positioned region rectangles in
1482// the [0,x_max]×[0,y_max] plane, horizontal ref lines + chips, an irregular x-axis, an optional
1483// right-side bracket, and a legend. The web twin of the Compose/SwiftUI RegionChart renderers.
1484fn region_chart_view(
1485    regions: &[ChartRegion],
1486    ticks: &[ChartTick],
1487    x_max: f32,
1488    y_max: f32,
1489    ref_lines: &[ChartRefLine],
1490    bracket: &Option<ChartBracket>,
1491    legend: &[ChartLegendItem],
1492) -> AnyView {
1493    let xm = x_max.max(1e-6);
1494    let ym = y_max.max(1e-6);
1495
1496    let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
1497        let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
1498        let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
1499        let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
1500        let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
1501        let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
1502        let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
1503        let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
1504        let label = r.label.clone();
1505        view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
1506    }).collect();
1507
1508    // The reference lines span the full plot width; their value chips sit in the right margin
1509    // (outside the plot), like the original — so the line clearly runs to the plot's edge.
1510    let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
1511        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
1512        let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
1513        view! { <div class=cls style=style></div> }
1514    }).collect();
1515    let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
1516        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
1517        let label = rl.label.clone();
1518        view! { <div class="rchart-chip" style=style>{label}</div> }
1519    }).collect();
1520
1521    let bracket_div = bracket.as_ref().map(|b| {
1522        let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
1523        let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
1524        let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
1525        let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
1526        view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
1527    });
1528
1529    let yticks: Vec<_> = (0..=4).rev().map(|k| {
1530        let v = ym * k as f32 / 4.0;
1531        view! { <span class="chart-tick">{fmt_tick(v)}</span> }
1532    }).collect();
1533
1534    let xticks: Vec<_> = ticks.iter().map(|t| {
1535        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
1536        let label = t.label.clone();
1537        view! { <span class="rchart-xtick" style=style>{label}</span> }
1538    }).collect();
1539
1540    // Axis tick marks (notches on the L-shaped axis): horizontal on the y-axis at each value,
1541    // vertical on the x-axis at each irregular break — drawn over the bands at the plot edges.
1542    let ytick_marks: Vec<_> = (0..=4).map(|k| {
1543        let style = format!("bottom:{:.3}%", k as f32 * 25.0);
1544        view! { <div class="rchart-ytick" style=style></div> }
1545    }).collect();
1546    let xtick_marks: Vec<_> = ticks.iter().map(|t| {
1547        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
1548        view! { <div class="rchart-xtickmark" style=style></div> }
1549    }).collect();
1550
1551    let legend_row = if legend.is_empty() {
1552        None
1553    } else {
1554        let items: Vec<_> = legend.iter().map(|l| {
1555            let sw = format!("background:{}", hex(l.color));
1556            let name = l.label.clone();
1557            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
1558        }).collect();
1559        Some(view! { <div class="chart-legend">{items}</div> })
1560    };
1561
1562    view! {
1563        <div class="rchart">
1564            <div class="rchart-row">
1565                <div class="rchart-yaxis">{yticks}</div>
1566                <div class="rchart-plotwrap">
1567                    <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
1568                    {chip_divs}{bracket_div}
1569                </div>
1570            </div>
1571            <div class="rchart-xaxis">{xticks}</div>
1572            {legend_row}
1573        </div>
1574    }.into_any()
1575}