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