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