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