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