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