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