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