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