Skip to main content

mobiler_core/
lib.rs

1//! Mobiler runtime — the developer-facing API.
2//!
3//! Implement [`MobilerApp`] with your **typed** events, model, and view (built
4//! from the [builders](#functions)). Mobiler wraps it in [`MobilerShell`], a
5//! Crux app speaking the fixed UI ABI ([`mobiler_ui`]); you never touch the wire
6//! protocol. Device APIs are capabilities via [`Cx`].
7
8use std::marker::PhantomData;
9
10pub mod format;
11pub use format::{Currency, Locale};
12
13use crux_core::{
14    App, Command,
15    capability::Operation,
16    macros::effect,
17    render::{RenderOperation, render},
18};
19use facet::Facet;
20use serde::{Deserialize, Serialize, de::DeserializeOwned};
21
22pub use mobiler_ui::{
23    Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
24    ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
25    ImageRatio, ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
26    TextStyle, Theme, Tone, Widget,
27};
28
29// ============================ capabilities ============================
30
31/// Built-in capabilities the generic shell fulfils.
32#[effect(facet_typegen)]
33#[derive(Debug)]
34pub enum Effect {
35    Render(RenderOperation),
36    /// Fire-and-forget plugin call (shell does not resolve).
37    PluginNotify(PluginNotify),
38    /// Request/response plugin call (shell resolves with a [`PluginResponse`]).
39    Plugin(PluginCall),
40    /// Long-lived subscription: the shell starts a native source and resolves
41    /// **repeatedly** (a [`PluginResponse`] per event) until it's torn down. Powers
42    /// [`Cx::subscribe`]. Stop it with [`Cx::unsubscribe`] (a `stream`/`unsubscribe`
43    /// notify keyed by [`PluginStreamCall::key`]).
44    PluginStream(PluginStreamCall),
45}
46
47#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct PluginNotify {
49    pub plugin: String,
50    pub op: String,
51    pub input: String,
52}
53impl Operation for PluginNotify {
54    type Output = ();
55}
56
57#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
58pub struct PluginCall {
59    pub plugin: String,
60    pub op: String,
61    pub input: String,
62}
63impl Operation for PluginCall {
64    type Output = PluginResponse;
65}
66
67/// A streaming plugin subscription (powers [`Effect::PluginStream`]). Like
68/// [`PluginCall`] but carries a caller-chosen `key` so the subscription can be torn
69/// down ([`Cx::unsubscribe`]) — the shell registers the native source under `key`.
70#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
71pub struct PluginStreamCall {
72    pub key: String,
73    pub plugin: String,
74    pub op: String,
75    pub input: String,
76}
77impl Operation for PluginStreamCall {
78    type Output = PluginResponse;
79}
80
81#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginResponse {
83    pub ok: bool,
84    pub output: String,
85}
86
87type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
88/// A streaming continuation — fires once **per event** (so `Fn`, not `FnOnce`).
89type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
90
91/// Effects an app requests during `update`, generic over the app event type so
92/// continuations stay fully typed.
93pub struct Cx<E> {
94    notifications: Vec<PluginNotify>,
95    requests: Vec<(PluginCall, Continuation<E>)>,
96    streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
97}
98
99impl<E> Default for Cx<E> {
100    fn default() -> Self {
101        Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
102    }
103}
104
105impl<E> Cx<E> {
106    /// Fire-and-forget call to a native plugin.
107    pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
108        self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
109    }
110
111    /// Request/response call: when the plugin replies, `then(response)` produces
112    /// the typed event delivered back to your `update`.
113    pub fn plugin(
114        &mut self,
115        plugin: impl Into<String>,
116        op: impl Into<String>,
117        input: impl Into<String>,
118        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
119    ) {
120        self.requests
121            .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
122    }
123
124    /// Subscribe to a streaming plugin: the shell starts a native source and delivers
125    /// **every** event it produces to `on_event` (which fires repeatedly, once per
126    /// event), each producing a typed event into your `update`. `key` is a
127    /// caller-chosen id for this subscription — pass the same `key` to
128    /// [`unsubscribe`](Self::unsubscribe) to stop it. Call `subscribe` **once** per
129    /// key (e.g. in [`init`](MobilerApp::init) or on a connect event); calling it
130    /// again with a live key starts a second source.
131    pub fn subscribe(
132        &mut self,
133        key: impl Into<String>,
134        plugin: impl Into<String>,
135        op: impl Into<String>,
136        input: impl Into<String>,
137        on_event: impl Fn(PluginResponse) -> E + Send + 'static,
138    ) {
139        self.streams.push((
140            PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
141            Box::new(on_event),
142        ));
143    }
144
145    /// Stop the streaming subscription started under `key` by [`subscribe`](Self::subscribe).
146    /// The shell tears down the native source registered under `key`, so it stops
147    /// producing events. No-op if `key` isn't subscribed.
148    pub fn unsubscribe(&mut self, key: impl Into<String>) {
149        self.notify("stream", "unsubscribe", key);
150    }
151
152    /// Persist `data` (handed back to [`MobilerApp::restore`] on next startup).
153    pub fn save(&mut self, data: impl Into<String>) {
154        self.notify("storage", "save", data);
155    }
156
157    /// Copy `text` to the system clipboard (built-in `clipboard` capability).
158    pub fn copy(&mut self, text: impl Into<String>) {
159        self.notify("clipboard", "copy", text);
160    }
161
162    /// Open the system share sheet with `text` (built-in `share` capability).
163    pub fn share(&mut self, text: impl Into<String>) {
164        self.notify("share", "text", text);
165    }
166
167    /// Open `url` in the platform browser / default handler (built-in `browser`
168    /// capability). Fire-and-forget: the app leaves the foreground.
169    pub fn open_url(&mut self, url: impl Into<String>) {
170        self.notify("browser", "open", url);
171    }
172
173    /// Show a transient toast / snackbar with `text` (built-in `toast` capability).
174    pub fn toast(&mut self, text: impl Into<String>) {
175        self.notify("toast", "show", text);
176    }
177
178    /// Fire a haptic tap (built-in `haptics` capability). `style` is `"light"`,
179    /// `"medium"`, or `"heavy"`; unknown styles fall back to medium.
180    pub fn haptic(&mut self, style: impl Into<String>) {
181        self.notify("haptics", style, "");
182    }
183
184    /// Perform an HTTP request via the shell's built-in `http` capability. When it
185    /// completes, `then(response)` produces the typed event delivered back to
186    /// `update` — `response.output` is the body, `response.ok` is success (2xx).
187    /// Rides the request/response plugin mechanism, so it resolves asynchronously.
188    pub fn http(
189        &mut self,
190        method: impl Into<String>,
191        url: impl Into<String>,
192        body: Option<String>,
193        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
194    ) {
195        #[derive(Serialize)]
196        struct HttpReq {
197            url: String,
198            body: Option<String>,
199        }
200        let input = serde_json::to_string(&HttpReq { url: url.into(), body })
201            .expect("serialize http request");
202        self.plugin("http", method, input, then);
203    }
204
205    /// `GET url`, delivering the response to `then`.
206    pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
207        self.http("GET", url, None, then);
208    }
209    /// `POST url` with a JSON `body`, delivering the response to `then`.
210    pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
211        self.http("POST", url, Some(body.into()), then);
212    }
213    /// `PATCH url` with a JSON `body`, delivering the response to `then`.
214    pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
215        self.http("PATCH", url, Some(body.into()), then);
216    }
217    /// `DELETE url`, delivering the response to `then`.
218    pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
219        self.http("DELETE", url, None, then);
220    }
221
222    /// Query the device model/name via the built-in `device` capability; the result
223    /// (`response.output`, e.g. "Google Pixel 7" / "Apple iPhone (iOS 18.0)") is
224    /// delivered to `then`.
225    pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
226        self.plugin("device", "model", "", then);
227    }
228
229    /// Query the device's preferred locale as a BCP-47 language tag (e.g. `"de-CH"`, `"en-US"`)
230    /// via the built-in `device` capability; `then` receives it in `response.output`. Pair with
231    /// [`Locale::from_tag`](crate::format::Locale::from_tag) to choose the app's language /
232    /// formatting locale at startup. Works on iOS, Android, and web.
233    pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
234        self.plugin("device", "locale", "", then);
235    }
236
237    /// Let the user pick an image (built-in `photo` capability — the system photo
238    /// picker, no permission required). `then` receives the result: on success
239    /// `response.ok` is `true` and `response.output` is a local image URI you can
240    /// hand straight to the `image(...)` widget; on cancel, `ok` is `false`.
241    pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
242        self.plugin("photo", "pick", "", then);
243    }
244
245    /// Capture a photo with the device camera (built-in `camera` capability — launches
246    /// the system camera). `then` receives the result: on success `response.ok` is
247    /// `true` and `response.output` is a local image URI you can hand straight to the
248    /// `image(...)` widget; on cancel, `ok` is `false`. iOS requires an
249    /// `NSCameraUsageDescription` (the template ships one, opt-in); Android captures via
250    /// the system camera app, so no extra runtime permission is needed.
251    pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
252        self.plugin("camera", "capture", "", then);
253    }
254
255    /// Ask the user to confirm via a native dialog (built-in `dialog` capability).
256    /// `then` receives the choice: `response.ok` is `true` if confirmed, `false` if
257    /// cancelled/dismissed. Resolves asynchronously (the user replies whenever).
258    pub fn confirm(
259        &mut self,
260        title: impl Into<String>,
261        message: impl Into<String>,
262        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
263    ) {
264        #[derive(Serialize)]
265        struct Confirm {
266            title: String,
267            message: String,
268        }
269        let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
270            .expect("serialize confirm");
271        self.plugin("dialog", "confirm", input, then);
272    }
273
274    /// Let the user pick a date via the native date picker (built-in `datetime`
275    /// capability). On success `response.ok` is `true` and `response.output` is the
276    /// chosen date as an ISO `YYYY-MM-DD` string; on cancel/dismiss, `ok` is `false`.
277    /// Resolves asynchronously (the user replies whenever).
278    pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
279        self.plugin("datetime", "date", "", then);
280    }
281
282    /// Let the user pick a time via the native time picker (built-in `datetime`
283    /// capability). On success `response.ok` is `true` and `response.output` is the
284    /// chosen time as a 24-hour `HH:MM` string; on cancel/dismiss, `ok` is `false`.
285    /// Resolves asynchronously (the user replies whenever).
286    pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
287        self.plugin("datetime", "time", "", then);
288    }
289}
290
291// ============================ the app trait ============================
292
293/// What a Mobiler app implements. Write typed domain events; Mobiler serializes
294/// them into opaque tokens behind the scenes.
295pub trait MobilerApp: Default {
296    type Event: Serialize + DeserializeOwned + Send + 'static;
297    type Model: Default;
298
299    fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
300
301    fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
302        let _ = (id, value, model, cx);
303    }
304
305    /// Restore persisted state on startup. `data` is whatever you last passed to
306    /// `cx.save` (or empty if nothing was saved). Default: ignore.
307    fn restore(&self, data: &str, model: &mut Self::Model) {
308        let _ = (data, model);
309    }
310
311    /// Run once on startup, after [`restore`](Self::restore). The place to kick
312    /// off initial effects — e.g. fetch data with `cx.get`. Default: nothing.
313    fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
314        let _ = (model, cx);
315    }
316
317    fn view(&self, model: &Self::Model) -> Widget;
318}
319
320/// Crux adapter: turns a [`MobilerApp`] into an app speaking the fixed ABI.
321pub struct MobilerShell<A>(PhantomData<fn() -> A>);
322
323impl<A> Default for MobilerShell<A> {
324    fn default() -> Self {
325        Self(PhantomData)
326    }
327}
328
329impl<A: MobilerApp> App for MobilerShell<A> {
330    type Event = Action;
331    type Model = A::Model;
332    type ViewModel = Widget;
333    type Effect = Effect;
334
335    fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
336        let app = A::default();
337        let mut cx = Cx::<A::Event>::default();
338        match action {
339            Action::Fired { token } => {
340                if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
341                    app.update(event, model, &mut cx);
342                }
343            }
344            Action::Input { id, value } => app.input(&id, value, model, &mut cx),
345            Action::Restore { data } => app.restore(&data, model),
346            Action::Start => app.init(model, &mut cx),
347        }
348        let mut commands: Vec<Command<Effect, Action>> = Vec::new();
349        for op in cx.notifications {
350            commands.push(Command::notify_shell(op).build());
351        }
352        for (op, then) in cx.requests {
353            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
354                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
355            }));
356        }
357        for (op, then) in cx.streams {
358            // A long-lived shell stream: `then_send` fires `then` once per emitted
359            // event (it's `Fn`), each re-entering `update` as a `Fired` action.
360            commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
361                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
362            }));
363        }
364        commands.push(render());
365        Command::all(commands)
366    }
367
368    fn view(&self, model: &Self::Model) -> Widget {
369        A::default().view(model)
370    }
371}
372
373// ============================ navigation ============================
374
375/// A navigation stack the app holds in its `Model`. The **core owns the stack**
376/// (single source of truth); the framework reads its `route`/`depth` to drive
377/// the shell's push/pop transitions and back button.
378///
379/// `R` is your screen-route type (typically a small enum). Hold it in the model,
380/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
381/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
382/// `pop` so the back affordance works.
383///
384/// ```ignore
385/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
386/// // model.nav: Nav<Route> = Nav::new(Route::List);
387/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
388/// //         Msg::Back      => model.nav.pop(),
389/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
390/// ```
391#[derive(Clone, Debug)]
392pub struct Nav<R> {
393    stack: Vec<R>,
394}
395
396impl<R: Clone + Serialize> Nav<R> {
397    /// A stack containing a single root route.
398    #[must_use]
399    pub fn new(root: R) -> Self {
400        Self { stack: vec![root] }
401    }
402    /// Push a new screen onto the stack.
403    pub fn push(&mut self, route: R) {
404        self.stack.push(route);
405    }
406    /// Pop the top screen (no-op at the root).
407    pub fn pop(&mut self) {
408        if self.stack.len() > 1 {
409            self.stack.pop();
410        }
411    }
412    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
413    pub fn reset(&mut self, root: R) {
414        self.stack = vec![root];
415    }
416    /// The current (top) route — what `view` should render.
417    #[must_use]
418    pub fn current(&self) -> &R {
419        self.stack.last().expect("nav stack is never empty")
420    }
421    /// Stack depth (root = 1).
422    #[must_use]
423    pub fn depth(&self) -> u32 {
424        self.stack.len() as u32
425    }
426    /// Whether there is a screen to pop back to.
427    #[must_use]
428    pub fn can_go_back(&self) -> bool {
429        self.stack.len() > 1
430    }
431    /// Stable identity of the current route (its serialization), used by the shell
432    /// to decide when to animate a transition.
433    fn route_key(&self) -> String {
434        serde_json::to_string(self.current()).expect("serialize route")
435    }
436}
437
438// ============================ widget builders ============================
439// Action-carrying builders take a TYPED event and serialize it into a token.
440
441fn tok<E: Serialize>(event: E) -> String {
442    serde_json::to_string(&event).expect("serialize event")
443}
444
445#[must_use]
446pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
447    Widget::Text { content: content.into(), style }
448}
449#[must_use]
450pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
451#[must_use]
452pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
453#[must_use]
454pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
455#[must_use]
456pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
457#[must_use]
458pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
459
460#[must_use]
461pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
462    Widget::Image { source: source.into(), shape, ratio }
463}
464#[must_use]
465pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
466    Widget::Badge { label: label.into(), tone }
467}
468/// A small colored identity dot.
469#[must_use]
470pub fn color_dot(color: ProjectColor) -> Widget {
471    Widget::ColorDot { color }
472}
473#[must_use]
474pub fn divider() -> Widget { Widget::Divider }
475/// A progress bar (`Some(0.0..=1.0)`) or an indeterminate spinner (`None`).
476#[must_use]
477pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
478/// A shimmer placeholder shown while content loads.
479#[must_use]
480pub fn skeleton() -> Widget { Widget::Skeleton }
481/// An in-app PDF viewer for the document at `url` (remote https URL or local file URI) — rendered
482/// natively per platform (PDFKit / `PdfRenderer` / `<iframe>`). The app just supplies the URL, e.g.
483/// a backend-generated report. Give it room (place in a sized container or a scroller).
484#[must_use]
485pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
486/// A controllable native video player for `url` (remote MP4/HLS or a local file URI), rendered with the
487/// native player per platform (AVPlayer / Media3 ExoPlayer / `<video>`). `id` routes the ~once-per-second
488/// position into `input(id, InputValue::Int(position_ms))`; build it fresh each render with the current
489/// `playing` (play/pause) + `seek_to_ms` (the shell jumps when this CHANGES; `-1` = no seek). `on_ended`
490/// fires when the clip finishes. Defaults: controls shown, not looping/muted — tune with
491/// [`with_loop`]/[`with_muted`]/[`without_controls`]. Give it room (a sized container or a card).
492#[must_use]
493pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
494    Widget::Video {
495        url: url.into(),
496        id: id.into(),
497        playing,
498        seek_to_ms,
499        controls: true,
500        looping: false,
501        muted: false,
502        on_ended: Some(tok(on_ended)),
503    }
504}
505/// Loop a [`video_player`] (restart on end). No-op on non-Video widgets.
506#[must_use]
507pub fn with_loop(widget: Widget) -> Widget {
508    match widget {
509        Widget::Video { url, id, playing, seek_to_ms, controls, muted, on_ended, .. } =>
510            Widget::Video { url, id, playing, seek_to_ms, controls, looping: true, muted, on_ended },
511        other => other,
512    }
513}
514/// Start a [`video_player`] muted (needed for reliable autoplay). No-op on non-Video widgets.
515#[must_use]
516pub fn with_muted(widget: Widget) -> Widget {
517    match widget {
518        Widget::Video { url, id, playing, seek_to_ms, controls, looping, on_ended, .. } =>
519            Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted: true, on_ended },
520        other => other,
521    }
522}
523/// Hide the native transport controls on a [`video_player`] (the app drives it). No-op otherwise.
524#[must_use]
525pub fn without_controls(widget: Widget) -> Widget {
526    match widget {
527        Widget::Video { url, id, playing, seek_to_ms, looping, muted, on_ended, .. } =>
528            Widget::Video { url, id, playing, seek_to_ms, controls: false, looping, muted, on_ended },
529        other => other,
530    }
531}
532/// A single unnamed series wrapping `values` — the back-compat shape for `bar_chart`/`line_chart`.
533fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
534    vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
535}
536
537/// A bar chart of `values` (normalized to the max), with optional per-value `labels`.
538/// Single-series, no axis or legend — for richer charts use [`chart`].
539#[must_use]
540pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
541    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
542}
543/// A line chart of `values` (normalized to the max), with optional per-value `labels`.
544/// Single-series, no axis or legend — for richer charts use [`chart`].
545#[must_use]
546pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
547    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
548}
549/// A multi-series chart in the given `style`, with optional x-axis `labels`, y-`axis` gridlines/
550/// ticks (cartesian styles), and a series `legend`. The general builder behind the convenience
551/// constructors below.
552#[must_use]
553pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
554    Widget::Chart { series, labels, style, axis, legend }
555}
556/// Bars stacked to a total per x-slot. Axis + legend on by default.
557#[must_use]
558pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
559    chart(series, labels, ChartStyle::StackedBar, true, true)
560}
561/// Bars where each x-slot fills to 100% — series as proportions. Legend on, no value axis.
562#[must_use]
563pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
564    chart(series, labels, ChartStyle::StackedBar100, false, true)
565}
566/// A pie chart — each series is one wedge sized by its magnitude. Legend on.
567#[must_use]
568pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
569    chart(series, vec![], ChartStyle::Pie, false, true)
570}
571/// A donut chart (pie with a center hole). Legend on.
572#[must_use]
573pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
574    chart(series, vec![], ChartStyle::Donut, false, true)
575}
576/// Concentric progress rings — one per series, swept by `sum(values) / goal`. Legend on.
577/// Give each series a goal via [`ChartSeries::with_goal`].
578#[must_use]
579pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
580    chart(series, vec![], ChartStyle::Rings, false, true)
581}
582/// A single radial gauge — the first series' `value / goal` with the number in the center.
583#[must_use]
584pub fn gauge_chart(series: ChartSeries) -> Widget {
585    chart(vec![series], vec![], ChartStyle::Gauge, false, false)
586}
587
588/// A variable-width stacked-region ("coverage-gap" / Marimekko) chart. `regions` are rectangles in
589/// the `[0, x_max] × [0, y_max]` plane (build with [`ChartRegion::new`]); `ticks` label the
590/// irregular x-axis; `ref_lines` are horizontal target/max lines ([`ChartRefLine::target`]/`::max`);
591/// `legend` names the colors. Add a right-side bracket annotation with [`with_bracket`].
592#[must_use]
593pub fn region_chart(
594    regions: Vec<ChartRegion>,
595    ticks: Vec<ChartTick>,
596    x_max: f32,
597    y_max: f32,
598    ref_lines: Vec<ChartRefLine>,
599    legend: Vec<ChartLegendItem>,
600) -> Widget {
601    Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
602}
603
604/// Attach a right-side bracket annotation to a [`region_chart`] (no-op on any other widget).
605#[must_use]
606pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
607    match widget {
608        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
609            Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
610        }
611        other => other,
612    }
613}
614
615/// Days in `month` (1–12) of `year`, leap-year aware.
616fn days_in_month(year: u32, month: u8) -> u8 {
617    match month {
618        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
619        4 | 6 | 9 | 11 => 30,
620        2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
621        _ => 30,
622    }
623}
624
625/// Weekday of `year-month-day` as 0=Sunday..6=Saturday (Sakamoto's algorithm).
626fn weekday(year: u32, month: u8, day: u8) -> u8 {
627    const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
628    let y = if month < 3 { year - 1 } else { year };
629    let m = month as usize - 1;
630    ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
631}
632
633/// An inline month calendar for `year`/`month` (1–12). `on_day(d)` builds the tap event for each
634/// day `d` in the month; `selected` highlights a day. Leading blanks + weekday header are handled
635/// by the shells from the computed `first_weekday`.
636#[must_use]
637pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
638    let n = days_in_month(year, month);
639    let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
640    Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
641}
642
643/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
644/// tappable. On web the actions render inline (no gesture).
645#[must_use]
646pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
647    Widget::SwipeAction {
648        child: Box::new(child),
649        actions: actions
650            .into_iter()
651            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
652            .collect(),
653    }
654}
655#[must_use]
656pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
657
658#[must_use]
659pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
660#[must_use]
661pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
662#[must_use]
663pub fn card(child: Widget, style: CardStyle) -> Widget {
664    Widget::Card { child: Box::new(child), style, on_press: None }
665}
666/// A tappable card carrying a typed press event.
667#[must_use]
668pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
669    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
670}
671/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
672/// darkened background and the rest render on top.
673#[must_use]
674pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
675    Widget::Box { children, align, scrim }
676}
677#[must_use]
678pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
679/// Horizontally scrolling row of children (a carousel / chip rail).
680#[must_use]
681pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
682/// A circular avatar image.
683#[must_use]
684pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
685/// A circular avatar image with a colored status dot.
686#[must_use]
687pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
688    Widget::Avatar { source: source.into(), status: Some(status) }
689}
690/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
691#[must_use]
692pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
693/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
694#[must_use]
695pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
696    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
697}
698
699#[must_use]
700pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
701    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
702}
703#[must_use]
704pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
705    Widget::IconButton { icon, on_press: tok(on_press) }
706}
707#[must_use]
708pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
709    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
710}
711#[must_use]
712pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
713    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
714}
715/// A text field with full control over [`FieldKind`] and an optional inline
716/// validation `error`. The kind-specific helpers below ([`secure_field`],
717/// [`email_field`], …) wrap this for the common cases.
718#[must_use]
719pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
720    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
721}
722/// A masked password field ([`FieldKind::Secure`]).
723#[must_use]
724pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
725    field(id, placeholder, value, FieldKind::Secure, None)
726}
727/// An email-keyboard field ([`FieldKind::Email`]).
728#[must_use]
729pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
730    field(id, placeholder, value, FieldKind::Email, None)
731}
732/// A whole-number keypad field ([`FieldKind::Number`]).
733#[must_use]
734pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
735    field(id, placeholder, value, FieldKind::Number, None)
736}
737/// A decimal keypad field ([`FieldKind::Decimal`]).
738#[must_use]
739pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
740    field(id, placeholder, value, FieldKind::Decimal, None)
741}
742/// A phone-keypad field ([`FieldKind::Phone`]).
743#[must_use]
744pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
745    field(id, placeholder, value, FieldKind::Phone, None)
746}
747/// A URL-keyboard field ([`FieldKind::Url`]).
748#[must_use]
749pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
750    field(id, placeholder, value, FieldKind::Url, None)
751}
752/// A growable multi-line text area ([`FieldKind::Multiline`]).
753#[must_use]
754pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
755    field(id, placeholder, value, FieldKind::Multiline, None)
756}
757/// Attach an inline validation message to a [`Widget::TextField`], marking it
758/// invalid. No-op on any other widget.
759#[must_use]
760pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
761    match widget {
762        Widget::TextField { id, placeholder, value, kind, .. } =>
763            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
764        other => other,
765    }
766}
767/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
768#[must_use]
769pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
770    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
771}
772/// One option in a [`segmented`] control, carrying a typed selection event.
773#[must_use]
774pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
775    Segment { label: label.into(), selected, on_select: tok(on_select) }
776}
777/// A single-choice segmented control (exclusive options in a pill).
778#[must_use]
779pub fn segmented(segments: Vec<Segment>) -> Widget {
780    Widget::Segmented { segments }
781}
782#[must_use]
783pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
784    Widget::Toggle { id: id.into(), label: label.into(), value }
785}
786#[must_use]
787pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
788    Widget::Checkbox { id: id.into(), label: label.into(), value }
789}
790#[must_use]
791pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
792    Widget::Slider { id: id.into(), value, max }
793}
794#[must_use]
795pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
796    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
797}
798
799/// A bottom-nav tab carrying a typed selection event (label-only).
800#[must_use]
801pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
802    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
803}
804
805/// A bottom-nav tab with a leading icon (icon tab bar).
806#[must_use]
807pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
808    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
809}
810
811/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
812/// theme-as-data (the shell themes the whole app from it).
813#[must_use]
814pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
815    let title = title.into();
816    // route defaults to the title; root depth = 1.
817    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, theme: None, fab: None, sheet: None, on_refresh: None, refreshing: false, depth: 1 }
818}
819
820/// Like [`scaffold`], but the top bar (and the system back button) navigate back
821/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
822/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
823#[must_use]
824pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
825    let title = title.into();
826    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, theme: None, fab: None, sheet: None, on_refresh: None, refreshing: false, depth: 2 }
827}
828
829/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
830/// serialization) and `depth` (stack depth) so the shell animates transitions,
831/// and shows a back affordance (top-bar arrow + system back button) firing
832/// `on_back` whenever the stack can pop.
833#[must_use]
834pub fn nav_scaffold<R, E>(
835    title: impl Into<String>,
836    dark_mode: bool,
837    tabs: Vec<Tab>,
838    body: Widget,
839    nav: &Nav<R>,
840    on_back: E,
841) -> Widget
842where
843    R: Clone + Serialize,
844    E: Serialize,
845{
846    Widget::Scaffold {
847        title: title.into(),
848        body: Box::new(body),
849        tabs,
850        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
851        dark_mode,
852        theme: None,
853        fab: None,
854        sheet: None,
855        on_refresh: None,
856        refreshing: false,
857        route: nav.route_key(),
858        depth: nav.depth(),
859    }
860}
861
862/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
863/// other widget. Lets an app brand its UI without new scaffold builder overloads:
864/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
865pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
866    match widget {
867        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
868            title,
869            body,
870            tabs,
871            back,
872            dark_mode,
873            theme: Some(theme),
874            fab,
875            sheet,
876            on_refresh,
877            refreshing,
878            route,
879            depth,
880        },
881        other => other,
882    }
883}
884
885/// Anchor a floating action button over a scaffold's body (the raised primary action).
886/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
887pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
888    match widget {
889        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
890            title,
891            body,
892            tabs,
893            back,
894            dark_mode,
895            theme,
896            fab: Some(Fab { icon, on_press: tok(on_press) }),
897            sheet,
898            on_refresh,
899            refreshing,
900            route,
901            depth,
902        },
903        other => other,
904    }
905}
906
907/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
908/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
909pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
910    match widget {
911        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
912            title: t,
913            body,
914            tabs,
915            back,
916            dark_mode,
917            theme,
918            fab,
919            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
920            on_refresh,
921            refreshing,
922            route,
923            depth,
924        },
925        other => other,
926    }
927}
928
929/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
930/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
931/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
932pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
933    match widget {
934        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
935            title,
936            body,
937            tabs,
938            back,
939            dark_mode,
940            theme,
941            fab,
942            sheet,
943            on_refresh: Some(tok(on_refresh)),
944            refreshing,
945            route,
946            depth,
947        },
948        // Pull-to-refresh on a LazyList's top — same API as on a Scaffold. Leaves the load-more
949        // fields intact.
950        Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
951            children,
952            on_load_more,
953            loading,
954            has_more,
955            on_refresh: Some(tok(on_refresh)),
956            refreshing,
957        },
958        other => other,
959    }
960}
961
962/// A scrollable list for long/paged feeds that fires `on_load_more` when the user scrolls near the
963/// end. The app owns the state: append to `children` on each load-more event, set `loading` true
964/// while the page loads (the shell shows a spinner and won't re-fire), and `has_more=false` when
965/// the feed is exhausted. Add pull-to-refresh at the top with [`with_refresh`]. Give it room — a
966/// `LazyList` nested in a scrollable body needs a bounded height to scroll on its own.
967#[must_use]
968pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
969    Widget::LazyList {
970        children,
971        on_load_more: Some(tok(on_load_more)),
972        loading,
973        has_more,
974        on_refresh: None,
975        refreshing: false,
976    }
977}
978
979/// A scrollable list with no load-more and no refresh — a plain virtualized list of `children`.
980#[must_use]
981pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
982    Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
983}
984
985#[cfg(test)]
986mod tests {
987    use super::*;
988    use serde::Serialize;
989
990    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
991    enum Route {
992        Home,
993        Detail(u32),
994    }
995
996    #[derive(Serialize)]
997    enum Ev {
998        Tap,
999        Open(u32),
1000    }
1001
1002    // ---- Nav ----
1003
1004    #[test]
1005    fn nav_push_pop_depth() {
1006        let mut nav = Nav::new(Route::Home);
1007        assert_eq!(nav.depth(), 1);
1008        assert!(!nav.can_go_back());
1009
1010        nav.push(Route::Detail(7));
1011        assert_eq!(nav.depth(), 2);
1012        assert!(nav.can_go_back());
1013        assert!(matches!(nav.current(), Route::Detail(7)));
1014
1015        nav.pop();
1016        assert_eq!(nav.depth(), 1);
1017        assert!(matches!(nav.current(), Route::Home));
1018
1019        nav.pop(); // no-op at the root
1020        assert_eq!(nav.depth(), 1);
1021    }
1022
1023    #[test]
1024    fn nav_reset_replaces_stack() {
1025        let mut nav = Nav::new(Route::Home);
1026        nav.push(Route::Detail(1));
1027        nav.push(Route::Detail(2));
1028        nav.reset(Route::Detail(9));
1029        assert_eq!(nav.depth(), 1);
1030        assert!(matches!(nav.current(), Route::Detail(9)));
1031    }
1032
1033    #[test]
1034    fn nav_route_key_is_serialization() {
1035        let nav = Nav::new(Route::Detail(3));
1036        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1037    }
1038
1039    // ---- builders ----
1040
1041    #[test]
1042    fn scaffold_sets_route_depth_and_no_back() {
1043        match scaffold("Home", false, vec![], text("x")) {
1044            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1045                assert_eq!(route, "Home");
1046                assert_eq!(depth, 1);
1047                assert!(back.is_none());
1048                assert!(!dark_mode);
1049            }
1050            other => panic!("expected Scaffold, got {other:?}"),
1051        }
1052    }
1053
1054    #[test]
1055    fn scaffold_back_is_depth_2_with_back() {
1056        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1057            Widget::Scaffold { depth, back, dark_mode, .. } => {
1058                assert_eq!(depth, 2);
1059                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1060                assert!(dark_mode);
1061            }
1062            other => panic!("expected Scaffold, got {other:?}"),
1063        }
1064    }
1065
1066    #[test]
1067    fn nav_scaffold_shows_back_only_when_poppable() {
1068        let mut nav = Nav::new(Route::Home);
1069        // at the root: no back, depth 1, route = serialized current route
1070        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1071            Widget::Scaffold { back, depth, route, .. } => {
1072                assert!(back.is_none());
1073                assert_eq!(depth, 1);
1074                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1075            }
1076            other => panic!("expected Scaffold, got {other:?}"),
1077        }
1078        // after a push: back present, depth 2
1079        nav.push(Route::Detail(2));
1080        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1081            Widget::Scaffold { back, depth, .. } => {
1082                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1083                assert_eq!(depth, 2);
1084            }
1085            other => panic!("expected Scaffold, got {other:?}"),
1086        }
1087    }
1088
1089    #[test]
1090    fn buttons_carry_serialized_event_tokens() {
1091        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1092            Widget::Button { label, on_press, .. } => {
1093                assert_eq!(label, "Go");
1094                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1095            }
1096            other => panic!("expected Button, got {other:?}"),
1097        }
1098        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1099            Widget::Card { on_press, .. } => {
1100                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1101            }
1102            other => panic!("expected Card, got {other:?}"),
1103        }
1104        // a plain card is not tappable
1105        match card(text("c"), CardStyle::Elevated) {
1106            Widget::Card { on_press, .. } => assert!(on_press.is_none()),
1107            other => panic!("expected Card, got {other:?}"),
1108        }
1109    }
1110
1111    // ---- Cx capabilities ----
1112
1113    #[test]
1114    fn cx_notify_and_save_enqueue_notifications() {
1115        let mut cx = Cx::<Ev>::default();
1116        cx.notify("toast", "show", "hi");
1117        cx.save("blob");
1118        assert_eq!(cx.notifications.len(), 2);
1119        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1120        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1121        assert!(cx.requests.is_empty());
1122    }
1123
1124    #[test]
1125    fn cx_http_helpers_build_requests() {
1126        let mut cx = Cx::<Ev>::default();
1127        cx.get("http://h/x", |_| Ev::Tap);
1128        cx.post("http://h/y", "hello", |_| Ev::Tap);
1129        cx.patch("http://h/z", "patch", |_| Ev::Tap);
1130        cx.delete("http://h/d", |_| Ev::Tap);
1131
1132        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1133        assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1134        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1135
1136        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1137        assert_eq!(get_input["url"], "http://h/x");
1138        assert!(get_input["body"].is_null());
1139
1140        let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1141        assert_eq!(post_input["url"], "http://h/y");
1142        assert_eq!(post_input["body"], "hello");
1143    }
1144
1145    #[test]
1146    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1147        let mut cx = Cx::<Ev>::default();
1148        cx.pick_photo(|_| Ev::Tap);
1149        cx.capture_photo(|_| Ev::Tap);
1150        assert_eq!(cx.requests.len(), 2);
1151        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1152        // carry empty input (the shell needs no parameters to launch picker/camera).
1153        assert_eq!((cx.requests[0].0.plugin.as_str(), cx.requests[0].0.op.as_str(), cx.requests[0].0.input.as_str()), ("photo", "pick", ""));
1154        assert_eq!((cx.requests[1].0.plugin.as_str(), cx.requests[1].0.op.as_str(), cx.requests[1].0.input.as_str()), ("camera", "capture", ""));
1155    }
1156
1157    #[test]
1158    fn cx_capture_photo_routes_success_and_cancel() {
1159        // Happy path: ok=true delivers the URI to the success branch.
1160        let mut cx = Cx::<Ev>::default();
1161        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1162        let (_, then) = cx.requests.pop().unwrap();
1163        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1164
1165        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1166        let mut cx = Cx::<Ev>::default();
1167        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1168        let (_, then) = cx.requests.pop().unwrap();
1169        assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1170    }
1171
1172    #[test]
1173    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1174        let mut cx = Cx::<Ev>::default();
1175        cx.copy("c");
1176        cx.share("s");
1177        cx.open_url("u");
1178        cx.toast("t");
1179        cx.haptic("heavy");
1180        let got: Vec<(&str, &str, &str)> = cx
1181            .notifications
1182            .iter()
1183            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1184            .collect();
1185        assert_eq!(
1186            got,
1187            vec![
1188                ("clipboard", "copy", "c"),
1189                ("share", "text", "s"),
1190                ("browser", "open", "u"),
1191                ("toast", "show", "t"),
1192                ("haptics", "heavy", ""), // haptic style is the op, input empty
1193            ]
1194        );
1195        assert!(cx.requests.is_empty());
1196    }
1197
1198    #[test]
1199    fn cx_device_model_is_a_request_not_a_notification() {
1200        let mut cx = Cx::<Ev>::default();
1201        cx.device_model(|_| Ev::Tap);
1202        assert!(cx.notifications.is_empty());
1203        assert_eq!(cx.requests.len(), 1);
1204        let (call, _) = &cx.requests[0];
1205        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1206    }
1207
1208    #[test]
1209    fn cx_device_locale_requests_the_device_locale_op() {
1210        let mut cx = Cx::<Ev>::default();
1211        cx.device_locale(|_| Ev::Tap);
1212        assert!(cx.notifications.is_empty());
1213        assert_eq!(cx.requests.len(), 1);
1214        let (call, _) = &cx.requests[0];
1215        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1216    }
1217
1218    #[test]
1219    fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1220        let mut cx = Cx::<Ev>::default();
1221        cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1222        // It's a stream, not a one-shot request or a notification.
1223        assert!(cx.notifications.is_empty());
1224        assert!(cx.requests.is_empty());
1225        assert_eq!(cx.streams.len(), 1);
1226        let (call, on_event) = &cx.streams[0];
1227        assert_eq!(
1228            (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1229            ("ws", "websocket", "stream", "wss://h/x")
1230        );
1231        // The continuation is `Fn` — it can map MANY events, not just one.
1232        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1233        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1234        assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1235    }
1236
1237    #[test]
1238    fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1239        let mut cx = Cx::<Ev>::default();
1240        cx.unsubscribe("ws");
1241        assert!(cx.streams.is_empty());
1242        assert_eq!(cx.notifications.len(), 1);
1243        // The shell tears down the native source registered under this key.
1244        assert_eq!(
1245            cx.notifications[0],
1246            PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1247        );
1248    }
1249
1250    #[test]
1251    fn cx_confirm_serializes_title_message_and_routes_ok() {
1252        let mut cx = Cx::<Ev>::default();
1253        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1254        let (call, then) = cx.requests.pop().unwrap();
1255        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1256        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1257        assert_eq!(v["title"], "Delete?");
1258        assert_eq!(v["message"], "This cannot be undone.");
1259        // ok=true → confirmed branch; ok=false would take the else branch.
1260        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1261    }
1262
1263    // ---- widget builders ----
1264
1265    #[test]
1266    fn text_builders_carry_their_style() {
1267        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1268        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1269        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1270        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1271        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1272    }
1273
1274    #[test]
1275    fn layout_and_content_builders_produce_their_variants() {
1276        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1277        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1278        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1279        assert!(matches!(divider(), Widget::Divider));
1280        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1281        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1282        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1283        assert!(matches!(gauge_chart(ChartSeries::new("g", vec![3.0]).with_goal(5.0)), Widget::Chart { style: ChartStyle::Gauge, series, .. } if series[0].goal == Some(5.0)));
1284        let rc = with_bracket(
1285            region_chart(
1286                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1287                vec![ChartTick::new(3.0, "3 Mt.")],
1288                65.0, 80.0,
1289                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1290                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1291            ),
1292            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1293        );
1294        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1295        // June 2026 has 30 days and starts on a Monday (weekday 1).
1296        assert!(matches!(
1297            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1298            Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1299        ));
1300        assert!(matches!(
1301            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1302            Widget::SwipeAction { actions, .. } if actions.len() == 1
1303        ));
1304        // lazy_list carries the load-more token + app-owned flags; no refresh by default.
1305        assert!(matches!(
1306            lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1307            Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1308                if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1309        ));
1310        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1311        // with_refresh adds pull-to-refresh to a LazyList without disturbing the load-more fields.
1312        assert!(matches!(
1313            with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1314            Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1315                if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1316        ));
1317        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1318        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1319        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1320        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1321        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1322        // a scrim z-stack keeps its align + scrim flag
1323        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1324    }
1325
1326    #[test]
1327    fn input_builders_carry_ids_values_and_event_tokens() {
1328        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1329        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1330        // video_player defaults + the cosmetic modifiers (match-and-rebind like with_refresh).
1331        assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1332            Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1333        assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1334            Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1335        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1336        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1337        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1338        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1339        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1340        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1341        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1342        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1343
1344        match chip("Latte", true, Ev::Open(2)) {
1345            Widget::Chip { selected, on_press, .. } => {
1346                assert!(selected);
1347                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1348            }
1349            other => panic!("expected Chip, got {other:?}"),
1350        }
1351        match stepper(5, Ev::Tap, Ev::Open(1)) {
1352            Widget::Stepper { value, on_decrement, on_increment } => {
1353                assert_eq!(value, 5);
1354                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1355                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1356            }
1357            other => panic!("expected Stepper, got {other:?}"),
1358        }
1359        let t = tab("Home", true, Ev::Tap);
1360        assert_eq!(t.label, "Home");
1361        assert!(t.selected);
1362        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1363    }
1364
1365    // ---- ABI serialization round-trips (structural stability of the wire types) ----
1366
1367    #[test]
1368    fn widget_tree_round_trips_through_serde() {
1369        let tree = scaffold(
1370            "Home",
1371            true,
1372            vec![tab("A", true, Ev::Tap)],
1373            column(vec![
1374                title("Hi"),
1375                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1376                image("u", ImageShape::Rounded, ImageRatio::Wide),
1377                slider("s", 2, 5),
1378            ]),
1379        );
1380        let s = serde_json::to_string(&tree).unwrap();
1381        let back: Widget = serde_json::from_str(&s).unwrap();
1382        assert_eq!(s, serde_json::to_string(&back).unwrap());
1383    }
1384
1385    #[test]
1386    fn actions_and_input_values_round_trip() {
1387        let actions = vec![
1388            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1389            Action::Input { id: "n".into(), value: InputValue::Int(7) },
1390            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1391            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1392            Action::Restore { data: "blob".into() },
1393            Action::Start,
1394        ];
1395        for a in actions {
1396            let s = serde_json::to_string(&a).unwrap();
1397            let back: Action = serde_json::from_str(&s).unwrap();
1398            assert_eq!(s, serde_json::to_string(&back).unwrap());
1399        }
1400    }
1401
1402    // ---- MobilerShell: the fixed-ABI action dispatch ----
1403
1404    #[derive(Default)]
1405    struct CounterModel {
1406        count: i32,
1407        restored: String,
1408        started: bool,
1409        last_input: String,
1410    }
1411
1412    #[derive(serde::Serialize, serde::Deserialize)]
1413    enum CounterEv {
1414        Inc,
1415        Add(i32),
1416    }
1417
1418    #[derive(Default)]
1419    struct CounterApp;
1420
1421    impl MobilerApp for CounterApp {
1422        type Event = CounterEv;
1423        type Model = CounterModel;
1424        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1425            match ev {
1426                CounterEv::Inc => model.count += 1,
1427                CounterEv::Add(n) => model.count += n,
1428            }
1429        }
1430        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1431            if let InputValue::Text(t) = value {
1432                model.last_input = format!("{id}={t}");
1433            }
1434        }
1435        fn restore(&self, data: &str, model: &mut CounterModel) {
1436            model.restored = data.to_string();
1437        }
1438        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1439            model.started = true;
1440        }
1441        fn view(&self, model: &CounterModel) -> Widget {
1442            text(format!("{}", model.count))
1443        }
1444    }
1445
1446    #[test]
1447    fn shell_dispatches_fired_input_restore_and_start() {
1448        use crux_core::App as _;
1449        let shell = MobilerShell::<CounterApp>::default();
1450        let mut m = CounterModel::default();
1451
1452        // Fired with a valid token → the typed event reaches app.update.
1453        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1454        assert_eq!(m.count, 5);
1455        // Input → app.input.
1456        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1457        assert_eq!(m.last_input, "name=bob");
1458        // Restore → app.restore.
1459        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1460        assert_eq!(m.restored, "saved");
1461        // Start → app.init.
1462        let _ = shell.update(Action::Start, &mut m);
1463        assert!(m.started);
1464        // view renders the (mutated) model through the ABI.
1465        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1466    }
1467
1468    #[test]
1469    fn shell_ignores_a_malformed_fired_token() {
1470        use crux_core::App as _;
1471        let shell = MobilerShell::<CounterApp>::default();
1472        let mut m = CounterModel::default();
1473        // A token that doesn't deserialize to the app's event type is dropped — no
1474        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1475        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1476        assert_eq!(m.count, 0);
1477    }
1478}