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