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