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/// An in-app PDF viewer for the document at `url` (remote https URL or local file URI) — rendered
425/// natively per platform (PDFKit / `PdfRenderer` / `<iframe>`). The app just supplies the URL, e.g.
426/// a backend-generated report. Give it room (place in a sized container or a scroller).
427#[must_use]
428pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
429/// A single unnamed series wrapping `values` — the back-compat shape for `bar_chart`/`line_chart`.
430fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
431    vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
432}
433
434/// A bar chart of `values` (normalized to the max), with optional per-value `labels`.
435/// Single-series, no axis or legend — for richer charts use [`chart`].
436#[must_use]
437pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
438    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
439}
440/// A line chart of `values` (normalized to the max), with optional per-value `labels`.
441/// Single-series, no axis or legend — for richer charts use [`chart`].
442#[must_use]
443pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
444    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
445}
446/// A multi-series chart in the given `style`, with optional x-axis `labels`, y-`axis` gridlines/
447/// ticks (cartesian styles), and a series `legend`. The general builder behind the convenience
448/// constructors below.
449#[must_use]
450pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
451    Widget::Chart { series, labels, style, axis, legend }
452}
453/// Bars stacked to a total per x-slot. Axis + legend on by default.
454#[must_use]
455pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
456    chart(series, labels, ChartStyle::StackedBar, true, true)
457}
458/// Bars where each x-slot fills to 100% — series as proportions. Legend on, no value axis.
459#[must_use]
460pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
461    chart(series, labels, ChartStyle::StackedBar100, false, true)
462}
463/// A pie chart — each series is one wedge sized by its magnitude. Legend on.
464#[must_use]
465pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
466    chart(series, vec![], ChartStyle::Pie, false, true)
467}
468/// A donut chart (pie with a center hole). Legend on.
469#[must_use]
470pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
471    chart(series, vec![], ChartStyle::Donut, false, true)
472}
473/// Concentric progress rings — one per series, swept by `sum(values) / goal`. Legend on.
474/// Give each series a goal via [`ChartSeries::with_goal`].
475#[must_use]
476pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
477    chart(series, vec![], ChartStyle::Rings, false, true)
478}
479/// A single radial gauge — the first series' `value / goal` with the number in the center.
480#[must_use]
481pub fn gauge_chart(series: ChartSeries) -> Widget {
482    chart(vec![series], vec![], ChartStyle::Gauge, false, false)
483}
484
485/// A variable-width stacked-region ("coverage-gap" / Marimekko) chart. `regions` are rectangles in
486/// the `[0, x_max] × [0, y_max]` plane (build with [`ChartRegion::new`]); `ticks` label the
487/// irregular x-axis; `ref_lines` are horizontal target/max lines ([`ChartRefLine::target`]/`::max`);
488/// `legend` names the colors. Add a right-side bracket annotation with [`with_bracket`].
489#[must_use]
490pub fn region_chart(
491    regions: Vec<ChartRegion>,
492    ticks: Vec<ChartTick>,
493    x_max: f32,
494    y_max: f32,
495    ref_lines: Vec<ChartRefLine>,
496    legend: Vec<ChartLegendItem>,
497) -> Widget {
498    Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
499}
500
501/// Attach a right-side bracket annotation to a [`region_chart`] (no-op on any other widget).
502#[must_use]
503pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
504    match widget {
505        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
506            Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
507        }
508        other => other,
509    }
510}
511
512/// Days in `month` (1–12) of `year`, leap-year aware.
513fn days_in_month(year: u32, month: u8) -> u8 {
514    match month {
515        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
516        4 | 6 | 9 | 11 => 30,
517        2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
518        _ => 30,
519    }
520}
521
522/// Weekday of `year-month-day` as 0=Sunday..6=Saturday (Sakamoto's algorithm).
523fn weekday(year: u32, month: u8, day: u8) -> u8 {
524    const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
525    let y = if month < 3 { year - 1 } else { year };
526    let m = month as usize - 1;
527    ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
528}
529
530/// An inline month calendar for `year`/`month` (1–12). `on_day(d)` builds the tap event for each
531/// day `d` in the month; `selected` highlights a day. Leading blanks + weekday header are handled
532/// by the shells from the computed `first_weekday`.
533#[must_use]
534pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
535    let n = days_in_month(year, month);
536    let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
537    Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
538}
539
540/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
541/// tappable. On web the actions render inline (no gesture).
542#[must_use]
543pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
544    Widget::SwipeAction {
545        child: Box::new(child),
546        actions: actions
547            .into_iter()
548            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
549            .collect(),
550    }
551}
552#[must_use]
553pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
554
555#[must_use]
556pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
557#[must_use]
558pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
559#[must_use]
560pub fn card(child: Widget, style: CardStyle) -> Widget {
561    Widget::Card { child: Box::new(child), style, on_press: None }
562}
563/// A tappable card carrying a typed press event.
564#[must_use]
565pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
566    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
567}
568/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
569/// darkened background and the rest render on top.
570#[must_use]
571pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
572    Widget::Box { children, align, scrim }
573}
574#[must_use]
575pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
576/// Horizontally scrolling row of children (a carousel / chip rail).
577#[must_use]
578pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
579/// A circular avatar image.
580#[must_use]
581pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
582/// A circular avatar image with a colored status dot.
583#[must_use]
584pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
585    Widget::Avatar { source: source.into(), status: Some(status) }
586}
587/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
588#[must_use]
589pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
590/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
591#[must_use]
592pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
593    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
594}
595
596#[must_use]
597pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
598    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
599}
600#[must_use]
601pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
602    Widget::IconButton { icon, on_press: tok(on_press) }
603}
604#[must_use]
605pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
606    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
607}
608#[must_use]
609pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
610    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
611}
612/// A text field with full control over [`FieldKind`] and an optional inline
613/// validation `error`. The kind-specific helpers below ([`secure_field`],
614/// [`email_field`], …) wrap this for the common cases.
615#[must_use]
616pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
617    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
618}
619/// A masked password field ([`FieldKind::Secure`]).
620#[must_use]
621pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
622    field(id, placeholder, value, FieldKind::Secure, None)
623}
624/// An email-keyboard field ([`FieldKind::Email`]).
625#[must_use]
626pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
627    field(id, placeholder, value, FieldKind::Email, None)
628}
629/// A whole-number keypad field ([`FieldKind::Number`]).
630#[must_use]
631pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
632    field(id, placeholder, value, FieldKind::Number, None)
633}
634/// A decimal keypad field ([`FieldKind::Decimal`]).
635#[must_use]
636pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
637    field(id, placeholder, value, FieldKind::Decimal, None)
638}
639/// A phone-keypad field ([`FieldKind::Phone`]).
640#[must_use]
641pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
642    field(id, placeholder, value, FieldKind::Phone, None)
643}
644/// A URL-keyboard field ([`FieldKind::Url`]).
645#[must_use]
646pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
647    field(id, placeholder, value, FieldKind::Url, None)
648}
649/// A growable multi-line text area ([`FieldKind::Multiline`]).
650#[must_use]
651pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
652    field(id, placeholder, value, FieldKind::Multiline, None)
653}
654/// Attach an inline validation message to a [`Widget::TextField`], marking it
655/// invalid. No-op on any other widget.
656#[must_use]
657pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
658    match widget {
659        Widget::TextField { id, placeholder, value, kind, .. } =>
660            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
661        other => other,
662    }
663}
664/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
665#[must_use]
666pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
667    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
668}
669/// One option in a [`segmented`] control, carrying a typed selection event.
670#[must_use]
671pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
672    Segment { label: label.into(), selected, on_select: tok(on_select) }
673}
674/// A single-choice segmented control (exclusive options in a pill).
675#[must_use]
676pub fn segmented(segments: Vec<Segment>) -> Widget {
677    Widget::Segmented { segments }
678}
679#[must_use]
680pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
681    Widget::Toggle { id: id.into(), label: label.into(), value }
682}
683#[must_use]
684pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
685    Widget::Checkbox { id: id.into(), label: label.into(), value }
686}
687#[must_use]
688pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
689    Widget::Slider { id: id.into(), value, max }
690}
691#[must_use]
692pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
693    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
694}
695
696/// A bottom-nav tab carrying a typed selection event (label-only).
697#[must_use]
698pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
699    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
700}
701
702/// A bottom-nav tab with a leading icon (icon tab bar).
703#[must_use]
704pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
705    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
706}
707
708/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
709/// theme-as-data (the shell themes the whole app from it).
710#[must_use]
711pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
712    let title = title.into();
713    // route defaults to the title; root depth = 1.
714    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 }
715}
716
717/// Like [`scaffold`], but the top bar (and the system back button) navigate back
718/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
719/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
720#[must_use]
721pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
722    let title = title.into();
723    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 }
724}
725
726/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
727/// serialization) and `depth` (stack depth) so the shell animates transitions,
728/// and shows a back affordance (top-bar arrow + system back button) firing
729/// `on_back` whenever the stack can pop.
730#[must_use]
731pub fn nav_scaffold<R, E>(
732    title: impl Into<String>,
733    dark_mode: bool,
734    tabs: Vec<Tab>,
735    body: Widget,
736    nav: &Nav<R>,
737    on_back: E,
738) -> Widget
739where
740    R: Clone + Serialize,
741    E: Serialize,
742{
743    Widget::Scaffold {
744        title: title.into(),
745        body: Box::new(body),
746        tabs,
747        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
748        dark_mode,
749        theme: None,
750        fab: None,
751        sheet: None,
752        on_refresh: None,
753        refreshing: false,
754        route: nav.route_key(),
755        depth: nav.depth(),
756    }
757}
758
759/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
760/// other widget. Lets an app brand its UI without new scaffold builder overloads:
761/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
762pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
763    match widget {
764        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
765            title,
766            body,
767            tabs,
768            back,
769            dark_mode,
770            theme: Some(theme),
771            fab,
772            sheet,
773            on_refresh,
774            refreshing,
775            route,
776            depth,
777        },
778        other => other,
779    }
780}
781
782/// Anchor a floating action button over a scaffold's body (the raised primary action).
783/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
784pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
785    match widget {
786        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
787            title,
788            body,
789            tabs,
790            back,
791            dark_mode,
792            theme,
793            fab: Some(Fab { icon, on_press: tok(on_press) }),
794            sheet,
795            on_refresh,
796            refreshing,
797            route,
798            depth,
799        },
800        other => other,
801    }
802}
803
804/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
805/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
806pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
807    match widget {
808        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
809            title: t,
810            body,
811            tabs,
812            back,
813            dark_mode,
814            theme,
815            fab,
816            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
817            on_refresh,
818            refreshing,
819            route,
820            depth,
821        },
822        other => other,
823    }
824}
825
826/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
827/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
828/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
829pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
830    match widget {
831        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
832            title,
833            body,
834            tabs,
835            back,
836            dark_mode,
837            theme,
838            fab,
839            sheet,
840            on_refresh: Some(tok(on_refresh)),
841            refreshing,
842            route,
843            depth,
844        },
845        other => other,
846    }
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852    use serde::Serialize;
853
854    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
855    enum Route {
856        Home,
857        Detail(u32),
858    }
859
860    #[derive(Serialize)]
861    enum Ev {
862        Tap,
863        Open(u32),
864    }
865
866    // ---- Nav ----
867
868    #[test]
869    fn nav_push_pop_depth() {
870        let mut nav = Nav::new(Route::Home);
871        assert_eq!(nav.depth(), 1);
872        assert!(!nav.can_go_back());
873
874        nav.push(Route::Detail(7));
875        assert_eq!(nav.depth(), 2);
876        assert!(nav.can_go_back());
877        assert!(matches!(nav.current(), Route::Detail(7)));
878
879        nav.pop();
880        assert_eq!(nav.depth(), 1);
881        assert!(matches!(nav.current(), Route::Home));
882
883        nav.pop(); // no-op at the root
884        assert_eq!(nav.depth(), 1);
885    }
886
887    #[test]
888    fn nav_reset_replaces_stack() {
889        let mut nav = Nav::new(Route::Home);
890        nav.push(Route::Detail(1));
891        nav.push(Route::Detail(2));
892        nav.reset(Route::Detail(9));
893        assert_eq!(nav.depth(), 1);
894        assert!(matches!(nav.current(), Route::Detail(9)));
895    }
896
897    #[test]
898    fn nav_route_key_is_serialization() {
899        let nav = Nav::new(Route::Detail(3));
900        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
901    }
902
903    // ---- builders ----
904
905    #[test]
906    fn scaffold_sets_route_depth_and_no_back() {
907        match scaffold("Home", false, vec![], text("x")) {
908            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
909                assert_eq!(route, "Home");
910                assert_eq!(depth, 1);
911                assert!(back.is_none());
912                assert!(!dark_mode);
913            }
914            other => panic!("expected Scaffold, got {other:?}"),
915        }
916    }
917
918    #[test]
919    fn scaffold_back_is_depth_2_with_back() {
920        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
921            Widget::Scaffold { depth, back, dark_mode, .. } => {
922                assert_eq!(depth, 2);
923                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
924                assert!(dark_mode);
925            }
926            other => panic!("expected Scaffold, got {other:?}"),
927        }
928    }
929
930    #[test]
931    fn nav_scaffold_shows_back_only_when_poppable() {
932        let mut nav = Nav::new(Route::Home);
933        // at the root: no back, depth 1, route = serialized current route
934        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
935            Widget::Scaffold { back, depth, route, .. } => {
936                assert!(back.is_none());
937                assert_eq!(depth, 1);
938                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
939            }
940            other => panic!("expected Scaffold, got {other:?}"),
941        }
942        // after a push: back present, depth 2
943        nav.push(Route::Detail(2));
944        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
945            Widget::Scaffold { back, depth, .. } => {
946                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
947                assert_eq!(depth, 2);
948            }
949            other => panic!("expected Scaffold, got {other:?}"),
950        }
951    }
952
953    #[test]
954    fn buttons_carry_serialized_event_tokens() {
955        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
956            Widget::Button { label, on_press, .. } => {
957                assert_eq!(label, "Go");
958                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
959            }
960            other => panic!("expected Button, got {other:?}"),
961        }
962        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
963            Widget::Card { on_press, .. } => {
964                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
965            }
966            other => panic!("expected Card, got {other:?}"),
967        }
968        // a plain card is not tappable
969        match card(text("c"), CardStyle::Elevated) {
970            Widget::Card { on_press, .. } => assert!(on_press.is_none()),
971            other => panic!("expected Card, got {other:?}"),
972        }
973    }
974
975    // ---- Cx capabilities ----
976
977    #[test]
978    fn cx_notify_and_save_enqueue_notifications() {
979        let mut cx = Cx::<Ev>::default();
980        cx.notify("toast", "show", "hi");
981        cx.save("blob");
982        assert_eq!(cx.notifications.len(), 2);
983        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
984        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
985        assert!(cx.requests.is_empty());
986    }
987
988    #[test]
989    fn cx_http_helpers_build_requests() {
990        let mut cx = Cx::<Ev>::default();
991        cx.get("http://h/x", |_| Ev::Tap);
992        cx.post("http://h/y", "hello", |_| Ev::Tap);
993        cx.patch("http://h/z", "patch", |_| Ev::Tap);
994        cx.delete("http://h/d", |_| Ev::Tap);
995
996        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
997        assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
998        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
999
1000        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1001        assert_eq!(get_input["url"], "http://h/x");
1002        assert!(get_input["body"].is_null());
1003
1004        let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1005        assert_eq!(post_input["url"], "http://h/y");
1006        assert_eq!(post_input["body"], "hello");
1007    }
1008
1009    #[test]
1010    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1011        let mut cx = Cx::<Ev>::default();
1012        cx.pick_photo(|_| Ev::Tap);
1013        cx.capture_photo(|_| Ev::Tap);
1014        assert_eq!(cx.requests.len(), 2);
1015        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1016        // carry empty input (the shell needs no parameters to launch picker/camera).
1017        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", ""));
1018        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", ""));
1019    }
1020
1021    #[test]
1022    fn cx_capture_photo_routes_success_and_cancel() {
1023        // Happy path: ok=true delivers the URI to the success branch.
1024        let mut cx = Cx::<Ev>::default();
1025        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1026        let (_, then) = cx.requests.pop().unwrap();
1027        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1028
1029        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1030        let mut cx = Cx::<Ev>::default();
1031        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1032        let (_, then) = cx.requests.pop().unwrap();
1033        assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1034    }
1035
1036    #[test]
1037    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1038        let mut cx = Cx::<Ev>::default();
1039        cx.copy("c");
1040        cx.share("s");
1041        cx.open_url("u");
1042        cx.toast("t");
1043        cx.haptic("heavy");
1044        let got: Vec<(&str, &str, &str)> = cx
1045            .notifications
1046            .iter()
1047            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1048            .collect();
1049        assert_eq!(
1050            got,
1051            vec![
1052                ("clipboard", "copy", "c"),
1053                ("share", "text", "s"),
1054                ("browser", "open", "u"),
1055                ("toast", "show", "t"),
1056                ("haptics", "heavy", ""), // haptic style is the op, input empty
1057            ]
1058        );
1059        assert!(cx.requests.is_empty());
1060    }
1061
1062    #[test]
1063    fn cx_device_model_is_a_request_not_a_notification() {
1064        let mut cx = Cx::<Ev>::default();
1065        cx.device_model(|_| Ev::Tap);
1066        assert!(cx.notifications.is_empty());
1067        assert_eq!(cx.requests.len(), 1);
1068        let (call, _) = &cx.requests[0];
1069        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1070    }
1071
1072    #[test]
1073    fn cx_device_locale_requests_the_device_locale_op() {
1074        let mut cx = Cx::<Ev>::default();
1075        cx.device_locale(|_| Ev::Tap);
1076        assert!(cx.notifications.is_empty());
1077        assert_eq!(cx.requests.len(), 1);
1078        let (call, _) = &cx.requests[0];
1079        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1080    }
1081
1082    #[test]
1083    fn cx_confirm_serializes_title_message_and_routes_ok() {
1084        let mut cx = Cx::<Ev>::default();
1085        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1086        let (call, then) = cx.requests.pop().unwrap();
1087        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1088        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1089        assert_eq!(v["title"], "Delete?");
1090        assert_eq!(v["message"], "This cannot be undone.");
1091        // ok=true → confirmed branch; ok=false would take the else branch.
1092        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1093    }
1094
1095    // ---- widget builders ----
1096
1097    #[test]
1098    fn text_builders_carry_their_style() {
1099        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1100        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1101        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1102        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1103        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1104    }
1105
1106    #[test]
1107    fn layout_and_content_builders_produce_their_variants() {
1108        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1109        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1110        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1111        assert!(matches!(divider(), Widget::Divider));
1112        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1113        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1114        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1115        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)));
1116        let rc = with_bracket(
1117            region_chart(
1118                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1119                vec![ChartTick::new(3.0, "3 Mt.")],
1120                65.0, 80.0,
1121                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1122                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1123            ),
1124            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1125        );
1126        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1127        // June 2026 has 30 days and starts on a Monday (weekday 1).
1128        assert!(matches!(
1129            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1130            Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1131        ));
1132        assert!(matches!(
1133            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1134            Widget::SwipeAction { actions, .. } if actions.len() == 1
1135        ));
1136        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1137        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1138        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1139        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1140        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1141        // a scrim z-stack keeps its align + scrim flag
1142        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1143    }
1144
1145    #[test]
1146    fn input_builders_carry_ids_values_and_event_tokens() {
1147        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1148        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1149        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1150        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1151        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1152        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1153        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1154        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1155        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1156        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1157
1158        match chip("Latte", true, Ev::Open(2)) {
1159            Widget::Chip { selected, on_press, .. } => {
1160                assert!(selected);
1161                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1162            }
1163            other => panic!("expected Chip, got {other:?}"),
1164        }
1165        match stepper(5, Ev::Tap, Ev::Open(1)) {
1166            Widget::Stepper { value, on_decrement, on_increment } => {
1167                assert_eq!(value, 5);
1168                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1169                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1170            }
1171            other => panic!("expected Stepper, got {other:?}"),
1172        }
1173        let t = tab("Home", true, Ev::Tap);
1174        assert_eq!(t.label, "Home");
1175        assert!(t.selected);
1176        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1177    }
1178
1179    // ---- ABI serialization round-trips (structural stability of the wire types) ----
1180
1181    #[test]
1182    fn widget_tree_round_trips_through_serde() {
1183        let tree = scaffold(
1184            "Home",
1185            true,
1186            vec![tab("A", true, Ev::Tap)],
1187            column(vec![
1188                title("Hi"),
1189                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1190                image("u", ImageShape::Rounded, ImageRatio::Wide),
1191                slider("s", 2, 5),
1192            ]),
1193        );
1194        let s = serde_json::to_string(&tree).unwrap();
1195        let back: Widget = serde_json::from_str(&s).unwrap();
1196        assert_eq!(s, serde_json::to_string(&back).unwrap());
1197    }
1198
1199    #[test]
1200    fn actions_and_input_values_round_trip() {
1201        let actions = vec![
1202            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1203            Action::Input { id: "n".into(), value: InputValue::Int(7) },
1204            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1205            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1206            Action::Restore { data: "blob".into() },
1207            Action::Start,
1208        ];
1209        for a in actions {
1210            let s = serde_json::to_string(&a).unwrap();
1211            let back: Action = serde_json::from_str(&s).unwrap();
1212            assert_eq!(s, serde_json::to_string(&back).unwrap());
1213        }
1214    }
1215
1216    // ---- MobilerShell: the fixed-ABI action dispatch ----
1217
1218    #[derive(Default)]
1219    struct CounterModel {
1220        count: i32,
1221        restored: String,
1222        started: bool,
1223        last_input: String,
1224    }
1225
1226    #[derive(serde::Serialize, serde::Deserialize)]
1227    enum CounterEv {
1228        Inc,
1229        Add(i32),
1230    }
1231
1232    #[derive(Default)]
1233    struct CounterApp;
1234
1235    impl MobilerApp for CounterApp {
1236        type Event = CounterEv;
1237        type Model = CounterModel;
1238        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1239            match ev {
1240                CounterEv::Inc => model.count += 1,
1241                CounterEv::Add(n) => model.count += n,
1242            }
1243        }
1244        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1245            if let InputValue::Text(t) = value {
1246                model.last_input = format!("{id}={t}");
1247            }
1248        }
1249        fn restore(&self, data: &str, model: &mut CounterModel) {
1250            model.restored = data.to_string();
1251        }
1252        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1253            model.started = true;
1254        }
1255        fn view(&self, model: &CounterModel) -> Widget {
1256            text(format!("{}", model.count))
1257        }
1258    }
1259
1260    #[test]
1261    fn shell_dispatches_fired_input_restore_and_start() {
1262        use crux_core::App as _;
1263        let shell = MobilerShell::<CounterApp>::default();
1264        let mut m = CounterModel::default();
1265
1266        // Fired with a valid token → the typed event reaches app.update.
1267        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1268        assert_eq!(m.count, 5);
1269        // Input → app.input.
1270        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1271        assert_eq!(m.last_input, "name=bob");
1272        // Restore → app.restore.
1273        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1274        assert_eq!(m.restored, "saved");
1275        // Start → app.init.
1276        let _ = shell.update(Action::Start, &mut m);
1277        assert!(m.started);
1278        // view renders the (mutated) model through the ABI.
1279        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1280    }
1281
1282    #[test]
1283    fn shell_ignores_a_malformed_fired_token() {
1284        use crux_core::App as _;
1285        let shell = MobilerShell::<CounterApp>::default();
1286        let mut m = CounterModel::default();
1287        // A token that doesn't deserialize to the app's event type is dropped — no
1288        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1289        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1290        assert_eq!(m.count, 0);
1291    }
1292}