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::Rating { value, max, on_rate } => {
485            let value = *value;
486            let stars: Vec<AnyView> = (1..=*max)
487                .map(|i| {
488                    let threshold = u32::from(i) * 10;
489                    // filled / half / empty by tenths.
490                    let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
491                    match on_rate {
492                        Some(tokens) => {
493                            let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
494                            view! {
495                                <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
496                                    {glyph}
497                                </button>
498                            }
499                            .into_any()
500                        }
501                        None => view! { <span class="star">{glyph}</span> }.into_any(),
502                    }
503                })
504                .collect();
505            view! { <span class="rating">{stars}</span> }.into_any()
506        }
507        Widget::Divider => view! { <hr class="divider" /> }.into_any(),
508        Widget::Progress { value } => match value {
509            Some(v) => {
510                let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
511                view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
512            }
513            None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
514        },
515        Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
516        Widget::Chart { series, labels, style, axis, legend } => {
517            chart_view(series, labels, *style, *axis, *legend)
518        }
519        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
520            region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
521        }
522        Widget::Calendar { year, month, first_weekday, selected, on_day } => {
523            const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June",
524                "July", "August", "September", "October", "November", "December"];
525            let head_label = format!("{} {year}", MONTHS.get((*month as usize).saturating_sub(1)).copied().unwrap_or(""));
526            let weekdays = ["S", "M", "T", "W", "T", "F", "S"];
527            let heads: Vec<_> = weekdays.iter().map(|w| view! { <div class="cal-head">{*w}</div> }).collect();
528            let blanks: Vec<_> = (0..*first_weekday).map(|_| view! { <div class="cal-blank"></div> }).collect();
529            let selected = *selected;
530            let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
531                let day = (i + 1) as u8;
532                let token = token.clone();
533                let send = send.clone();
534                let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
535                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}</button> }
536            }).collect();
537            view! {
538                <div class="calendar">
539                    <div class="cal-title">{head_label}</div>
540                    <div class="cal-grid">{heads}{blanks}{days}</div>
541                </div>
542            }.into_any()
543        }
544        Widget::SwipeAction { child, actions } => {
545            // Web has no swipe gesture — render the actions inline as a trailing button row.
546            let acts: Vec<_> = actions.iter().map(|a| {
547                let token = a.on_tap.clone();
548                let send = send.clone();
549                let cls = format!("swipe-act {}", tone_class(a.tone));
550                let label = a.label.clone();
551                view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
552            }).collect();
553            view! {
554                <div class="swipe-row">
555                    <div class="swipe-content">{render(child, send)}</div>
556                    <div class="swipe-actions">{acts}</div>
557                </div>
558            }.into_any()
559        }
560        Widget::Spacer { size } => {
561            view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
562        }
563
564        // ---- layout ----
565        Widget::Row { children } => {
566            let kids = render_all(children, send);
567            view! { <div class="row">{kids}</div> }.into_any()
568        }
569        Widget::Column { children } => {
570            let kids = render_all(children, send);
571            view! { <div class="col">{kids}</div> }.into_any()
572        }
573        Widget::Card { child, style, on_press } => {
574            let class = format!("card {}", card_class(*style));
575            let body = render(child, send);
576            match on_press {
577                Some(token) => {
578                    let (send, token) = (send.clone(), token.clone());
579                    view! {
580                        <button
581                            class=format!("{class} card-tappable")
582                            on:click=move |_| send(Action::Fired { token: token.clone() })
583                        >
584                            {body}
585                        </button>
586                    }
587                    .into_any()
588                }
589                None => view! { <div class=class>{body}</div> }.into_any(),
590            }
591        }
592        // Z-stack. With `scrim`, the first child is a background image, darkened
593        // by an overlay, and the rest layer on top in light content — the DOM twin
594        // of the Compose `matchParentSize` scrim / SwiftUI `.overlay` on the image.
595        Widget::Box { children, align, scrim } => {
596            let acls = align_class(*align);
597            if *scrim && children.len() > 1 {
598                let bg = render(&children[0], send);
599                let content = render_all(&children[1..], send);
600                view! {
601                    <div class=format!("box box-scrim {acls}")>
602                        {bg}
603                        <div class="scrim"></div>
604                        <div class="box-content">{content}</div>
605                    </div>
606                }
607                .into_any()
608            } else {
609                let kids = render_all(children, send);
610                view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
611            }
612        }
613        Widget::Grid { children } => {
614            let kids = render_all(children, send);
615            view! { <div class="grid">{kids}</div> }.into_any()
616        }
617        Widget::Scroller { children } => {
618            let kids = render_all(children, send);
619            view! { <div class="scroller">{kids}</div> }.into_any()
620        }
621
622        // ---- input / actions ----
623        Widget::Button { label, style, on_press } => {
624            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
625            let class = format!("btn {}", button_class(*style));
626            view! {
627                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
628                    {label}
629                </button>
630            }
631            .into_any()
632        }
633        Widget::IconButton { icon, on_press } => {
634            let (send, token) = (send.clone(), on_press.clone());
635            let glyph = icon_glyph(*icon);
636            view! {
637                <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
638                    {glyph}
639                </button>
640            }
641            .into_any()
642        }
643        Widget::Chip { label, selected, on_press } => {
644            let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
645            let class = if *selected { "chip selected" } else { "chip" };
646            view! {
647                <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
648                    {label}
649                </button>
650            }
651            .into_any()
652        }
653        Widget::TextField { id, placeholder, value, kind, error } => {
654            let (send, id) = (send.clone(), id.clone());
655            let (placeholder, value) = (placeholder.clone(), value.clone());
656            let invalid = error.is_some();
657            let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
658            // (input type, inputmode) per FieldKind. Multiline renders a <textarea> below.
659            let (itype, imode): (&str, &str) = match kind {
660                FieldKind::Secure => ("password", ""),
661                FieldKind::Email => ("email", "email"),
662                FieldKind::Number => ("text", "numeric"),
663                FieldKind::Decimal => ("text", "decimal"),
664                FieldKind::Phone => ("tel", "tel"),
665                FieldKind::Url => ("url", "url"),
666                FieldKind::Text | FieldKind::Multiline => ("text", ""),
667            };
668            let field_class = if invalid { "field field-invalid" } else { "field" };
669            let control = if matches!(kind, FieldKind::Multiline) {
670                view! {
671                    <textarea
672                        class=field_class
673                        rows="3"
674                        placeholder=placeholder
675                        prop:value=value
676                        on:input=move |ev| send(Action::Input {
677                            id: id.clone(),
678                            value: InputValue::Text(event_target_value(&ev)),
679                        })
680                    ></textarea>
681                }
682                .into_any()
683            } else {
684                view! {
685                    <input
686                        class=field_class
687                        r#type=itype
688                        inputmode=imode
689                        placeholder=placeholder
690                        prop:value=value
691                        on:input=move |ev| send(Action::Input {
692                            id: id.clone(),
693                            value: InputValue::Text(event_target_value(&ev)),
694                        })
695                    />
696                }
697                .into_any()
698            };
699            view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
700        }
701        Widget::SearchField { id, placeholder, value } => {
702            let (send, id) = (send.clone(), id.clone());
703            let (placeholder, value) = (placeholder.clone(), value.clone());
704            view! {
705                <div class="searchfield">
706                    <span class="search-icon">{icon_glyph(Icon::Search)}</span>
707                    <input
708                        class="search-input"
709                        placeholder=placeholder
710                        prop:value=value
711                        on:input=move |ev| send(Action::Input {
712                            id: id.clone(),
713                            value: InputValue::Text(event_target_value(&ev)),
714                        })
715                    />
716                </div>
717            }
718            .into_any()
719        }
720        Widget::Segmented { segments } => {
721            let segs: Vec<AnyView> = segments
722                .iter()
723                .map(|s| {
724                    let (send, token) = (send.clone(), s.on_select.clone());
725                    let class = if s.selected { "segment selected" } else { "segment" };
726                    let label = s.label.clone();
727                    view! {
728                        <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
729                            {label}
730                        </button>
731                    }
732                    .into_any()
733                })
734                .collect();
735            view! { <div class="segmented">{segs}</div> }.into_any()
736        }
737        Widget::Toggle { id, label, value } => {
738            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
739            view! {
740                <label class="toggle">
741                    {label}
742                    <input
743                        type="checkbox"
744                        role="switch"
745                        prop:checked=checked
746                        on:change=move |ev| send(Action::Input {
747                            id: id.clone(),
748                            value: InputValue::Bool(event_target_checked(&ev)),
749                        })
750                    />
751                </label>
752            }
753            .into_any()
754        }
755        Widget::Checkbox { id, label, value } => {
756            let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
757            view! {
758                <label class="check">
759                    <input
760                        type="checkbox"
761                        prop:checked=checked
762                        on:change=move |ev| send(Action::Input {
763                            id: id.clone(),
764                            value: InputValue::Bool(event_target_checked(&ev)),
765                        })
766                    />
767                    {label}
768                </label>
769            }
770            .into_any()
771        }
772        Widget::Slider { id, value, max } => {
773            let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
774            view! {
775                <input
776                    class="slider"
777                    type="range"
778                    min="0"
779                    max=max
780                    prop:value=value
781                    on:input=move |ev| send(Action::Input {
782                        id: id.clone(),
783                        value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
784                    })
785                />
786            }
787            .into_any()
788        }
789        Widget::Stepper { value, on_decrement, on_increment } => {
790            let send_dec = send.clone();
791            let send_inc = send.clone();
792            let (dec, inc) = (on_decrement.clone(), on_increment.clone());
793            view! {
794                <div class="stepper">
795                    <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
796                    <span class="stepper-value">{*value}</span>
797                    <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
798                </div>
799            }
800            .into_any()
801        }
802
803        // ---- shell ----
804        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth } => {
805            let back_btn = back.clone().map(|token| {
806                let send = send.clone();
807                view! {
808                    <button class="back" on:click=move |_| send(Action::Fired { token: token.clone() })>
809                        "‹"
810                    </button>
811                }
812            });
813            let tabbar = (!tabs.is_empty()).then(|| {
814                let tabs: Vec<AnyView> = tabs
815                    .iter()
816                    .map(|tab| {
817                        let (send, token) = (send.clone(), tab.on_select.clone());
818                        let class = if tab.selected { "tab selected" } else { "tab" };
819                        let label = tab.label.clone();
820                        // Optional leading icon → glyph above the label (icon tab bar).
821                        let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
822                        view! {
823                            <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
824                                {icon}
825                                <span class="tab-label">{label}</span>
826                            </button>
827                        }
828                        .into_any()
829                    })
830                    .collect();
831                view! { <div class="tabbar">{tabs}</div> }
832            });
833            // Floating action button — the raised primary action, anchored over the body.
834            let fab_btn = fab.clone().map(|f| {
835                let (send, token) = (send.clone(), f.on_press.clone());
836                view! {
837                    <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
838                        {icon_glyph(f.icon)}
839                    </button>
840                }
841            });
842            // Modal bottom sheet — a scrim (tap to dismiss) + a panel rising from the bottom.
843            let sheet_overlay = sheet.as_ref().map(|s| {
844                let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
845                let (title, child) = (s.title.clone(), render(&s.child, send));
846                view! {
847                    <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
848                    <div class="sheet">
849                        <div class="sheet-handle"></div>
850                        <div class="sheet-title">{title}</div>
851                        {child}
852                    </div>
853                }
854            });
855            // `theme-dark` flips the CSS variables for the whole shell — theme-as-data,
856            // the web twin of the native shells' `preferredColorScheme`/Material theme.
857            let class = if *dark_mode { "scaffold theme-dark" } else { "scaffold" };
858            // Pull-to-refresh — web has no pull gesture, so expose a top-bar refresh button +
859            // an indeterminate bar at the top of the body while `refreshing`.
860            let refresh_btn = on_refresh.clone().map(|token| {
861                let send = send.clone();
862                view! {
863                    <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
864                }
865            });
866            let refresh_bar = refreshing.then(|| {
867                view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
868            });
869            let body_class = format!("scaffold-body {}", nav_class(route, *depth));
870            // An app `Theme` overrides the CSS variables inline (brand color, corner, density,
871            // font) — the web twin of the native shells' brand/tint + shape + spacing + font.
872            let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
873            let (title, body) = (title.clone(), render(body, send));
874            view! {
875                <div class=class style=theme_style>
876                    <div class="topbar">
877                        {back_btn}
878                        <span class="title">{title}</span>
879                        {refresh_btn}
880                    </div>
881                    <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
882                    {fab_btn}
883                    {tabbar}
884                    {sheet_overlay}
885                </div>
886            }
887            .into_any()
888        }
889    }
890}
891
892/// Render a slice of children as sibling views.
893fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
894    children.iter().map(|c| render(c, send)).collect()
895}
896
897thread_local! {
898    /// (previous route key, previous depth, alternating toggle). The render is a
899    /// stateless whole-tree rebuild, so nav state lives here (wasm is single-
900    /// threaded). Lets the Scaffold body animate on navigation — the web twin of
901    /// the native shells keying their body on `route`.
902    static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
903
904    /// Open streaming subscriptions keyed by subscription key (wasm is single-
905    /// threaded). Each [`Effect::PluginStream`] parks its source here so
906    /// `cx.unsubscribe(key)` can stop it; dropping the entry stops the source.
907    static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
908}
909
910/// Render an app [`Theme`] as inline CSS custom properties on the scaffold root — the web
911/// twin of the native brand/tint + shape + spacing + font. Overrides `mobiler.css`'s defaults
912/// (its rules read these via `var(--…)`); dark mode still works (it only swaps the colors the
913/// seed doesn't pin).
914fn theme_css(t: &Theme) -> String {
915    let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
916    let radius = match t.corner {
917        Corner::None => "0px",
918        Corner::Small => "8px",
919        Corner::Medium => "14px",
920        Corner::Large => "22px",
921    };
922    let (gap, pad) = match t.density {
923        Density::Compact => ("8px", "10px"),
924        Density::Comfortable => ("12px", "14px"),
925    };
926    let font = match t.font {
927        FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
928        FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
929        FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
930        FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
931    };
932    // Secondary brand color (for the CardStyle::Brand gradient); falls back to the seed.
933    let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
934    format!(
935        "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
936         --accent2:rgb({ar},{ag},{ab});\
937         --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
938         --gap:{gap};--pad:{pad};--font:{font};"
939    )
940}
941
942/// Pick the Scaffold body's transition class for this render. Returns `""` for a
943/// same-route data update (re-render in place, no transition). On a route change it
944/// returns a directional class — slide-in from the right when `depth` grew (push),
945/// from the left when it shrank (pop), a crossfade for a lateral move — and *alternates*
946/// the `-a`/`-b` suffix each navigation so the CSS animation restarts even though
947/// Leptos reuses the same DOM node.
948fn nav_class(route: &str, depth: u32) -> &'static str {
949    NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
950        if route == prev_route {
951            return "";
952        }
953        let dir = if depth > *prev_depth {
954            ["nav-push-a", "nav-push-b"]
955        } else if depth < *prev_depth {
956            ["nav-pop-a", "nav-pop-b"]
957        } else {
958            ["nav-fade-a", "nav-fade-b"]
959        };
960        *toggle = !*toggle;
961        *prev_route = route.to_string();
962        *prev_depth = depth;
963        dir[usize::from(*toggle)]
964    })
965}
966
967// ---- style intent → CSS class / glyph (the only place that names the look) ----
968
969fn text_class(s: TextStyle) -> &'static str {
970    match s {
971        TextStyle::Title => "t-title",
972        TextStyle::Subtitle => "t-subtitle",
973        TextStyle::Caption => "t-caption",
974        TextStyle::Emphasis => "t-emphasis",
975        TextStyle::Body => "t-body",
976    }
977}
978
979fn button_class(s: ButtonStyle) -> &'static str {
980    match s {
981        ButtonStyle::Filled => "btn-filled",
982        ButtonStyle::Outlined => "btn-outlined",
983        ButtonStyle::Text => "btn-text",
984    }
985}
986
987fn card_class(s: CardStyle) -> &'static str {
988    match s {
989        CardStyle::Elevated => "card-elevated",
990        CardStyle::Outlined => "card-outlined",
991        CardStyle::Filled => "card-filled",
992        CardStyle::Brand => "card-brand",
993    }
994}
995
996fn tone_class(t: Tone) -> &'static str {
997    match t {
998        Tone::Neutral => "tone-neutral",
999        Tone::Success => "tone-success",
1000        Tone::Warning => "tone-warning",
1001        Tone::Danger => "tone-danger",
1002        Tone::Info => "tone-info",
1003    }
1004}
1005
1006fn spacer_class(s: Spacing) -> &'static str {
1007    match s {
1008        Spacing::Xs => "sp-xs",
1009        Spacing::Sm => "sp-sm",
1010        Spacing::Md => "sp-md",
1011        Spacing::Lg => "sp-lg",
1012        Spacing::Xl => "sp-xl",
1013    }
1014}
1015
1016fn icon_glyph(i: Icon) -> &'static str {
1017    match i {
1018        Icon::Delete => "🗑",
1019        Icon::Add => "+",
1020        Icon::Edit => "✏️",
1021        Icon::Close => "✕",
1022        Icon::Settings => "⚙",
1023        Icon::Check => "✓",
1024        Icon::Star => "★",
1025        Icon::Info => "ℹ",
1026        Icon::Home => "⌂",
1027        Icon::Search => "🔍",
1028        Icon::Menu => "☰",
1029        Icon::Filter => "⚟",
1030        Icon::Back => "‹",
1031        Icon::Forward => "›",
1032        Icon::Down => "⌄",
1033        Icon::Bell => "🔔",
1034        Icon::Cart => "🛒",
1035        Icon::Share => "↗",
1036        Icon::Heart => "♡",
1037        Icon::HeartFilled => "♥",
1038        Icon::Person => "👤",
1039        Icon::People => "👥",
1040        Icon::Phone => "📞",
1041        Icon::Mail => "✉",
1042        Icon::Calendar => "📅",
1043        Icon::Clock => "🕑",
1044        Icon::MapPin => "📍",
1045        Icon::Camera => "📷",
1046        Icon::Photo => "🖼",
1047        Icon::Play => "▶",
1048        Icon::Scissors => "✂",
1049    }
1050}
1051
1052fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
1053    let shape = match shape {
1054        ImageShape::Square => "img-square",
1055        ImageShape::Rounded => "img-rounded",
1056        ImageShape::Circle => "img-circle",
1057    };
1058    let ratio = match ratio {
1059        ImageRatio::Wide => "ratio-wide",
1060        ImageRatio::Square => "ratio-square",
1061        ImageRatio::Tall => "ratio-tall",
1062    };
1063    format!("img {shape} {ratio}")
1064}
1065
1066fn dot_class(c: ProjectColor) -> &'static str {
1067    match c {
1068        ProjectColor::Indigo => "dot-indigo",
1069        ProjectColor::Teal => "dot-teal",
1070        ProjectColor::Coral => "dot-coral",
1071        ProjectColor::Amber => "dot-amber",
1072        ProjectColor::Lime => "dot-lime",
1073        ProjectColor::Pink => "dot-pink",
1074    }
1075}
1076
1077fn align_class(a: BoxAlign) -> &'static str {
1078    match a {
1079        BoxAlign::TopStart => "align-top-start",
1080        BoxAlign::TopEnd => "align-top-end",
1081        BoxAlign::Center => "align-center",
1082        BoxAlign::BottomStart => "align-bottom-start",
1083        BoxAlign::BottomCenter => "align-bottom-center",
1084        BoxAlign::BottomEnd => "align-bottom-end",
1085    }
1086}
1087
1088// ------------------------------- charts -------------------------------
1089
1090/// Distinct fallback colors for series 1.. (series 0 with no override rides the theme accent).
1091const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
1092
1093fn hex(c: Rgb) -> String {
1094    format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
1095}
1096
1097/// Color for series `i`: explicit override → theme accent (i==0) → palette.
1098fn chart_color(i: usize, s: &ChartSeries) -> String {
1099    match s.color {
1100        Some(c) => hex(c),
1101        None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
1102        None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
1103    }
1104}
1105
1106/// A series' single magnitude for circular charts (sum of its values).
1107fn chart_mag(s: &ChartSeries) -> f32 {
1108    s.values.iter().copied().sum()
1109}
1110
1111/// Point on a circle: `ang` in radians, 0 = top (12 o'clock), increasing clockwise.
1112fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
1113    (cx + r * ang.sin(), cy - r * ang.cos())
1114}
1115
1116/// An open arc path (for ring/donut/gauge strokes).
1117fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1118    let (x0, y0) = polar(cx, cy, r, a0);
1119    let (x1, y1) = polar(cx, cy, r, a1);
1120    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1121    format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
1122}
1123
1124/// A filled wedge from the center (for pie/donut slices).
1125fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1126    let (x0, y0) = polar(cx, cy, r, a0);
1127    let (x1, y1) = polar(cx, cy, r, a1);
1128    let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1129    format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
1130}
1131
1132fn fmt_tick(v: f32) -> String {
1133    if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
1134}
1135
1136fn is_cartesian(style: ChartStyle) -> bool {
1137    matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
1138}
1139
1140/// The y-axis denominator for a cartesian chart.
1141fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
1142    match style {
1143        ChartStyle::StackedBar => (0..nslots)
1144            .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
1145            .fold(0.0, f32::max)
1146            .max(1e-6),
1147        ChartStyle::StackedBar100 => 1.0,
1148        _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
1149    }
1150}
1151
1152fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
1153    // plot area: y in [2, 48] of the 0..50 viewBox
1154    let mut nodes: Vec<AnyView> = Vec::new();
1155    if axis {
1156        for k in 0..=4 {
1157            let y = 2.0 + k as f32 * (46.0 / 4.0);
1158            nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
1159        }
1160    }
1161    match style {
1162        ChartStyle::Line => {
1163            for (i, s) in series.iter().enumerate() {
1164                let n = s.values.len().max(1);
1165                let pts = s.values.iter().enumerate().map(|(j, v)| {
1166                    let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
1167                    let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
1168                    format!("{x:.2},{y:.2}")
1169                }).collect::<Vec<_>>().join(" ");
1170                let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
1171                nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
1172            }
1173        }
1174        ChartStyle::Bar => {
1175            let sw = 100.0 / nslots as f32;
1176            let ns = series.len().max(1);
1177            for (i, s) in series.iter().enumerate() {
1178                let st = format!("fill:{}", chart_color(i, s));
1179                for (j, v) in s.values.iter().enumerate() {
1180                    let h = (v / max).clamp(0.0, 1.0) * 46.0;
1181                    let bw = sw * 0.8 / ns as f32;
1182                    let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
1183                    let y = 48.0 - h;
1184                    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());
1185                }
1186            }
1187        }
1188        ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
1189            let sw = 100.0 / nslots as f32;
1190            for j in 0..nslots {
1191                let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
1192                let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
1193                let mut acc = 0.0_f32;
1194                for (i, s) in series.iter().enumerate() {
1195                    let v = *s.values.get(j).unwrap_or(&0.0);
1196                    let h = (v / denom).clamp(0.0, 1.0) * 46.0;
1197                    let x = j as f32 * sw + sw * 0.15;
1198                    let bw = sw * 0.7;
1199                    let y = 48.0 - acc - h;
1200                    let st = format!("fill:{}", chart_color(i, s));
1201                    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());
1202                    acc += h;
1203                }
1204            }
1205        }
1206        _ => {}
1207    }
1208    view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
1209}
1210
1211fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
1212    use std::f32::consts::PI;
1213    let mut nodes: Vec<AnyView> = Vec::new();
1214    match style {
1215        ChartStyle::Pie | ChartStyle::Donut => {
1216            let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
1217            let mut a = 0.0_f32;
1218            for (i, s) in series.iter().enumerate() {
1219                let frac = chart_mag(s) / total;
1220                let st = format!("fill:{}", chart_color(i, s));
1221                if frac >= 0.999 {
1222                    nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
1223                } else if frac > 0.0 {
1224                    let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
1225                    nodes.push(view! { <path d=d style=st></path> }.into_any());
1226                }
1227                a += frac * 2.0 * PI;
1228            }
1229            if matches!(style, ChartStyle::Donut) {
1230                nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
1231            }
1232        }
1233        ChartStyle::Rings => {
1234            let n = series.len().max(1);
1235            for (i, s) in series.iter().enumerate() {
1236                let r = 45.0 - i as f32 * (34.0 / n as f32);
1237                let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
1238                let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
1239                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());
1240                let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
1241                if prog >= 0.999 {
1242                    nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
1243                } else if prog > 0.0 {
1244                    let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
1245                    nodes.push(view! { <path d=d style=st></path> }.into_any());
1246                }
1247            }
1248        }
1249        ChartStyle::Gauge => {
1250            let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
1251            let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
1252            let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
1253            let a0 = -0.75 * PI; // 270° sweep, gap at the bottom
1254            let a1 = 0.75 * PI;
1255            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());
1256            if prog > 0.0 {
1257                let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
1258                nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
1259            }
1260            let pct = format!("{}%", (prog * 100.0).round() as i64);
1261            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());
1262        }
1263        _ => {}
1264    }
1265    view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
1266}
1267
1268fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
1269    let cartesian = is_cartesian(style);
1270    let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
1271    let max = cartesian_max(series, style, nslots);
1272
1273    let plot = if cartesian {
1274        let svg = cartesian_svg(series, style, axis, max, nslots);
1275        let yaxis = if axis {
1276            let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
1277                .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
1278                .collect();
1279            Some(view! { <div class="chart-yaxis">{ticks}</div> })
1280        } else {
1281            None
1282        };
1283        view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
1284    } else {
1285        circular_svg(series, style).into_any()
1286    };
1287
1288    let label_row = if cartesian && !labels.is_empty() {
1289        let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
1290        Some(view! { <div class="chart-labels">{items}</div> })
1291    } else {
1292        None
1293    };
1294
1295    let legend_row = if legend {
1296        let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
1297            let sw = format!("background:{}", chart_color(i, s));
1298            let name = s.name.clone();
1299            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
1300        }).collect();
1301        Some(view! { <div class="chart-legend">{items}</div> })
1302    } else {
1303        None
1304    };
1305
1306    view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
1307}
1308
1309// --------------------------- region chart ---------------------------
1310
1311/// Palette as RGB (parallel to `CHART_PALETTE`) so region charts can compute label contrast.
1312const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
1313    [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
1314
1315/// The resolved fill RGB for region `i` (explicit override → palette).
1316fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
1317    match r.color {
1318        Some(c) => (c.r, c.g, c.b),
1319        None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
1320    }
1321}
1322
1323/// Black or white label text, whichever reads on the given fill (perceived luminance).
1324fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
1325    let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
1326    if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
1327}
1328
1329fn region_color(i: usize, r: &ChartRegion) -> String {
1330    let (r8, g8, b8) = region_rgb(i, r);
1331    format!("#{r8:02x}{g8:02x}{b8:02x}")
1332}
1333
1334// A variable-width stacked-region / coverage-gap chart: absolute-positioned region rectangles in
1335// the [0,x_max]×[0,y_max] plane, horizontal ref lines + chips, an irregular x-axis, an optional
1336// right-side bracket, and a legend. The web twin of the Compose/SwiftUI RegionChart renderers.
1337fn region_chart_view(
1338    regions: &[ChartRegion],
1339    ticks: &[ChartTick],
1340    x_max: f32,
1341    y_max: f32,
1342    ref_lines: &[ChartRefLine],
1343    bracket: &Option<ChartBracket>,
1344    legend: &[ChartLegendItem],
1345) -> AnyView {
1346    let xm = x_max.max(1e-6);
1347    let ym = y_max.max(1e-6);
1348
1349    let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
1350        let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
1351        let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
1352        let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
1353        let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
1354        let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
1355        let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
1356        let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
1357        let label = r.label.clone();
1358        view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
1359    }).collect();
1360
1361    // The reference lines span the full plot width; their value chips sit in the right margin
1362    // (outside the plot), like the original — so the line clearly runs to the plot's edge.
1363    let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
1364        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
1365        let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
1366        view! { <div class=cls style=style></div> }
1367    }).collect();
1368    let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
1369        let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
1370        let label = rl.label.clone();
1371        view! { <div class="rchart-chip" style=style>{label}</div> }
1372    }).collect();
1373
1374    let bracket_div = bracket.as_ref().map(|b| {
1375        let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
1376        let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
1377        let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
1378        let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
1379        view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
1380    });
1381
1382    let yticks: Vec<_> = (0..=4).rev().map(|k| {
1383        let v = ym * k as f32 / 4.0;
1384        view! { <span class="chart-tick">{fmt_tick(v)}</span> }
1385    }).collect();
1386
1387    let xticks: Vec<_> = ticks.iter().map(|t| {
1388        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
1389        let label = t.label.clone();
1390        view! { <span class="rchart-xtick" style=style>{label}</span> }
1391    }).collect();
1392
1393    // Axis tick marks (notches on the L-shaped axis): horizontal on the y-axis at each value,
1394    // vertical on the x-axis at each irregular break — drawn over the bands at the plot edges.
1395    let ytick_marks: Vec<_> = (0..=4).map(|k| {
1396        let style = format!("bottom:{:.3}%", k as f32 * 25.0);
1397        view! { <div class="rchart-ytick" style=style></div> }
1398    }).collect();
1399    let xtick_marks: Vec<_> = ticks.iter().map(|t| {
1400        let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
1401        view! { <div class="rchart-xtickmark" style=style></div> }
1402    }).collect();
1403
1404    let legend_row = if legend.is_empty() {
1405        None
1406    } else {
1407        let items: Vec<_> = legend.iter().map(|l| {
1408            let sw = format!("background:{}", hex(l.color));
1409            let name = l.label.clone();
1410            view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
1411        }).collect();
1412        Some(view! { <div class="chart-legend">{items}</div> })
1413    };
1414
1415    view! {
1416        <div class="rchart">
1417            <div class="rchart-row">
1418                <div class="rchart-yaxis">{yticks}</div>
1419                <div class="rchart-plotwrap">
1420                    <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
1421                    {chip_divs}{bracket_div}
1422                </div>
1423            </div>
1424            <div class="rchart-xaxis">{xticks}</div>
1425            {legend_row}
1426        </div>
1427    }.into_any()
1428}