Skip to main content

mobiler_core/
lib.rs

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