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 app_info;
11pub mod bunny;
12pub mod dialog;
13pub mod format;
14pub mod http;
15pub mod i18n;
16pub mod transfer;
17pub use app_info::AppInfo;
18pub use dialog::{Confirm, Picker, Snackbar, SnackbarDuration};
19pub use format::{Currency, Locale, Weekday};
20pub use http::{HttpHeader, HttpOutcome};
21pub use i18n::{Catalog, negotiate};
22pub use transfer::TransferEvent;
23
24use crux_core::{
25    App, Command,
26    capability::Operation,
27    macros::effect,
28    render::{RenderOperation, render},
29};
30use facet::Facet;
31use serde::{Deserialize, Serialize, de::DeserializeOwned};
32
33pub use mobiler_ui::{
34    A11yRole, Action, Appearance, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
35    ChartSeries, ChartStyle, ChartTick, ColorRoles, Corner, FamilyRole, Density, Fab, FieldKind, FontFamily, Icon,
36    ImageRatio, ImageShape, InputValue, MapMarker, Palette, ProjectColor, Radius, Rgb, Rgba, Segment, Shapes, Sheet, ShellLabels, Spacing, SwipeButton, Tab,
37    TextStyle, Theme, Tone, TonePair, TypeScale, TypeSpec, Widget,
38};
39
40// ============================ capabilities ============================
41
42/// Built-in capabilities the generic shell fulfils.
43#[effect(facet_typegen)]
44#[derive(Debug)]
45pub enum Effect {
46    Render(RenderOperation),
47    /// Fire-and-forget plugin call (shell does not resolve).
48    PluginNotify(PluginNotify),
49    /// Request/response plugin call (shell resolves with a [`PluginResponse`]).
50    Plugin(PluginCall),
51    /// Long-lived subscription: the shell starts a native source and resolves
52    /// **repeatedly** (a [`PluginResponse`] per event) until it's torn down. Powers
53    /// [`Cx::subscribe`]. Stop it with [`Cx::unsubscribe`] (a `stream`/`unsubscribe`
54    /// notify keyed by [`PluginStreamCall::key`]).
55    PluginStream(PluginStreamCall),
56}
57
58#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
59pub struct PluginNotify {
60    pub plugin: String,
61    pub op: String,
62    pub input: String,
63}
64impl Operation for PluginNotify {
65    type Output = ();
66}
67
68#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
69pub struct PluginCall {
70    pub plugin: String,
71    pub op: String,
72    pub input: String,
73}
74impl Operation for PluginCall {
75    type Output = PluginResponse;
76}
77
78/// A streaming plugin subscription (powers [`Effect::PluginStream`]). Like
79/// [`PluginCall`] but carries a caller-chosen `key` so the subscription can be torn
80/// down ([`Cx::unsubscribe`]) — the shell registers the native source under `key`.
81#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginStreamCall {
83    pub key: String,
84    pub plugin: String,
85    pub op: String,
86    pub input: String,
87}
88impl Operation for PluginStreamCall {
89    type Output = PluginResponse;
90}
91
92/// A plugin's reply. `output` is raw bytes: the HTTP capability puts a bincode
93/// [`HttpOutcome`](crate::HttpOutcome) here, while most plugins put UTF-8 text (use
94/// [`PluginResponse::text`] to build one and [`as_text`](Self::as_text) to read it).
95///
96/// Note the asymmetry with [`PluginCall`], whose `input` stays a `String`: changing
97/// `output` affects only where a response is *constructed*, whereas changing `input`
98/// would affect where it is *parsed* — in every plugin on every shell. Large uploads
99/// pass file paths (text), so `input` stays adequate.
100#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
101pub struct PluginResponse {
102    pub ok: bool,
103    pub output: Vec<u8>,
104}
105
106impl PluginResponse {
107    /// Build a response whose payload is UTF-8 text — what most plugins return.
108    pub fn text(ok: bool, s: impl Into<String>) -> Self {
109        Self { ok, output: s.into().into_bytes() }
110    }
111
112    /// The payload as text, or `None` if it is not valid UTF-8.
113    pub fn as_text(&self) -> Option<&str> {
114        std::str::from_utf8(&self.output).ok()
115    }
116}
117
118type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
119/// A streaming continuation — fires once **per event** (so `Fn`, not `FnOnce`).
120type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
121
122/// Effects an app requests during `update`, generic over the app event type so
123/// continuations stay fully typed.
124pub struct Cx<E> {
125    notifications: Vec<PluginNotify>,
126    requests: Vec<(PluginCall, Continuation<E>)>,
127    streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
128    app_info: AppInfo,
129}
130
131impl<E> Default for Cx<E> {
132    fn default() -> Self {
133        Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new(), app_info: AppInfo::default() }
134    }
135}
136
137impl<E> Cx<E> {
138    /// A `Cx` carrying `info` — for app unit tests that exercise code reading [`app_info`](Self::app_info).
139    #[must_use]
140    pub fn with_app_info(info: AppInfo) -> Self {
141        Self { app_info: info, ..Self::default() }
142    }
143
144    /// The app's own version/build/platform/bundle id, as the shell reported it at startup
145    /// (before `restore`/`init`), so `init` can put the build number on the first request.
146    /// All fields are empty when the shell predates it. `view` has no `Cx`: copy what a screen
147    /// shows into the Model in `init`.
148    #[must_use]
149    pub fn app_info(&self) -> &AppInfo {
150        &self.app_info
151    }
152
153    /// Fire-and-forget call to a native plugin.
154    pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
155        self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
156    }
157
158    /// Request/response call: when the plugin replies, `then(response)` produces
159    /// the typed event delivered back to your `update`.
160    pub fn plugin(
161        &mut self,
162        plugin: impl Into<String>,
163        op: impl Into<String>,
164        input: impl Into<String>,
165        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
166    ) {
167        self.requests
168            .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
169    }
170
171    /// Subscribe to a streaming plugin: the shell starts a native source and delivers
172    /// **every** event it produces to `on_event` (which fires repeatedly, once per
173    /// event), each producing a typed event into your `update`. `key` is a
174    /// caller-chosen id for this subscription — pass the same `key` to
175    /// [`unsubscribe`](Self::unsubscribe) to stop it. Call `subscribe` **once** per
176    /// key (e.g. in [`init`](MobilerApp::init) or on a connect event); calling it
177    /// again with a live key starts a second source.
178    pub fn subscribe(
179        &mut self,
180        key: impl Into<String>,
181        plugin: impl Into<String>,
182        op: impl Into<String>,
183        input: impl Into<String>,
184        on_event: impl Fn(PluginResponse) -> E + Send + 'static,
185    ) {
186        self.streams.push((
187            PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
188            Box::new(on_event),
189        ));
190    }
191
192    /// Stop the streaming subscription started under `key` by [`subscribe`](Self::subscribe).
193    /// The shell tears down the native source registered under `key`, so it stops
194    /// producing events. No-op if `key` isn't subscribed.
195    pub fn unsubscribe(&mut self, key: impl Into<String>) {
196        self.notify("stream", "unsubscribe", key);
197    }
198
199    /// Upload the file at `source` (a path / `content://` / `file://` / `blob:` handle)
200    /// as the raw request body. Finish with [`TransferBuilder::start`].
201    pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
202        crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
203    }
204
205    /// Download `url` to `dest` (a sandbox path on iOS/Android; a filename hint on web,
206    /// which returns a `blob:` handle). Finish with [`TransferBuilder::start`].
207    pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
208        crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
209    }
210
211    /// Persist `data` (handed back to [`MobilerApp::restore`] on next startup).
212    pub fn save(&mut self, data: impl Into<String>) {
213        self.notify("storage", "save", data);
214    }
215
216    /// Copy `text` to the system clipboard (built-in `clipboard` capability).
217    pub fn copy(&mut self, text: impl Into<String>) {
218        self.notify("clipboard", "copy", text);
219    }
220
221    /// Open the system share sheet with `text` (built-in `share` capability).
222    pub fn share(&mut self, text: impl Into<String>) {
223        self.notify("share", "text", text);
224    }
225
226    /// Open `url` in the platform browser / default handler (built-in `browser`
227    /// capability). Fire-and-forget: the app leaves the foreground.
228    pub fn open_url(&mut self, url: impl Into<String>) {
229        self.notify("browser", "open", url);
230    }
231
232    /// Like [`open_url`](Self::open_url), but `then` learns whether it opened: `ok: true` when the
233    /// system handed the link to an app; `ok: false` with a reason (`"no app can open this link"`,
234    /// `"invalid url"`, `"blocked"` — a web pop-up blocker —, `"cancelled"` — the user declined the
235    /// system's confirmation) otherwise — e.g. `tel:` on a device without a dialer:
236    /// `cx.open_url_then("tel:+381601234567", |r| Msg::Dialed(r.ok))`. A browser can't tell whether
237    /// the desktop can place a call, so on web `ok` only means the link was handed off.
238    pub fn open_url_then(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
239        self.plugin("browser", "open", url, then);
240    }
241
242    /// Show a transient toast / snackbar with `text` (built-in `toast` capability).
243    pub fn toast(&mut self, text: impl Into<String>) {
244        self.notify("toast", "show", text);
245    }
246
247    /// Fire a haptic tap (built-in `haptics` capability). `style` is `"light"`,
248    /// `"medium"`, or `"heavy"`; unknown styles fall back to medium.
249    pub fn haptic(&mut self, style: impl Into<String>) {
250        self.notify("haptics", style, "");
251    }
252
253    /// Start an HTTP request with full control — headers, and later timeouts and
254    /// query params — finished with [`RequestBuilder::send`].
255    ///
256    /// ```ignore
257    /// cx.request("PUT", url)
258    ///     .bearer(&token)
259    ///     .body(json)
260    ///     .send(|outcome| match outcome.status() {
261    ///         Some(409) => Event::NeedsRebase,
262    ///         Some(s) if outcome.is_success() => Event::Saved,
263    ///         Some(s) => Event::ServerError(s),
264    ///         None => Event::Offline,
265    ///     });
266    /// ```
267    pub fn request(
268        &mut self,
269        method: impl Into<String>,
270        url: impl Into<String>,
271    ) -> crate::http::RequestBuilder<'_, E> {
272        crate::http::RequestBuilder::new(self, method.into(), url.into())
273    }
274
275    /// `GET url`, delivering the outcome to `then`.
276    pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
277        self.request("GET", url).send(then);
278    }
279    /// `POST url` with `body`, delivering the outcome to `then`.
280    pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
281        self.request("POST", url).body(body).send(then);
282    }
283    /// `PUT url` with `body`, delivering the outcome to `then`.
284    pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
285        self.request("PUT", url).body(body).send(then);
286    }
287    /// `PATCH url` with `body`, delivering the outcome to `then`.
288    pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
289        self.request("PATCH", url).body(body).send(then);
290    }
291    /// `DELETE url`, delivering the outcome to `then`.
292    pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
293        self.request("DELETE", url).send(then);
294    }
295
296    /// Query the device model/name via the built-in `device` capability; the result
297    /// (`response.output`, e.g. "Google Pixel 7" / "Apple iPhone (iOS 18.0)") is
298    /// delivered to `then`.
299    pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
300        self.plugin("device", "model", "", then);
301    }
302
303    /// Query the device's preferred locale as a BCP-47 language tag (e.g. `"de-CH"`, `"en-US"`)
304    /// via the built-in `device` capability; `then` receives it in `response.output`. Pair with
305    /// [`Locale::from_tag`](crate::format::Locale::from_tag) to choose the app's language /
306    /// formatting locale at startup. Works on iOS, Android, and web.
307    pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
308        self.plugin("device", "locale", "", then);
309    }
310
311    /// The OS light/dark setting (`"light"` / `"dark"` in `response.output`) via the built-in
312    /// `device` capability — the system's value even while the app forces one with `with_appearance`.
313    pub fn system_appearance(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
314        self.plugin("device", "appearance", "", then);
315    }
316
317    /// Subscribe to the OS light/dark setting: `on_event` gets `"light"` / `"dark"` once right away,
318    /// then on every change. Stop it with [`unsubscribe`](Self::unsubscribe)`(key)`.
319    pub fn subscribe_appearance(&mut self, key: impl Into<String>, on_event: impl Fn(PluginResponse) -> E + Send + 'static) {
320        self.subscribe(key, "appearance", "changes", "", on_event);
321    }
322
323    /// Let the user pick an image (built-in `photo` capability — the system photo
324    /// picker, no permission required). `then` receives the result: on success
325    /// `response.ok` is `true` and `response.output` is a local image URI you can
326    /// hand straight to the `image(...)` widget; on cancel, `ok` is `false`.
327    pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
328        self.plugin("photo", "pick", "", then);
329    }
330
331    /// Capture a photo with the device camera (built-in `camera` capability — launches
332    /// the system camera). `then` receives the result: on success `response.ok` is
333    /// `true` and `response.output` is a local image URI you can hand straight to the
334    /// `image(...)` widget; on cancel, `ok` is `false`. iOS requires an
335    /// `NSCameraUsageDescription` (the template ships one, opt-in); Android captures via
336    /// the system camera app, so no extra runtime permission is needed.
337    pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
338        self.plugin("camera", "capture", "", then);
339    }
340
341    /// Ask the user to confirm via a native dialog (built-in `dialog` capability).
342    /// `then` receives the choice: `response.ok` is `true` if confirmed, `false` if
343    /// cancelled/dismissed. Resolves asynchronously (the user replies whenever).
344    pub fn confirm(
345        &mut self,
346        title: impl Into<String>,
347        message: impl Into<String>,
348        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
349    ) {
350        self.confirm_with(Confirm::new(title, message), then);
351    }
352
353    /// As [`confirm`](Self::confirm), with the app's own button labels and an optional destructive
354    /// style — e.g. `Confirm::new("Cancel booking?", msg).confirm_label("Cancel booking")
355    /// .cancel_label("Keep it").destructive()`. Same response: `ok` is `true` only if confirmed.
356    pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
357        self.plugin("dialog", "confirm", dialog.to_input(), then);
358    }
359
360    /// Show a snackbar (built-in `snackbar` capability) above the bottom navigation and the FAB,
361    /// e.g. `cx.snackbar(Snackbar::new("Booking cancelled").action("Undo"), |r| Msg::Undo(r.ok))`.
362    /// `then` gets `ok: true` (output `"action"`) when its action is tapped; otherwise `ok: false`
363    /// with output `"timeout"`, `"dismissed"` (swiped away) or `"replaced"` (a newer snackbar). With
364    /// no scaffold on screen there's nothing to show it on, and it resolves `"timeout"` at once.
365    pub fn snackbar(&mut self, snackbar: Snackbar, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
366        self.plugin("snackbar", "show", snackbar.to_input(), then);
367    }
368
369    /// Let the user pick a date via the native date picker (built-in `datetime`
370    /// capability). On success `response.ok` is `true` and `response.output` is the
371    /// chosen date as an ISO `YYYY-MM-DD` string; on cancel/dismiss, `ok` is `false`.
372    /// Resolves asynchronously (the user replies whenever).
373    pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
374        self.plugin("datetime", "date", "", then);
375    }
376
377    /// Let the user pick a time via the native time picker (built-in `datetime`
378    /// capability). On success `response.ok` is `true` and `response.output` is the
379    /// chosen time as a 24-hour `HH:MM` string; on cancel/dismiss, `ok` is `false`.
380    /// Resolves asynchronously (the user replies whenever).
381    pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
382        self.plugin("datetime", "time", "", then);
383    }
384
385    /// As [`pick_date`](Self::pick_date), with the app's own title and button labels.
386    pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
387        self.plugin("datetime", "date", picker.to_input(), then);
388    }
389
390    /// As [`pick_time`](Self::pick_time), with the app's own title and button labels.
391    pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
392        self.plugin("datetime", "time", picker.to_input(), then);
393    }
394
395    /// Read the current local date-time (built-in `datetime` capability). The core is a
396    /// pure state machine and can't read the clock itself, so stamping an event with "now"
397    /// — a ledger entry, a log line — goes through the shell. `response.output` is the local
398    /// date-time as `YYYY-MM-DD HH:MM:SS` (sortable lexicographically; the date is the first
399    /// 10 chars). No UI — resolves immediately. Pair with [`pick_date`](Self::pick_date) when
400    /// the user should choose a different date instead.
401    pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
402        self.plugin("datetime", "now", "", then);
403    }
404}
405
406// ============================ the app trait ============================
407
408/// What a Mobiler app implements. Write typed domain events; Mobiler serializes
409/// them into opaque tokens behind the scenes.
410pub trait MobilerApp: Default {
411    type Event: Serialize + DeserializeOwned + Send + 'static;
412    type Model: Default;
413
414    fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
415
416    fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
417        let _ = (id, value, model, cx);
418    }
419
420    /// Restore persisted state on startup. `data` is whatever you last passed to
421    /// `cx.save` (or empty if nothing was saved). Default: ignore.
422    fn restore(&self, data: &str, model: &mut Self::Model) {
423        let _ = (data, model);
424    }
425
426    /// Run once on startup, after [`restore`](Self::restore). The place to kick
427    /// off initial effects — e.g. fetch data with `cx.get`. Default: nothing.
428    fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
429        let _ = (model, cx);
430    }
431
432    fn view(&self, model: &Self::Model) -> Widget;
433}
434
435/// Crux adapter: turns a [`MobilerApp`] into an app speaking the fixed ABI.
436pub struct MobilerShell<A>(PhantomData<fn() -> A>);
437
438impl<A> Default for MobilerShell<A> {
439    fn default() -> Self {
440        Self(PhantomData)
441    }
442}
443
444impl<A: MobilerApp> App for MobilerShell<A> {
445    type Event = Action;
446    type Model = A::Model;
447    type ViewModel = Widget;
448    type Effect = Effect;
449
450    fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
451        let app = A::default();
452        let mut cx = Cx::<A::Event>::with_app_info(app_info::get());
453        match action {
454            Action::Fired { token } => {
455                if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
456                    app.update(event, model, &mut cx);
457                }
458            }
459            Action::Input { id, value } => app.input(&id, value, model, &mut cx),
460            Action::Restore { data } => app.restore(&data, model),
461            Action::Start => app.init(model, &mut cx),
462            Action::AppInfo { version, build, platform, bundle_id } => {
463                app_info::set(AppInfo { version, build, platform, bundle_id });
464            }
465        }
466        // Render first: the model is final once the app's handler returns, so the first frame
467        // must show it. A shell that awaits a request before looking at later effects (the
468        // Android shell once did) would otherwise show the change a full round trip late —
469        // a controlled text field then reverts keystrokes. Replies re-render via their own
470        // `Fired` update.
471        let mut commands: Vec<Command<Effect, Action>> = vec![render()];
472        for op in cx.notifications {
473            commands.push(Command::notify_shell(op).build());
474        }
475        for (op, then) in cx.requests {
476            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
477                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
478            }));
479        }
480        for (op, then) in cx.streams {
481            // A long-lived shell stream: `then_send` fires `then` once per emitted
482            // event (it's `Fn`), each re-entering `update` as a `Fired` action.
483            commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
484                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
485            }));
486        }
487        Command::all(commands)
488    }
489
490    fn view(&self, model: &Self::Model) -> Widget {
491        A::default().view(model)
492    }
493}
494
495// ============================ navigation ============================
496
497/// A navigation stack the app holds in its `Model`. The **core owns the stack**
498/// (single source of truth); the framework reads its `route`/`depth` to drive
499/// the shell's push/pop transitions and back button.
500///
501/// `R` is your screen-route type (typically a small enum). Hold it in the model,
502/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
503/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
504/// `pop` so the back affordance works.
505///
506/// ```ignore
507/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
508/// // model.nav: Nav<Route> = Nav::new(Route::List);
509/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
510/// //         Msg::Back      => model.nav.pop(),
511/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
512/// ```
513#[derive(Clone, Debug)]
514pub struct Nav<R> {
515    stack: Vec<R>,
516}
517
518impl<R: Clone + Serialize> Nav<R> {
519    /// A stack containing a single root route.
520    #[must_use]
521    pub fn new(root: R) -> Self {
522        Self { stack: vec![root] }
523    }
524    /// Push a new screen onto the stack.
525    pub fn push(&mut self, route: R) {
526        self.stack.push(route);
527    }
528    /// Pop the top screen (no-op at the root).
529    pub fn pop(&mut self) {
530        if self.stack.len() > 1 {
531            self.stack.pop();
532        }
533    }
534    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
535    pub fn reset(&mut self, root: R) {
536        self.stack = vec![root];
537    }
538    /// The current (top) route — what `view` should render.
539    #[must_use]
540    pub fn current(&self) -> &R {
541        self.stack.last().expect("nav stack is never empty")
542    }
543    /// Stack depth (root = 1).
544    #[must_use]
545    pub fn depth(&self) -> u32 {
546        self.stack.len() as u32
547    }
548    /// Whether there is a screen to pop back to.
549    #[must_use]
550    pub fn can_go_back(&self) -> bool {
551        self.stack.len() > 1
552    }
553    /// Stable identity of the current route (its serialization), used by the shell
554    /// to decide when to animate a transition.
555    fn route_key(&self) -> String {
556        serde_json::to_string(self.current()).expect("serialize route")
557    }
558}
559
560// ============================ widget builders ============================
561// Action-carrying builders take a TYPED event and serialize it into a token.
562
563fn tok<E: Serialize>(event: E) -> String {
564    serde_json::to_string(&event).expect("serialize event")
565}
566
567#[must_use]
568pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
569    Widget::Text { content: content.into(), style }
570}
571#[must_use]
572pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
573#[must_use]
574pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
575#[must_use]
576pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
577#[must_use]
578pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
579#[must_use]
580pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
581/// The largest text — e.g. an appointment time. Defaults to 36 bold (the display font under
582/// `FontFamily::Custom`); `Theme.type_scale.display` overrides it.
583#[must_use]
584pub fn display(content: impl Into<String>) -> Widget { styled(content, TextStyle::Display) }
585/// A section/sheet heading. Defaults to 24 semibold; `Theme.type_scale.headline` overrides it.
586#[must_use]
587pub fn headline(content: impl Into<String>) -> Widget { styled(content, TextStyle::Headline) }
588
589#[must_use]
590pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
591    Widget::Image { source: source.into(), shape, ratio }
592}
593#[must_use]
594pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
595    Widget::Badge { label: label.into(), tone, icon: None }
596}
597/// A small colored identity dot.
598#[must_use]
599pub fn color_dot(color: ProjectColor) -> Widget {
600    Widget::ColorDot { color }
601}
602#[must_use]
603pub fn divider() -> Widget { Widget::Divider }
604/// A progress bar (`Some(0.0..=1.0)`) or an indeterminate spinner (`None`).
605#[must_use]
606pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
607/// A shimmer placeholder shown while content loads.
608#[must_use]
609pub fn skeleton() -> Widget { Widget::Skeleton }
610/// An in-app PDF viewer for the document at `url` (remote https URL or local file URI) — rendered
611/// natively per platform (PDFKit / `PdfRenderer` / `<iframe>`). The app just supplies the URL, e.g.
612/// a backend-generated report. Give it room (place in a sized container or a scroller).
613#[must_use]
614pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
615/// A controllable native video player for `url` (remote MP4/HLS or a local file URI), rendered with the
616/// native player per platform (AVPlayer / Media3 ExoPlayer / `<video>`). `id` routes the ~once-per-second
617/// position into `input(id, InputValue::Int(position_ms))`; build it fresh each render with the current
618/// `playing` (play/pause) + `seek_to_ms` (the shell jumps when this CHANGES; `-1` = no seek). `on_ended`
619/// fires when the clip finishes. Defaults: controls shown, not looping/muted, no poster, no resume
620/// offset, no captions, rate 1.0, full volume, single clip (no playlist), PiP off — tune with
621/// [`with_loop`]/[`with_muted`]/[`without_controls`]/[`with_poster`]/[`with_start_at`]/[`with_captions`]/
622/// [`with_rate`]/[`with_volume`]/[`with_pip`] (or [`video_playlist`] for a queue). Give it room.
623#[must_use]
624pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
625    Widget::Video {
626        url: url.into(),
627        id: id.into(),
628        playing,
629        seek_to_ms,
630        controls: true,
631        looping: false,
632        muted: false,
633        on_ended: Some(tok(on_ended)),
634        poster: None,
635        start_at_ms: -1,
636        captions: Vec::new(),
637        rate: 1.0,
638        volume: 1.0,
639        urls: Vec::new(),
640        start_index: 0,
641        seek_index: -1,
642        allow_pip: false,
643    }
644}
645/// A controllable native video player over a **playlist** of `urls` (auto-advances gaplessly; the
646/// shell reports the current track via `input("{id}.index", InputValue::Int(i))`). `start_index` is
647/// the first clip; build it fresh each render with the current `playing`. Force-jump to a track by
648/// pairing this with [`with_seek_index`]. `on_ended` fires when the LAST clip finishes. Same cosmetic
649/// modifiers as [`video_player`]. Empty `urls` renders nothing useful — use [`video_player`] for one clip.
650#[must_use]
651pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
652    Widget::Video {
653        url: urls.first().cloned().unwrap_or_default(),
654        id: id.into(),
655        playing,
656        seek_to_ms: -1,
657        controls: true,
658        looping: false,
659        muted: false,
660        on_ended: Some(tok(on_ended)),
661        poster: None,
662        start_at_ms: -1,
663        captions: Vec::new(),
664        rate: 1.0,
665        volume: 1.0,
666        urls,
667        start_index,
668        seek_index: -1,
669        allow_pip: false,
670    }
671}
672/// Apply a mutation to a [`Widget::Video`]'s fields, passing other widgets through unchanged. Keeps
673/// the `with_*` video modifiers from each having to spell out all of `Video`'s fields.
674fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
675    match widget {
676        Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
677            poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
678            let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
679                poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
680            f(&mut v);
681            Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
682                controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
683                poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
684                volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
685                allow_pip: v.allow_pip }
686        }
687        other => other,
688    }
689}
690struct VideoFields {
691    url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
692    muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
693    captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
694    seek_index: i64, allow_pip: bool,
695}
696/// Loop a [`video_player`] (restart on end). No-op on non-Video widgets.
697#[must_use]
698pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
699/// Start a [`video_player`] muted (needed for reliable autoplay). No-op on non-Video widgets.
700#[must_use]
701pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
702/// Hide the native transport controls on a [`video_player`] (the app drives it). No-op otherwise.
703#[must_use]
704pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
705/// Show `poster` (an image URL) before the first play / while idle. No-op on non-Video widgets.
706#[must_use]
707pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
708    let poster = poster.into();
709    map_video(widget, move |v| v.poster = Some(poster))
710}
711/// Resume a [`video_player`] at `start_at_ms` (applied once on load). No-op on non-Video widgets.
712#[must_use]
713pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
714    map_video(widget, move |v| v.start_at_ms = start_at_ms)
715}
716/// Attach subtitle/caption tracks to a [`video_player`] (see [`Caption`]). No-op on non-Video widgets.
717#[must_use]
718pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
719    map_video(widget, move |v| v.captions = captions)
720}
721/// Set playback speed (`1.0` = normal) on a [`video_player`]. No-op on non-Video widgets.
722#[must_use]
723pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
724/// Set the volume (`0.0`–`1.0`) on a [`video_player`]. No-op on non-Video widgets.
725#[must_use]
726pub fn with_volume(widget: Widget, volume: f32) -> Widget {
727    map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
728}
729/// Force a playlist [`video_playlist`] to jump to track `index` when this CHANGES. No-op otherwise.
730#[must_use]
731pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
732    map_video(widget, move |v| v.seek_index = index)
733}
734/// Enable Picture-in-Picture on a [`video_player`] (the shell adds a PiP affordance). No-op otherwise.
735#[must_use]
736pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
737/// A native web view showing the page / embedded player at `url` (`WKWebView` / Android `WebView` /
738/// `<iframe>`). General-purpose: docs, dashboards, or a hosted player embed (e.g. a Bunny.net /
739/// YouTube embed URL). NOT the default video player — use [`video_player`] for that. Give it room
740/// (a sized container or a card).
741#[must_use]
742pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
743
744/// An interactive map centered at (`center_lat`, `center_lng`) with the given `zoom` (≈ MapLibre/Google
745/// zoom levels: ~2 world, ~14 city, ~17 street). iOS MapKit / Android MapLibre / web MapLibre-GL — no
746/// API key. Add pins with [`with_markers`], a vector style with [`with_map_style`]. Taps arrive in
747/// [`MobilerApp::input`] as `Input { id: "{id}.tap", Text("lat,lng") }` / `{ "{id}.marker", Text(id) }`.
748/// Give it a height (a sized container or card).
749#[must_use]
750pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
751    Widget::Map {
752        id: id.into(),
753        center_lat,
754        center_lng,
755        zoom,
756        markers: Vec::new(),
757        style_url: None,
758        interactive: true,
759    }
760}
761/// Add/replace the pins on a [`map`] (no-op on any other widget).
762#[must_use]
763pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
764    match widget {
765        Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
766            Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
767        other => other,
768    }
769}
770/// Set the MapLibre vector-style URL (Android + web; iOS MapKit ignores it). None → a free default.
771#[must_use]
772pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
773    match widget {
774        Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
775            Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
776        other => other,
777    }
778}
779/// A map pin at (`lat`, `lng`); `id` is echoed on tap. Add a title with [`marker_titled`].
780#[must_use]
781pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
782    MapMarker { id: id.into(), lat, lng, title: None }
783}
784/// A titled map pin (the title shows in the marker's callout/popup).
785#[must_use]
786pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
787    MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
788}
789/// A single unnamed series wrapping `values` — the back-compat shape for `bar_chart`/`line_chart`.
790fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
791    vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
792}
793
794/// A bar chart of `values` (normalized to the max), with optional per-value `labels`.
795/// Single-series, no axis or legend — for richer charts use [`chart`].
796#[must_use]
797pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
798    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
799}
800/// A line chart of `values` (normalized to the max), with optional per-value `labels`.
801/// Single-series, no axis or legend — for richer charts use [`chart`].
802#[must_use]
803pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
804    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
805}
806/// A multi-series chart in the given `style`, with optional x-axis `labels`, y-`axis` gridlines/
807/// ticks (cartesian styles), and a series `legend`. The general builder behind the convenience
808/// constructors below.
809#[must_use]
810pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
811    Widget::Chart { series, labels, style, axis, legend }
812}
813/// Bars stacked to a total per x-slot. Axis + legend on by default.
814#[must_use]
815pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
816    chart(series, labels, ChartStyle::StackedBar, true, true)
817}
818/// Bars where each x-slot fills to 100% — series as proportions. Legend on, no value axis.
819#[must_use]
820pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
821    chart(series, labels, ChartStyle::StackedBar100, false, true)
822}
823/// A pie chart — each series is one wedge sized by its magnitude. Legend on.
824#[must_use]
825pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
826    chart(series, vec![], ChartStyle::Pie, false, true)
827}
828/// A donut chart (pie with a center hole). Legend on.
829#[must_use]
830pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
831    chart(series, vec![], ChartStyle::Donut, false, true)
832}
833/// Concentric progress rings — one per series, swept by `sum(values) / goal`. Legend on.
834/// Give each series a goal via [`ChartSeries::with_goal`].
835#[must_use]
836pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
837    chart(series, vec![], ChartStyle::Rings, false, true)
838}
839/// A single radial gauge — the first series' `value / goal` with the number in the center.
840#[must_use]
841pub fn gauge_chart(series: ChartSeries) -> Widget {
842    chart(vec![series], vec![], ChartStyle::Gauge, false, false)
843}
844
845/// A variable-width stacked-region ("coverage-gap" / Marimekko) chart. `regions` are rectangles in
846/// the `[0, x_max] × [0, y_max]` plane (build with [`ChartRegion::new`]); `ticks` label the
847/// irregular x-axis; `ref_lines` are horizontal target/max lines ([`ChartRefLine::target`]/`::max`);
848/// `legend` names the colors. Add a right-side bracket annotation with [`with_bracket`].
849#[must_use]
850pub fn region_chart(
851    regions: Vec<ChartRegion>,
852    ticks: Vec<ChartTick>,
853    x_max: f32,
854    y_max: f32,
855    ref_lines: Vec<ChartRefLine>,
856    legend: Vec<ChartLegendItem>,
857) -> Widget {
858    Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
859}
860
861/// Attach a right-side bracket annotation to a [`region_chart`] (no-op on any other widget).
862#[must_use]
863pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
864    match widget {
865        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
866            Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
867        }
868        other => other,
869    }
870}
871
872/// Days in `month` (1–12) of `year`, leap-year aware.
873fn days_in_month(year: u32, month: u8) -> u8 {
874    match month {
875        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
876        4 | 6 | 9 | 11 => 30,
877        2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
878        _ => 30,
879    }
880}
881
882/// Weekday of `year-month-day` as 0=Sunday..6=Saturday (Sakamoto's algorithm).
883fn weekday(year: u32, month: u8, day: u8) -> u8 {
884    const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
885    let y = if month < 3 { year - 1 } else { year };
886    let m = month as usize - 1;
887    ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
888}
889
890/// An inline month calendar for `year`/`month` (1–12), US English (Sunday-first). `on_day(d)`
891/// builds the tap event for each day `d`; `selected` highlights a day. See [`calendar_in`] for a
892/// localized calendar with per-day markers.
893#[must_use]
894pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
895    calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
896}
897
898/// A localized inline month calendar: the title, weekday header and week start follow `locale`
899/// (e.g. [`Locale::SrLatn`] → "Septembar 2026", Monday-first `P U S Č P S N`). `markers` is one
900/// busy-level per day (`markers[d-1]`, `0..=3`, drawn as that many dots; `0` = none) — pass `&[]`
901/// for no markers. Shorter slices pad with `0`; levels above 3 clamp to 3.
902#[must_use]
903pub fn calendar_in<E: Serialize>(
904    locale: Locale,
905    year: u32,
906    month: u8,
907    selected: Option<u8>,
908    markers: &[u8],
909    on_day: impl Fn(u8) -> E,
910) -> Widget {
911    let n = days_in_month(year, month);
912    let start = locale.week_start().sun0();
913    let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
914    let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
915    let markers = if markers.is_empty() {
916        Vec::new()
917    } else {
918        (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
919    };
920    Widget::Calendar {
921        year,
922        month,
923        title: format::month_year(year, u32::from(month), locale),
924        weekday_labels,
925        leading_blanks,
926        selected,
927        on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
928        markers,
929    }
930}
931
932/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
933/// tappable. On web the actions render inline (no gesture).
934#[must_use]
935pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
936    Widget::SwipeAction {
937        child: Box::new(child),
938        actions: actions
939            .into_iter()
940            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
941            .collect(),
942    }
943}
944#[must_use]
945pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
946
947#[must_use]
948pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
949#[must_use]
950pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
951#[must_use]
952pub fn card(child: Widget, style: CardStyle) -> Widget {
953    Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
954}
955/// A tappable card carrying a typed press event.
956#[must_use]
957pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
958    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
959}
960/// Put an icon before a `Badge`'s label, so the status reads without its colour
961/// (`with_icon(badge("Confirmed", Tone::Success), Icon::Check)`). Decorative: only the label is
962/// read. No-op on any other widget.
963#[must_use]
964pub fn with_icon(widget: Widget, icon: Icon) -> Widget {
965    match widget {
966        Widget::Badge { label, tone, .. } => Widget::Badge { label, tone, icon: Some(icon) },
967        other => other,
968    }
969}
970
971/// Give an `Avatar` initials, drawn when its `source` is empty or fails to load:
972/// `with_initials(avatar(""), "MŽ")`. Pass the initials, not the name — only the first two
973/// characters are drawn. No-op on any other widget.
974#[must_use]
975pub fn with_initials(widget: Widget, initials: impl Into<String>) -> Widget {
976    match widget {
977        Widget::Avatar { source, status, size, .. } => Widget::Avatar { source, status, initials: Some(initials.into()), size },
978        other => other,
979    }
980}
981
982/// Set an `Avatar`'s diameter in dp/pt/px (default 48); the status dot keeps its size. No-op on any
983/// other widget.
984#[must_use]
985pub fn with_avatar_size(widget: Widget, size: u8) -> Widget {
986    match widget {
987        Widget::Avatar { source, status, initials, .. } => Widget::Avatar { source, status, initials, size: Some(size) },
988        other => other,
989    }
990}
991
992/// Attach a long-press (press-and-hold) event to a `Card`. No-op on any other widget.
993/// Combines with `card` / `card_button` — a card can carry both a tap and a long-press.
994#[must_use]
995pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
996    match widget {
997        Widget::Card { child, style, on_press, .. } => Widget::Card {
998            child,
999            style,
1000            on_press,
1001            on_long_press: Some(tok(on_long_press)),
1002        },
1003        other => other,
1004    }
1005}
1006/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
1007/// darkened background and the rest render on top.
1008#[must_use]
1009pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
1010    Widget::Box { children, align, scrim }
1011}
1012/// A step indicator: `total` equal segments with the first `current` filled (`current` is clamped
1013/// to `total`), spoken as "Step 2 of 3" in the root scaffold's [`ShellLabels::step_of`] language:
1014/// `steps(3, 2)`. It speaks the step itself: to also show the text, use [`with_step_caption`]
1015/// rather than a separate `text`, which screen readers would read a second time.
1016#[must_use]
1017pub fn steps(total: u8, current: u8) -> Widget {
1018    Widget::Steps { total, current: current.min(total), caption: false }
1019}
1020
1021/// Show the step text ("Korak 2 od 3", from [`ShellLabels::step_of`]) above a `steps` bar, as part
1022/// of the same single accessibility element: `with_step_caption(steps(3, 2))`. No-op elsewhere.
1023#[must_use]
1024pub fn with_step_caption(widget: Widget) -> Widget {
1025    match widget {
1026        Widget::Steps { total, current, .. } => Widget::Steps { total, current, caption: true },
1027        other => other,
1028    }
1029}
1030
1031/// The step indicator's spoken text: `template`'s `{current}` / `{total}` filled in; a missing or
1032/// empty template is `"Step {current} of {total}"`. (Shells use this, or its native twin.)
1033#[must_use]
1034pub fn step_text(template: Option<&str>, current: u8, total: u8) -> String {
1035    let t = template.filter(|t| !t.is_empty()).unwrap_or("Step {current} of {total}");
1036    t.replace("{current}", &current.to_string()).replace("{total}", &total.to_string())
1037}
1038
1039#[must_use]
1040pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children, columns: None } }
1041/// Give a `Grid` exactly `columns` equal columns (clamped to 1–4) at every width, instead of the
1042/// adaptive 2-on-a-phone rule: `with_columns(grid(slots), 3)`. No-op on any other widget.
1043#[must_use]
1044pub fn with_columns(widget: Widget, columns: u8) -> Widget {
1045    match widget {
1046        Widget::Grid { children, .. } => Widget::Grid { children, columns: Some(columns.clamp(1, 4)) },
1047        other => other,
1048    }
1049}
1050/// A two-pane master-detail layout ([`Widget::Split`]). Side-by-side on a wide screen (tablet /
1051/// landscape); one pane on a phone — `primary` until `show_detail` (the app sets it on selection),
1052/// then `detail` with a back chevron firing `on_back`. On wide, `detail` should show a placeholder
1053/// until a row is selected.
1054#[must_use]
1055pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
1056    Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
1057}
1058/// Horizontally scrolling row of children (a carousel / chip rail).
1059#[must_use]
1060pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
1061/// A [`scroller`] whose trailing edge fades out — a hint that it scrolls.
1062#[must_use]
1063pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
1064/// A circular avatar image.
1065#[must_use]
1066pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None, initials: None, size: None } }
1067/// A circular avatar image with a colored status dot.
1068#[must_use]
1069pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
1070    Widget::Avatar { source: source.into(), status: Some(status), initials: None, size: None }
1071}
1072/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
1073#[must_use]
1074pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
1075/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
1076#[must_use]
1077pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
1078    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
1079}
1080
1081/// Extra options for [`button_with`]; `ButtonOpts::default()` is a plain [`button`].
1082///
1083/// ```
1084/// use mobiler_core::{ButtonOpts, Icon, Tone};
1085/// let danger_wide = ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide();
1086/// assert!(danger_wide.wide);
1087/// ```
1088#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1089pub struct ButtonOpts {
1090    pub tone: Tone,
1091    pub icon: Option<Icon>,
1092    pub wide: bool,
1093}
1094
1095impl Default for ButtonOpts {
1096    fn default() -> Self {
1097        Self { tone: Tone::Neutral, icon: None, wide: false }
1098    }
1099}
1100
1101impl ButtonOpts {
1102    /// Recolor the button (`Tone::Danger` for destructive actions).
1103    #[must_use]
1104    pub const fn tone(mut self, tone: Tone) -> Self {
1105        self.tone = tone;
1106        self
1107    }
1108    /// A leading icon.
1109    #[must_use]
1110    pub const fn icon(mut self, icon: Icon) -> Self {
1111        self.icon = Some(icon);
1112        self
1113    }
1114    /// Stretch to the available width (a screen's main action).
1115    #[must_use]
1116    pub const fn wide(mut self) -> Self {
1117        self.wide = true;
1118        self
1119    }
1120}
1121
1122#[must_use]
1123pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
1124    button_with(label, style, on_press, ButtonOpts::default())
1125}
1126
1127/// A button with a [`ButtonOpts`] tone, leading icon, and/or full width.
1128#[must_use]
1129pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1130    Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1131}
1132#[must_use]
1133pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1134    Widget::IconButton { icon, on_press: tok(on_press) }
1135}
1136#[must_use]
1137pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1138    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1139}
1140#[must_use]
1141pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1142    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1143}
1144/// A text field with full control over [`FieldKind`] and an optional inline
1145/// validation `error`. The kind-specific helpers below ([`secure_field`],
1146/// [`email_field`], …) wrap this for the common cases.
1147#[must_use]
1148pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1149    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1150}
1151/// A masked password field ([`FieldKind::Secure`]).
1152#[must_use]
1153pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1154    field(id, placeholder, value, FieldKind::Secure, None)
1155}
1156/// An email-keyboard field ([`FieldKind::Email`]).
1157#[must_use]
1158pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1159    field(id, placeholder, value, FieldKind::Email, None)
1160}
1161/// A whole-number keypad field ([`FieldKind::Number`]).
1162#[must_use]
1163pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1164    field(id, placeholder, value, FieldKind::Number, None)
1165}
1166/// A decimal keypad field ([`FieldKind::Decimal`]).
1167#[must_use]
1168pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1169    field(id, placeholder, value, FieldKind::Decimal, None)
1170}
1171/// A phone-keypad field ([`FieldKind::Phone`]).
1172#[must_use]
1173pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1174    field(id, placeholder, value, FieldKind::Phone, None)
1175}
1176/// A URL-keyboard field ([`FieldKind::Url`]).
1177#[must_use]
1178pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1179    field(id, placeholder, value, FieldKind::Url, None)
1180}
1181/// A growable multi-line text area ([`FieldKind::Multiline`]).
1182#[must_use]
1183pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1184    field(id, placeholder, value, FieldKind::Multiline, None)
1185}
1186/// Attach an inline validation message to a [`Widget::TextField`], marking it
1187/// invalid. No-op on any other widget.
1188#[must_use]
1189pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1190    match widget {
1191        Widget::TextField { id, placeholder, value, kind, .. } =>
1192            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1193        other => other,
1194    }
1195}
1196
1197/// Wrap `child` so a screen reader (VoiceOver / TalkBack) announces the subtree as ONE element named
1198/// `label` — gives an unlabeled `icon_button`/`image` a name, or groups a card's children into one
1199/// announced element. Add `with_a11y_hint` / `with_a11y_role` for the activation hint + control type.
1200#[must_use]
1201pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1202    Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1203}
1204/// Set the accessibility activation hint (e.g. "Opens your bookings"); wraps `widget` if it isn't an
1205/// [`a11y`] wrapper yet.
1206#[must_use]
1207pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1208    match widget {
1209        Widget::A11y { child, label, role, .. } =>
1210            Widget::A11y { child, label, hint: Some(hint.into()), role },
1211        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1212    }
1213}
1214/// Set the accessibility role / control type; wraps `widget` if it isn't an [`a11y`] wrapper yet.
1215#[must_use]
1216pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1217    match widget {
1218        Widget::A11y { child, label, hint, .. } =>
1219            Widget::A11y { child, label, hint, role: Some(role) },
1220        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1221    }
1222}
1223/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
1224#[must_use]
1225pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1226    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1227}
1228/// One option in a [`segmented`] control, carrying a typed selection event.
1229#[must_use]
1230pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1231    Segment { label: label.into(), selected, on_select: tok(on_select) }
1232}
1233/// A single-choice segmented control (exclusive options in a pill).
1234#[must_use]
1235pub fn segmented(segments: Vec<Segment>) -> Widget {
1236    Widget::Segmented { segments }
1237}
1238#[must_use]
1239pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1240    Widget::Toggle { id: id.into(), label: label.into(), value }
1241}
1242#[must_use]
1243pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1244    Widget::Checkbox { id: id.into(), label: label.into(), value }
1245}
1246#[must_use]
1247pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1248    Widget::Slider { id: id.into(), value, max }
1249}
1250#[must_use]
1251pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1252    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1253}
1254
1255/// A bottom-nav tab carrying a typed selection event (label-only).
1256#[must_use]
1257pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1258    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1259}
1260
1261/// A bottom-nav tab with a leading icon (icon tab bar).
1262#[must_use]
1263pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1264    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1265}
1266
1267/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
1268/// theme-as-data (the shell themes the whole app from it).
1269#[must_use]
1270pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1271    let title = title.into();
1272    // route defaults to the title; root depth = 1.
1273    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, labels: None, appearance: None, bottom_bar: None }
1274}
1275
1276/// Like [`scaffold`], but the top bar (and the system back button) navigate back
1277/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
1278/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
1279#[must_use]
1280pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1281    let title = title.into();
1282    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, labels: None, appearance: None, bottom_bar: None }
1283}
1284
1285/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
1286/// serialization) and `depth` (stack depth) so the shell animates transitions,
1287/// and shows a back affordance (top-bar arrow + system back button) firing
1288/// `on_back` whenever the stack can pop.
1289#[must_use]
1290pub fn nav_scaffold<R, E>(
1291    title: impl Into<String>,
1292    dark_mode: bool,
1293    tabs: Vec<Tab>,
1294    body: Widget,
1295    nav: &Nav<R>,
1296    on_back: E,
1297) -> Widget
1298where
1299    R: Clone + Serialize,
1300    E: Serialize,
1301{
1302    Widget::Scaffold {
1303        title: title.into(),
1304        body: Box::new(body),
1305        tabs,
1306        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1307        dark_mode,
1308        theme: None,
1309        fab: None,
1310        sheet: None,
1311        on_refresh: None,
1312        refreshing: false,
1313        route: nav.route_key(),
1314        depth: nav.depth(),
1315        labels: None,
1316        appearance: None,
1317        bottom_bar: None,
1318    }
1319}
1320
1321/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
1322/// other widget. Lets an app brand its UI without new scaffold builder overloads:
1323/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
1324pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1325    match widget {
1326        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1327            title,
1328            body,
1329            tabs,
1330            back,
1331            dark_mode,
1332            theme: Some(theme),
1333            fab,
1334            sheet,
1335            on_refresh,
1336            refreshing,
1337            route,
1338            depth,
1339            labels,
1340            appearance,
1341            bottom_bar,
1342        },
1343        other => other,
1344    }
1345}
1346
1347/// Anchor a floating action button over a scaffold's body (the raised primary action).
1348/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
1349pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1350    set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1351}
1352
1353/// An extended FAB: the icon plus a label ("Novi termin"), which is also its accessible name.
1354/// Same anchor, colours and shape as [`with_fab`]; no-op on any other widget:
1355/// `with_extended_fab(scaffold(...), Icon::Add, "New booking", Msg::New)`.
1356pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1357    set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1358}
1359
1360/// Pin a screen's main actions (one or two buttons, equal widths) in a bar above the tabs and the
1361/// system navigation; the body ends above it, the FAB and snackbar float above it, and a sheet
1362/// covers it. With the keyboard up it rises above it on iOS, and on Android when the screen has no
1363/// bottom tabs (with tabs, the bar stays with the tab bar behind the keyboard). Empty = no bar. No-op on any other widget — drive it from
1364/// `view` like `with_sheet`: `with_bottom_bar(root, vec![button_with("Završi", .., ButtonOpts::default().wide()), ..])`
1365/// — `wide` buttons fill their equal cells on every shell.
1366#[must_use]
1367pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1368    match widget {
1369        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, .. } => {
1370            Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children) }
1371        }
1372        other => other,
1373    }
1374}
1375
1376fn set_fab(widget: Widget, fab: Fab) -> Widget {
1377    match widget {
1378        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1379            title,
1380            body,
1381            tabs,
1382            back,
1383            dark_mode,
1384            theme,
1385            fab: Some(fab),
1386            sheet,
1387            on_refresh,
1388            refreshing,
1389            route,
1390            depth,
1391            labels,
1392            appearance,
1393            bottom_bar,
1394        },
1395        other => other,
1396    }
1397}
1398
1399/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
1400/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
1401pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1402    match widget {
1403        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1404            title: t,
1405            body,
1406            tabs,
1407            back,
1408            dark_mode,
1409            theme,
1410            fab,
1411            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1412            on_refresh,
1413            refreshing,
1414            route,
1415            depth,
1416            labels,
1417            appearance,
1418            bottom_bar,
1419        },
1420        other => other,
1421    }
1422}
1423
1424/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
1425/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
1426/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
1427pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1428    match widget {
1429        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1430            title,
1431            body,
1432            tabs,
1433            back,
1434            dark_mode,
1435            theme,
1436            fab,
1437            sheet,
1438            on_refresh: Some(tok(on_refresh)),
1439            refreshing,
1440            route,
1441            depth,
1442            labels,
1443            appearance,
1444            bottom_bar,
1445        },
1446        // Pull-to-refresh on a LazyList's top — same API as on a Scaffold. Leaves the load-more
1447        // fields intact.
1448        Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1449            children,
1450            on_load_more,
1451            loading,
1452            has_more,
1453            on_refresh: Some(tok(on_refresh)),
1454            refreshing,
1455            end_label,
1456            fill,
1457        },
1458        other => other,
1459    }
1460}
1461
1462/// Set the app-wide shell text (see [`ShellLabels`]) on a scaffold — e.g.
1463/// `with_labels(root, ShellLabels::new().back("Nazad").ok("U redu").cancel("Otkaži"))` also puts
1464/// those words on a plain `cx.confirm`. Combines with the other scaffold helpers in any order.
1465/// No-op on other widgets.
1466#[must_use]
1467pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1468    match widget {
1469        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, .. } => {
1470            Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar }
1471        }
1472        other => other,
1473    }
1474}
1475
1476/// Choose Light / Dark / System for the scaffold. `System` follows the OS live on every shell and
1477/// switches the theme palette's light/dark set by itself; `dark_mode` is then ignored.
1478#[must_use]
1479pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1480    match widget {
1481        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, .. } => {
1482            Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar }
1483        }
1484        other => other,
1485    }
1486}
1487
1488/// A scrollable list for long/paged feeds that fires `on_load_more` when the user scrolls near the
1489/// end. The app owns the state: append to `children` on each load-more event, set `loading` true
1490/// while the page loads (the shell shows a spinner and won't re-fire), and `has_more=false` when
1491/// the feed is exhausted. Add pull-to-refresh at the top with [`with_refresh`]. Give it room — a
1492/// `LazyList` nested in a scrollable body needs a bounded height to scroll on its own.
1493#[must_use]
1494pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1495    Widget::LazyList {
1496        children,
1497        on_load_more: Some(tok(on_load_more)),
1498        loading,
1499        has_more,
1500        on_refresh: None,
1501        refreshing: false,
1502        end_label: None,
1503        fill: false,
1504    }
1505}
1506
1507/// A scrollable list with no load-more and no refresh — a plain virtualized list of `children`.
1508#[must_use]
1509pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1510    Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1511}
1512
1513/// Text shown at the end of an exhausted paged list (a [`lazy_list`] whose `has_more` is false) —
1514/// e.g. "You're all caught up", in the app's language. Without it nothing is shown there. Combines
1515/// with [`with_refresh`] in either order. No-op on other widgets.
1516#[must_use]
1517pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1518    match widget {
1519        Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1520            Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1521        }
1522        other => other,
1523    }
1524}
1525
1526/// Let a paged list fill the rest of the screen: when it is the scaffold body (or a direct child
1527/// of the body's column — the first such list), the body stops scrolling as a page and the list
1528/// takes the remaining height, scrolling itself. Anywhere else it keeps its normal bounded height.
1529/// Combines with [`with_refresh`] and [`with_end_label`] in any order. No-op on other widgets.
1530#[must_use]
1531pub fn with_fill(widget: Widget) -> Widget {
1532    match widget {
1533        Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1534            Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1535        }
1536        other => other,
1537    }
1538}
1539
1540#[cfg(test)]
1541mod tests {
1542    use super::*;
1543    use serde::Serialize;
1544
1545    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1546    enum Route {
1547        Home,
1548        Detail(u32),
1549    }
1550
1551    #[derive(Serialize)]
1552    enum Ev {
1553        Tap,
1554        Open(u32),
1555    }
1556
1557    // ---- PluginResponse ----
1558
1559    #[test]
1560    fn plugin_response_carries_bytes_and_converts_text() {
1561        let r = PluginResponse::text(true, "hello");
1562        assert!(r.ok);
1563        assert_eq!(r.output, b"hello".to_vec());
1564        assert_eq!(r.as_text(), Some("hello"));
1565
1566        let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1567        assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1568    }
1569
1570    // ---- Nav ----
1571
1572    #[test]
1573    fn nav_push_pop_depth() {
1574        let mut nav = Nav::new(Route::Home);
1575        assert_eq!(nav.depth(), 1);
1576        assert!(!nav.can_go_back());
1577
1578        nav.push(Route::Detail(7));
1579        assert_eq!(nav.depth(), 2);
1580        assert!(nav.can_go_back());
1581        assert!(matches!(nav.current(), Route::Detail(7)));
1582
1583        nav.pop();
1584        assert_eq!(nav.depth(), 1);
1585        assert!(matches!(nav.current(), Route::Home));
1586
1587        nav.pop(); // no-op at the root
1588        assert_eq!(nav.depth(), 1);
1589    }
1590
1591    #[test]
1592    fn nav_reset_replaces_stack() {
1593        let mut nav = Nav::new(Route::Home);
1594        nav.push(Route::Detail(1));
1595        nav.push(Route::Detail(2));
1596        nav.reset(Route::Detail(9));
1597        assert_eq!(nav.depth(), 1);
1598        assert!(matches!(nav.current(), Route::Detail(9)));
1599    }
1600
1601    #[test]
1602    fn nav_route_key_is_serialization() {
1603        let nav = Nav::new(Route::Detail(3));
1604        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1605    }
1606
1607    // ---- builders ----
1608
1609    #[test]
1610    fn scaffold_sets_route_depth_and_no_back() {
1611        match scaffold("Home", false, vec![], text("x")) {
1612            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1613                assert_eq!(route, "Home");
1614                assert_eq!(depth, 1);
1615                assert!(back.is_none());
1616                assert!(!dark_mode);
1617            }
1618            other => panic!("expected Scaffold, got {other:?}"),
1619        }
1620    }
1621
1622    #[test]
1623    fn scaffold_back_is_depth_2_with_back() {
1624        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1625            Widget::Scaffold { depth, back, dark_mode, .. } => {
1626                assert_eq!(depth, 2);
1627                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1628                assert!(dark_mode);
1629            }
1630            other => panic!("expected Scaffold, got {other:?}"),
1631        }
1632    }
1633
1634    #[test]
1635    fn nav_scaffold_shows_back_only_when_poppable() {
1636        let mut nav = Nav::new(Route::Home);
1637        // at the root: no back, depth 1, route = serialized current route
1638        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1639            Widget::Scaffold { back, depth, route, .. } => {
1640                assert!(back.is_none());
1641                assert_eq!(depth, 1);
1642                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1643            }
1644            other => panic!("expected Scaffold, got {other:?}"),
1645        }
1646        // after a push: back present, depth 2
1647        nav.push(Route::Detail(2));
1648        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1649            Widget::Scaffold { back, depth, .. } => {
1650                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1651                assert_eq!(depth, 2);
1652            }
1653            other => panic!("expected Scaffold, got {other:?}"),
1654        }
1655    }
1656
1657    #[test]
1658    fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1659        let l = ShellLabels::new().back("Nazad").ok("U redu");
1660        assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1661        let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1662        assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1663        // Every scaffold combinator must carry labels through, in either order.
1664        let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1665        assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1666        let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1667        assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1668        let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1669        assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1670        let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1671        assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1672        // No-op elsewhere.
1673        assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1674        // Builder fills only what was set.
1675        assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1676        // nav_scaffold also defaults labels to None.
1677        let nav = Nav::new(Route::Home);
1678        assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1679    }
1680
1681    #[test]
1682    fn button_with_carries_tone_icon_and_width() {
1683        assert!(matches!(
1684            button("Go", ButtonStyle::Filled, Ev::Tap),
1685            Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1686        ));
1687        assert!(matches!(
1688            button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1689            Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1690        ));
1691    }
1692
1693    #[test]
1694    fn buttons_carry_serialized_event_tokens() {
1695        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1696            Widget::Button { label, on_press, .. } => {
1697                assert_eq!(label, "Go");
1698                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1699            }
1700            other => panic!("expected Button, got {other:?}"),
1701        }
1702        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1703            Widget::Card { on_press, .. } => {
1704                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1705            }
1706            other => panic!("expected Card, got {other:?}"),
1707        }
1708        // a plain card is not tappable
1709        match card(text("c"), CardStyle::Elevated) {
1710            Widget::Card { on_press, on_long_press, .. } => {
1711                assert!(on_press.is_none());
1712                assert!(on_long_press.is_none());
1713            }
1714            other => panic!("expected Card, got {other:?}"),
1715        }
1716        // with_long_press attaches a long-press, keeping any existing tap
1717        match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1718            Widget::Card { on_press, on_long_press, .. } => {
1719                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1720                assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1721            }
1722            other => panic!("expected Card, got {other:?}"),
1723        }
1724        // with_long_press on a non-Card is a no-op
1725        assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1726    }
1727
1728    // ---- Cx capabilities ----
1729
1730    #[test]
1731    fn cx_notify_and_save_enqueue_notifications() {
1732        let mut cx = Cx::<Ev>::default();
1733        cx.notify("toast", "show", "hi");
1734        cx.save("blob");
1735        assert_eq!(cx.notifications.len(), 2);
1736        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1737        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1738        assert!(cx.requests.is_empty());
1739    }
1740
1741    #[test]
1742    fn cx_http_helpers_build_requests() {
1743        let mut cx = Cx::<Ev>::default();
1744        cx.get("http://h/x", |_| Ev::Tap);
1745        cx.post("http://h/y", "hello", |_| Ev::Tap);
1746        cx.put("http://h/p", "putbody", |_| Ev::Tap);
1747        cx.patch("http://h/z", "patch", |_| Ev::Tap);
1748        cx.delete("http://h/d", |_| Ev::Tap);
1749
1750        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1751        assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1752        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1753
1754        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1755        assert_eq!(get_input["url"], "http://h/x");
1756        assert!(get_input["body"].is_null());
1757
1758        let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1759        assert_eq!(put_input["url"], "http://h/p");
1760        assert_eq!(put_input["body"], "putbody");
1761    }
1762
1763    #[test]
1764    fn request_builder_emits_headers_in_order() {
1765        let mut cx = Cx::<Ev>::default();
1766        cx.request("PUT", "http://h/access-key")
1767            .bearer("tok123")
1768            .header("X-Trace-Id", "abc")
1769            .body("{}")
1770            .send(|_| Ev::Tap);
1771
1772        assert_eq!(cx.requests.len(), 1);
1773        let (call, _) = &cx.requests[0];
1774        assert_eq!(call.plugin, "http");
1775        assert_eq!(call.op, "PUT");
1776
1777        let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1778        assert_eq!(input["url"], "http://h/access-key");
1779        assert_eq!(input["body"], "{}");
1780        assert_eq!(input["headers"][0]["name"], "Authorization");
1781        assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1782        assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1783        assert_eq!(input["headers"][1]["value"], "abc");
1784    }
1785
1786    #[test]
1787    fn helpers_emit_no_headers_field_content() {
1788        let mut cx = Cx::<Ev>::default();
1789        cx.get("http://h/x", |_| Ev::Tap);
1790        let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1791        assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1792    }
1793
1794    #[test]
1795    fn continuation_receives_decoded_outcome() {
1796        #[derive(Debug, PartialEq)]
1797        enum Got { Conflict, Offline, Other }
1798
1799        let classify = |r: PluginResponse| -> Got {
1800            match HttpOutcome::decode(&r.output).unwrap() {
1801                HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1802                HttpOutcome::TransportError { .. } => Got::Offline,
1803                _ => Got::Other,
1804            }
1805        };
1806
1807        let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1808        assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1809
1810        let offline = HttpOutcome::TransportError { message: "refused".into() };
1811        assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1812    }
1813
1814    #[test]
1815    fn decode_failure_in_continuation_surfaces_as_transport_error() {
1816        // Drives the actual `send()` callback path (not just `HttpOutcome::decode`
1817        // directly): stores a continuation via `cx.request(...).send(...)`, then
1818        // invokes it with a `PluginResponse` whose `output` is malformed bytes, the
1819        // way the shell would if it returned something undecodable.
1820        let mut cx = Cx::<Ev>::default();
1821
1822        cx.request("GET", "http://h/x").send(|outcome| {
1823            match outcome {
1824                HttpOutcome::TransportError { message } => {
1825                    assert!(
1826                        message.contains("malformed http response"),
1827                        "unexpected message: {message}"
1828                    );
1829                }
1830                HttpOutcome::Response { .. } => {
1831                    panic!("garbage bytes must not decode as a Response")
1832                }
1833            }
1834            Ev::Tap
1835        });
1836
1837        assert_eq!(cx.requests.len(), 1);
1838        let (_, continuation) = cx.requests.remove(0);
1839        // Must not panic: a malformed `output` has to surface as `TransportError`,
1840        // asserted inside the callback above.
1841        continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1842    }
1843
1844    #[test]
1845    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1846        let mut cx = Cx::<Ev>::default();
1847        cx.pick_photo(|_| Ev::Tap);
1848        cx.capture_photo(|_| Ev::Tap);
1849        assert_eq!(cx.requests.len(), 2);
1850        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1851        // carry empty input (the shell needs no parameters to launch picker/camera).
1852        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", ""));
1853        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", ""));
1854    }
1855
1856    #[test]
1857    fn cx_capture_photo_routes_success_and_cancel() {
1858        // Happy path: ok=true delivers the URI to the success branch.
1859        let mut cx = Cx::<Ev>::default();
1860        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1861        let (_, then) = cx.requests.pop().unwrap();
1862        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1863
1864        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1865        let mut cx = Cx::<Ev>::default();
1866        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1867        let (_, then) = cx.requests.pop().unwrap();
1868        assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1869    }
1870
1871    #[test]
1872    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1873        let mut cx = Cx::<Ev>::default();
1874        cx.copy("c");
1875        cx.share("s");
1876        cx.open_url("u");
1877        cx.toast("t");
1878        cx.haptic("heavy");
1879        let got: Vec<(&str, &str, &str)> = cx
1880            .notifications
1881            .iter()
1882            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1883            .collect();
1884        assert_eq!(
1885            got,
1886            vec![
1887                ("clipboard", "copy", "c"),
1888                ("share", "text", "s"),
1889                ("browser", "open", "u"),
1890                ("toast", "show", "t"),
1891                ("haptics", "heavy", ""), // haptic style is the op, input empty
1892            ]
1893        );
1894        assert!(cx.requests.is_empty());
1895    }
1896
1897    #[test]
1898    fn display_and_headline_builders() {
1899        assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
1900        assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
1901        let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
1902    }
1903
1904    #[test]
1905    fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
1906        let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
1907        assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
1908        assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
1909        assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
1910    }
1911
1912    #[test]
1913    fn with_theme_and_labels_keep_the_appearance() {
1914        let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
1915        let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
1916        assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
1917    }
1918
1919    #[test]
1920    fn appearance_query_and_stream_shapes() {
1921        let mut cx = Cx::<Ev>::default();
1922        cx.system_appearance(|_| Ev::Tap);
1923        let (call, _) = &cx.requests[0];
1924        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
1925        cx.subscribe_appearance("appr", |_| Ev::Tap);
1926        let (st, _) = &cx.streams[0];
1927        assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
1928    }
1929
1930    #[test]
1931    fn cx_device_model_is_a_request_not_a_notification() {
1932        let mut cx = Cx::<Ev>::default();
1933        cx.device_model(|_| Ev::Tap);
1934        assert!(cx.notifications.is_empty());
1935        assert_eq!(cx.requests.len(), 1);
1936        let (call, _) = &cx.requests[0];
1937        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1938    }
1939
1940    #[test]
1941    fn cx_device_locale_requests_the_device_locale_op() {
1942        let mut cx = Cx::<Ev>::default();
1943        cx.device_locale(|_| Ev::Tap);
1944        assert!(cx.notifications.is_empty());
1945        assert_eq!(cx.requests.len(), 1);
1946        let (call, _) = &cx.requests[0];
1947        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1948    }
1949
1950    #[test]
1951    fn cx_now_requests_the_datetime_now_op() {
1952        let mut cx = Cx::<Ev>::default();
1953        cx.now(|_| Ev::Tap);
1954        assert_eq!(cx.requests.len(), 1);
1955        let (call, _) = &cx.requests[0];
1956        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1957    }
1958
1959    #[test]
1960    fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1961        let mut cx = Cx::<Ev>::default();
1962        cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1963        // It's a stream, not a one-shot request or a notification.
1964        assert!(cx.notifications.is_empty());
1965        assert!(cx.requests.is_empty());
1966        assert_eq!(cx.streams.len(), 1);
1967        let (call, on_event) = &cx.streams[0];
1968        assert_eq!(
1969            (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1970            ("ws", "websocket", "stream", "wss://h/x")
1971        );
1972        // The continuation is `Fn` — it can map MANY events, not just one.
1973        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1974        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1975        assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1976    }
1977
1978    #[test]
1979    fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1980        let mut cx = Cx::<Ev>::default();
1981        cx.unsubscribe("ws");
1982        assert!(cx.streams.is_empty());
1983        assert_eq!(cx.notifications.len(), 1);
1984        // The shell tears down the native source registered under this key.
1985        assert_eq!(
1986            cx.notifications[0],
1987            PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1988        );
1989    }
1990
1991    #[test]
1992    fn cx_confirm_serializes_title_message_and_routes_ok() {
1993        let mut cx = Cx::<Ev>::default();
1994        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1995        let (call, then) = cx.requests.pop().unwrap();
1996        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1997        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1998        assert_eq!(v["title"], "Delete?");
1999        assert_eq!(v["message"], "This cannot be undone.");
2000        // ok=true → confirmed branch; ok=false would take the else branch.
2001        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2002    }
2003
2004    #[test]
2005    fn cx_confirm_stays_byte_identical_on_the_wire() {
2006        let mut cx = Cx::<Ev>::default();
2007        cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2008        let (call, _) = cx.requests.pop().unwrap();
2009        assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2010    }
2011
2012    #[test]
2013    fn cx_confirm_with_sends_labels_and_destructive() {
2014        let mut cx = Cx::<Ev>::default();
2015        cx.confirm_with(
2016            Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2017                .confirm_label("Otkaži termin")
2018                .cancel_label("Ne, vrati se")
2019                .destructive(),
2020            |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2021        );
2022        let (call, then) = cx.requests.pop().unwrap();
2023        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2024        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2025        assert_eq!(v["title"], "Otkazati termin?");
2026        assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2027        assert_eq!(v["confirm_label"], "Otkaži termin");
2028        assert_eq!(v["cancel_label"], "Ne, vrati se");
2029        assert_eq!(v["destructive"], true);
2030        assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2031        // Unset labels are omitted, not sent as null.
2032        let mut cx = Cx::<Ev>::default();
2033        cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2034        let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2035        assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2036    }
2037
2038    #[test]
2039    fn with_step_caption_turns_the_caption_on() {
2040        assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2041        assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2042        assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2043    }
2044
2045    #[test]
2046    fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2047        let mut cx = Cx::<Ev>::default();
2048        cx.open_url("https://x");
2049        assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2050        cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2051        let (call, then) = cx.requests.pop().unwrap();
2052        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2053        assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2054    }
2055
2056    #[test]
2057    fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2058        let bar = vec![text("A"), text("B")];
2059        let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2060        assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2061        assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2062        assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2063        let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2064        assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2065        assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2066        assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2067        assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2068        assert!(keep(with_theme(s.clone(), Theme::default())));
2069        assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2070        assert!(keep(with_appearance(s.clone(), Appearance::System)));
2071    }
2072
2073    #[test]
2074    fn steps_builder_clamps_and_step_text_fills_the_template() {
2075        assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2076        assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2077        assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2078        assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2079        assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2080        assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2081    }
2082
2083    #[test]
2084    fn with_columns_sets_clamps_and_ignores_other_widgets() {
2085        assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2086        assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2087        assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2088        assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2089        assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2090    }
2091
2092    #[test]
2093    fn badge_icon_and_avatar_initials_modifiers() {
2094        assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2095        assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2096        let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2097        assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2098        assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2099        // No-ops elsewhere.
2100        assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2101        assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2102        assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2103    }
2104
2105    #[test]
2106    fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2107        let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2108        assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2109        let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2110        assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2111    }
2112
2113    #[test]
2114    fn snackbar_input_is_the_wire_json() {
2115        assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2116        assert_eq!(
2117            Snackbar::new("Cancelled").action("Undo").long().to_input(),
2118            r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2119        );
2120    }
2121
2122    #[test]
2123    fn cx_snackbar_sends_a_snackbar_show_request() {
2124        let mut cx = Cx::<Ev>::default();
2125        cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2126        let (call, then) = cx.requests.pop().unwrap();
2127        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2128        assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2129        assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2130    }
2131
2132    #[test]
2133    fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2134        let mut cx = Cx::<Ev>::default();
2135        cx.pick_date(|_| Ev::Tap);
2136        cx.pick_time(|_| Ev::Tap);
2137        assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2138
2139        let mut cx = Cx::<Ev>::default();
2140        cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2141        cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2142        let (date, _) = &cx.requests[0];
2143        assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2144        let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2145        assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2146        let (time, _) = &cx.requests[1];
2147        assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2148    }
2149
2150    // ---- widget builders ----
2151
2152    #[test]
2153    fn text_builders_carry_their_style() {
2154        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2155        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2156        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2157        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2158        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2159    }
2160
2161    #[test]
2162    fn layout_and_content_builders_produce_their_variants() {
2163        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2164        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2165        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2166        assert!(matches!(divider(), Widget::Divider));
2167        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2168        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2169        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2170        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)));
2171        let rc = with_bracket(
2172            region_chart(
2173                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2174                vec![ChartTick::new(3.0, "3 Mt.")],
2175                65.0, 80.0,
2176                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2177                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2178            ),
2179            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2180        );
2181        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2182        // June 2026 has 30 days and starts on a Monday; US English is Sunday-first → 1 blank.
2183        assert!(matches!(
2184            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2185            Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2186                if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2187        ));
2188        assert!(matches!(
2189            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2190            Widget::SwipeAction { actions, .. } if actions.len() == 1
2191        ));
2192        // lazy_list carries the load-more token + app-owned flags; no refresh by default.
2193        assert!(matches!(
2194            lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2195            Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2196                if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2197        ));
2198        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2199        // with_refresh adds pull-to-refresh to a LazyList without disturbing the load-more fields.
2200        assert!(matches!(
2201            with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2202            Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2203                if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2204        ));
2205        // with_end_label sets the end text; nothing else changes. Default is None (render nothing).
2206        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2207        assert!(matches!(
2208            with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2209            Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2210        ));
2211        // with_refresh keeps an end label set before it, and with_end_label keeps refresh.
2212        assert!(matches!(
2213            with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2214            Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2215        ));
2216        assert!(matches!(
2217            with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2218            Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2219        ));
2220        // No-op on other widgets.
2221        assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2222        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2223        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2224        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2225        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2226        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2227        // a scrim z-stack keeps its align + scrim flag
2228        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2229        // split: children boxed, show_detail + on_back carried.
2230        assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2231            Widget::Split { show_detail: true, on_back: Some(_), .. }));
2232    }
2233
2234    #[test]
2235    fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2236        assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2237        assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2238        let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2239        assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2240        // Other orders keep fill too.
2241        let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2242        assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2243        assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2244        assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2245    }
2246
2247    #[test]
2248    fn input_builders_carry_ids_values_and_event_tokens() {
2249        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2250        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2251        assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2252        // video_player defaults + the cosmetic modifiers (match-and-rebind like with_refresh).
2253        assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2254            Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2255        assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2256            Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2257        // v2 defaults + modifiers.
2258        assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2259            Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2260                if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2261        let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2262            with_captions(video_player("v", "u", true, -1, Ev::Tap),
2263                vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2264            "p.jpg"), 9000), 1.5), 0.5));
2265        assert!(matches!(tuned,
2266            Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2267                if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2268        // playlist builder: url defaults to the first clip; urls/start_index carried; seek_index jumps.
2269        assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2270            Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2271        // modifiers are no-ops on non-Video widgets.
2272        assert!(matches!(with_pip(divider()), Widget::Divider));
2273        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2274        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2275        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2276        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2277        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2278        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2279        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2280        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2281
2282        match chip("Latte", true, Ev::Open(2)) {
2283            Widget::Chip { selected, on_press, .. } => {
2284                assert!(selected);
2285                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2286            }
2287            other => panic!("expected Chip, got {other:?}"),
2288        }
2289        match stepper(5, Ev::Tap, Ev::Open(1)) {
2290            Widget::Stepper { value, on_decrement, on_increment } => {
2291                assert_eq!(value, 5);
2292                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2293                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2294            }
2295            other => panic!("expected Stepper, got {other:?}"),
2296        }
2297        let t = tab("Home", true, Ev::Tap);
2298        assert_eq!(t.label, "Home");
2299        assert!(t.selected);
2300        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2301    }
2302
2303    // ---- ABI serialization round-trips (structural stability of the wire types) ----
2304
2305    #[test]
2306    fn widget_tree_round_trips_through_serde() {
2307        let tree = scaffold(
2308            "Home",
2309            true,
2310            vec![tab("A", true, Ev::Tap)],
2311            column(vec![
2312                title("Hi"),
2313                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2314                image("u", ImageShape::Rounded, ImageRatio::Wide),
2315                slider("s", 2, 5),
2316            ]),
2317        );
2318        let s = serde_json::to_string(&tree).unwrap();
2319        let back: Widget = serde_json::from_str(&s).unwrap();
2320        assert_eq!(s, serde_json::to_string(&back).unwrap());
2321    }
2322
2323    #[test]
2324    fn actions_and_input_values_round_trip() {
2325        let actions = vec![
2326            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2327            Action::Input { id: "n".into(), value: InputValue::Int(7) },
2328            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2329            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2330            Action::Restore { data: "blob".into() },
2331            Action::Start,
2332            Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2333        ];
2334        for a in actions {
2335            let s = serde_json::to_string(&a).unwrap();
2336            let back: Action = serde_json::from_str(&s).unwrap();
2337            assert_eq!(s, serde_json::to_string(&back).unwrap());
2338        }
2339    }
2340
2341    // ---- MobilerShell: the fixed-ABI action dispatch ----
2342
2343    #[derive(Default)]
2344    struct CounterModel {
2345        count: i32,
2346        restored: String,
2347        started: bool,
2348        last_input: String,
2349        app_build: String,
2350    }
2351
2352    #[derive(serde::Serialize, serde::Deserialize)]
2353    enum CounterEv {
2354        Inc,
2355        Add(i32),
2356    }
2357
2358    #[derive(Default)]
2359    struct CounterApp;
2360
2361    impl MobilerApp for CounterApp {
2362        type Event = CounterEv;
2363        type Model = CounterModel;
2364        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2365            match ev {
2366                CounterEv::Inc => model.count += 1,
2367                CounterEv::Add(n) => model.count += n,
2368            }
2369        }
2370        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2371            if let InputValue::Text(t) = value {
2372                model.last_input = format!("{id}={t}");
2373            }
2374        }
2375        fn restore(&self, data: &str, model: &mut CounterModel) {
2376            model.restored = data.to_string();
2377        }
2378        fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2379            model.started = true;
2380            model.app_build = cx.app_info().build.clone();
2381        }
2382        fn view(&self, model: &CounterModel) -> Widget {
2383            text(format!("{}", model.count))
2384        }
2385    }
2386
2387    #[test]
2388    fn shell_dispatches_fired_input_restore_and_start() {
2389        use crux_core::App as _;
2390        let shell = MobilerShell::<CounterApp>::default();
2391        let mut m = CounterModel::default();
2392
2393        // Fired with a valid token → the typed event reaches app.update.
2394        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2395        assert_eq!(m.count, 5);
2396        // Input → app.input.
2397        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2398        assert_eq!(m.last_input, "name=bob");
2399        // Restore → app.restore.
2400        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2401        assert_eq!(m.restored, "saved");
2402        // Start → app.init.
2403        let _ = shell.update(Action::Start, &mut m);
2404        assert!(m.started);
2405        // view renders the (mutated) model through the ABI.
2406        assert!(matches!(shell.view(&m), Widget::Text { .. }));
2407    }
2408
2409    fn info(build: &str) -> AppInfo {
2410        AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2411    }
2412
2413    fn app_info_action(build: &str) -> Action {
2414        let i = info(build);
2415        Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2416    }
2417
2418    // The global is process-wide, so every test that sends Action::AppInfo holds this lock to keep
2419    // `cargo test`'s parallel threads from interleaving.
2420    static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2421
2422    #[test]
2423    fn init_sees_app_info_sent_before_start() {
2424        use crux_core::App as _;
2425        let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2426        let shell = MobilerShell::<CounterApp>::default();
2427        let mut m = CounterModel::default();
2428        let _ = shell.update(app_info_action("7"), &mut m);
2429        let _ = shell.update(Action::Start, &mut m);
2430        assert_eq!(m.app_build, "7");
2431    }
2432
2433    #[test]
2434    fn later_app_info_replaces_earlier() {
2435        use crux_core::App as _;
2436        let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2437        let shell = MobilerShell::<CounterApp>::default();
2438        let mut m = CounterModel::default();
2439        let _ = shell.update(app_info_action("7"), &mut m);
2440        let _ = shell.update(app_info_action("8"), &mut m);
2441        let _ = shell.update(Action::Start, &mut m);
2442        assert_eq!(m.app_build, "8");
2443    }
2444
2445    #[test]
2446    fn app_info_action_does_not_touch_the_model() {
2447        use crux_core::App as _;
2448        let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2449        let shell = MobilerShell::<CounterApp>::default();
2450        let mut m = CounterModel::default();
2451        let _ = shell.update(app_info_action("9"), &mut m);
2452        assert!(!m.started);
2453        assert_eq!(m.count, 0);
2454        assert!(m.restored.is_empty());
2455        assert!(m.last_input.is_empty());
2456        assert!(m.app_build.is_empty());
2457    }
2458
2459    #[test]
2460    fn cx_default_has_empty_app_info() {
2461        let cx = Cx::<Ev>::default();
2462        assert_eq!(cx.app_info(), &AppInfo::default());
2463        assert!(cx.app_info().platform.is_empty());
2464    }
2465
2466    #[test]
2467    fn cx_with_app_info_carries_it() {
2468        let cx = Cx::<Ev>::with_app_info(info("42"));
2469        assert_eq!(cx.app_info().build, "42");
2470        assert_eq!(cx.app_info().bundle_id, "rs.x");
2471    }
2472
2473    #[test]
2474    fn shell_ignores_a_malformed_fired_token() {
2475        use crux_core::App as _;
2476        let shell = MobilerShell::<CounterApp>::default();
2477        let mut m = CounterModel::default();
2478        // A token that doesn't deserialize to the app's event type is dropped — no
2479        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
2480        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2481        assert_eq!(m.count, 0);
2482    }
2483
2484    // An app whose one event makes a notify, a request and a subscription, in that
2485    // call order — used to pin the effect order `MobilerShell::update` emits.
2486    #[derive(Default)]
2487    struct EffectsApp;
2488
2489    impl MobilerApp for EffectsApp {
2490        type Event = CounterEv;
2491        type Model = CounterModel;
2492        fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2493            model.count += 1;
2494            cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2495            cx.notify("toast", "show", "hi");
2496            cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2497            cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2498        }
2499        fn view(&self, model: &CounterModel) -> Widget {
2500            text(format!("{}", model.count))
2501        }
2502    }
2503
2504    #[test]
2505    fn shell_renders_before_requests_notifications_and_streams() {
2506        use crux_core::App as _;
2507        let shell = MobilerShell::<EffectsApp>::default();
2508        let mut m = CounterModel::default();
2509        let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2510        let kinds: Vec<String> = cmd
2511            .effects()
2512            .map(|e| match e {
2513                Effect::Render(_) => "render".to_string(),
2514                Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2515                Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2516                Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2517            })
2518            .collect();
2519        // Render first (the model is final when update returns, so the first frame shows it);
2520        // then notifications, requests (in call order), streams — the order shells already rely on.
2521        assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2522    }
2523
2524    // ---- transfer builders (cx.upload / cx.download) ----
2525
2526    #[test]
2527    fn upload_builder_emits_transfer_stream_call() {
2528        let mut cx = Cx::<Ev>::default();
2529        let key = cx
2530            .upload("https://h/put", "file:///tmp/a.enc")
2531            .bearer("tok")
2532            .header("Content-Type", "application/octet-stream")
2533            .start("up-1", |_ev| Ev::Tap);
2534
2535        assert_eq!(key, "up-1");
2536        assert_eq!(cx.streams.len(), 1);
2537        let (call, _) = &cx.streams[0];
2538        assert_eq!(call.key, "up-1");
2539        assert_eq!(call.plugin, "transfer");
2540        assert_eq!(call.op, "upload");
2541
2542        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2543        assert_eq!(v["url"], "https://h/put");
2544        assert_eq!(v["source"], "file:///tmp/a.enc");
2545        assert_eq!(v["method"], "PUT"); // default
2546        assert_eq!(v["headers"][0]["name"], "Authorization");
2547        assert_eq!(v["headers"][0]["value"], "Bearer tok");
2548        assert_eq!(v["headers"][1]["name"], "Content-Type");
2549    }
2550
2551    #[test]
2552    fn download_builder_uses_dest_and_no_default_method() {
2553        let mut cx = Cx::<Ev>::default();
2554        cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2555        let (call, _) = &cx.streams[0];
2556        assert_eq!(call.op, "download");
2557        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2558        assert_eq!(v["dest"], "/data/att-9.enc");
2559        assert!(v.get("source").is_none());
2560    }
2561
2562    #[test]
2563    fn start_continuation_decodes_progress_and_done() {
2564        use crate::http::HttpOutcome;
2565
2566        // Local to this test (not module-scope `Ev`, which isn't `PartialEq`) so the
2567        // continuation's return type can be compared with `assert_eq!`.
2568        #[derive(Debug, PartialEq)]
2569        enum Got {
2570            Prog(u64),
2571            Done(u16),
2572            Bad,
2573        }
2574        #[derive(Debug, PartialEq)]
2575        struct GotEv(Got);
2576
2577        let mut cx = Cx::<GotEv>::default();
2578        cx.download("https://h/get", "/d").start("k", |ev| match ev {
2579            TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2580            TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2581                Some(s) => Got::Done(s),
2582                None => Got::Bad,
2583            }),
2584        });
2585        let (_, cont) = &cx.streams[0];
2586
2587        let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2588        assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2589
2590        let done = TransferEvent::Done {
2591            outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2592            handle: Some("/d".into()),
2593        };
2594        assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2595    }
2596
2597    #[test]
2598    fn calendar_in_localizes_layout_and_clamps_markers() {
2599        // 1 September 2026 is a Tuesday; Serbian weeks start Monday → 1 leading blank, "U" 2nd column.
2600        let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2601        let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2602        assert_eq!(title, "Septembar 2026");
2603        assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2604        assert_eq!(leading_blanks, 1);
2605        assert_eq!(on_day.len(), 30);
2606        assert_eq!(markers.len(), 30, "padded to one level per day");
2607        assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2608        // Same month, US English (Sunday-first) → 2 leading blanks.
2609        assert!(matches!(
2610            calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2611            Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2612        ));
2613    }
2614
2615    #[test]
2616    fn scroller_hint_is_opt_in() {
2617        assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2618        assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2619    }
2620}