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};
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        let mut commands: Vec<Command<Effect, Action>> = Vec::new();
403        for op in cx.notifications {
404            commands.push(Command::notify_shell(op).build());
405        }
406        for (op, then) in cx.requests {
407            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
408                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
409            }));
410        }
411        for (op, then) in cx.streams {
412            // A long-lived shell stream: `then_send` fires `then` once per emitted
413            // event (it's `Fn`), each re-entering `update` as a `Fired` action.
414            commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
415                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
416            }));
417        }
418        commands.push(render());
419        Command::all(commands)
420    }
421
422    fn view(&self, model: &Self::Model) -> Widget {
423        A::default().view(model)
424    }
425}
426
427// ============================ navigation ============================
428
429/// A navigation stack the app holds in its `Model`. The **core owns the stack**
430/// (single source of truth); the framework reads its `route`/`depth` to drive
431/// the shell's push/pop transitions and back button.
432///
433/// `R` is your screen-route type (typically a small enum). Hold it in the model,
434/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
435/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
436/// `pop` so the back affordance works.
437///
438/// ```ignore
439/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
440/// // model.nav: Nav<Route> = Nav::new(Route::List);
441/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
442/// //         Msg::Back      => model.nav.pop(),
443/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
444/// ```
445#[derive(Clone, Debug)]
446pub struct Nav<R> {
447    stack: Vec<R>,
448}
449
450impl<R: Clone + Serialize> Nav<R> {
451    /// A stack containing a single root route.
452    #[must_use]
453    pub fn new(root: R) -> Self {
454        Self { stack: vec![root] }
455    }
456    /// Push a new screen onto the stack.
457    pub fn push(&mut self, route: R) {
458        self.stack.push(route);
459    }
460    /// Pop the top screen (no-op at the root).
461    pub fn pop(&mut self) {
462        if self.stack.len() > 1 {
463            self.stack.pop();
464        }
465    }
466    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
467    pub fn reset(&mut self, root: R) {
468        self.stack = vec![root];
469    }
470    /// The current (top) route — what `view` should render.
471    #[must_use]
472    pub fn current(&self) -> &R {
473        self.stack.last().expect("nav stack is never empty")
474    }
475    /// Stack depth (root = 1).
476    #[must_use]
477    pub fn depth(&self) -> u32 {
478        self.stack.len() as u32
479    }
480    /// Whether there is a screen to pop back to.
481    #[must_use]
482    pub fn can_go_back(&self) -> bool {
483        self.stack.len() > 1
484    }
485    /// Stable identity of the current route (its serialization), used by the shell
486    /// to decide when to animate a transition.
487    fn route_key(&self) -> String {
488        serde_json::to_string(self.current()).expect("serialize route")
489    }
490}
491
492// ============================ widget builders ============================
493// Action-carrying builders take a TYPED event and serialize it into a token.
494
495fn tok<E: Serialize>(event: E) -> String {
496    serde_json::to_string(&event).expect("serialize event")
497}
498
499#[must_use]
500pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
501    Widget::Text { content: content.into(), style }
502}
503#[must_use]
504pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
505#[must_use]
506pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
507#[must_use]
508pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
509#[must_use]
510pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
511#[must_use]
512pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
513
514#[must_use]
515pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
516    Widget::Image { source: source.into(), shape, ratio }
517}
518#[must_use]
519pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
520    Widget::Badge { label: label.into(), tone }
521}
522/// A small colored identity dot.
523#[must_use]
524pub fn color_dot(color: ProjectColor) -> Widget {
525    Widget::ColorDot { color }
526}
527#[must_use]
528pub fn divider() -> Widget { Widget::Divider }
529/// A progress bar (`Some(0.0..=1.0)`) or an indeterminate spinner (`None`).
530#[must_use]
531pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
532/// A shimmer placeholder shown while content loads.
533#[must_use]
534pub fn skeleton() -> Widget { Widget::Skeleton }
535/// An in-app PDF viewer for the document at `url` (remote https URL or local file URI) — rendered
536/// natively per platform (PDFKit / `PdfRenderer` / `<iframe>`). The app just supplies the URL, e.g.
537/// a backend-generated report. Give it room (place in a sized container or a scroller).
538#[must_use]
539pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
540/// A controllable native video player for `url` (remote MP4/HLS or a local file URI), rendered with the
541/// native player per platform (AVPlayer / Media3 ExoPlayer / `<video>`). `id` routes the ~once-per-second
542/// position into `input(id, InputValue::Int(position_ms))`; build it fresh each render with the current
543/// `playing` (play/pause) + `seek_to_ms` (the shell jumps when this CHANGES; `-1` = no seek). `on_ended`
544/// fires when the clip finishes. Defaults: controls shown, not looping/muted, no poster, no resume
545/// offset, no captions, rate 1.0, full volume, single clip (no playlist), PiP off — tune with
546/// [`with_loop`]/[`with_muted`]/[`without_controls`]/[`with_poster`]/[`with_start_at`]/[`with_captions`]/
547/// [`with_rate`]/[`with_volume`]/[`with_pip`] (or [`video_playlist`] for a queue). Give it room.
548#[must_use]
549pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
550    Widget::Video {
551        url: url.into(),
552        id: id.into(),
553        playing,
554        seek_to_ms,
555        controls: true,
556        looping: false,
557        muted: false,
558        on_ended: Some(tok(on_ended)),
559        poster: None,
560        start_at_ms: -1,
561        captions: Vec::new(),
562        rate: 1.0,
563        volume: 1.0,
564        urls: Vec::new(),
565        start_index: 0,
566        seek_index: -1,
567        allow_pip: false,
568    }
569}
570/// A controllable native video player over a **playlist** of `urls` (auto-advances gaplessly; the
571/// shell reports the current track via `input("{id}.index", InputValue::Int(i))`). `start_index` is
572/// the first clip; build it fresh each render with the current `playing`. Force-jump to a track by
573/// pairing this with [`with_seek_index`]. `on_ended` fires when the LAST clip finishes. Same cosmetic
574/// modifiers as [`video_player`]. Empty `urls` renders nothing useful — use [`video_player`] for one clip.
575#[must_use]
576pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
577    Widget::Video {
578        url: urls.first().cloned().unwrap_or_default(),
579        id: id.into(),
580        playing,
581        seek_to_ms: -1,
582        controls: true,
583        looping: false,
584        muted: false,
585        on_ended: Some(tok(on_ended)),
586        poster: None,
587        start_at_ms: -1,
588        captions: Vec::new(),
589        rate: 1.0,
590        volume: 1.0,
591        urls,
592        start_index,
593        seek_index: -1,
594        allow_pip: false,
595    }
596}
597/// Apply a mutation to a [`Widget::Video`]'s fields, passing other widgets through unchanged. Keeps
598/// the `with_*` video modifiers from each having to spell out all of `Video`'s fields.
599fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
600    match widget {
601        Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
602            poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
603            let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
604                poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
605            f(&mut v);
606            Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
607                controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
608                poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
609                volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
610                allow_pip: v.allow_pip }
611        }
612        other => other,
613    }
614}
615struct VideoFields {
616    url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
617    muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
618    captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
619    seek_index: i64, allow_pip: bool,
620}
621/// Loop a [`video_player`] (restart on end). No-op on non-Video widgets.
622#[must_use]
623pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
624/// Start a [`video_player`] muted (needed for reliable autoplay). No-op on non-Video widgets.
625#[must_use]
626pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
627/// Hide the native transport controls on a [`video_player`] (the app drives it). No-op otherwise.
628#[must_use]
629pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
630/// Show `poster` (an image URL) before the first play / while idle. No-op on non-Video widgets.
631#[must_use]
632pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
633    let poster = poster.into();
634    map_video(widget, move |v| v.poster = Some(poster))
635}
636/// Resume a [`video_player`] at `start_at_ms` (applied once on load). No-op on non-Video widgets.
637#[must_use]
638pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
639    map_video(widget, move |v| v.start_at_ms = start_at_ms)
640}
641/// Attach subtitle/caption tracks to a [`video_player`] (see [`Caption`]). No-op on non-Video widgets.
642#[must_use]
643pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
644    map_video(widget, move |v| v.captions = captions)
645}
646/// Set playback speed (`1.0` = normal) on a [`video_player`]. No-op on non-Video widgets.
647#[must_use]
648pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
649/// Set the volume (`0.0`–`1.0`) on a [`video_player`]. No-op on non-Video widgets.
650#[must_use]
651pub fn with_volume(widget: Widget, volume: f32) -> Widget {
652    map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
653}
654/// Force a playlist [`video_playlist`] to jump to track `index` when this CHANGES. No-op otherwise.
655#[must_use]
656pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
657    map_video(widget, move |v| v.seek_index = index)
658}
659/// Enable Picture-in-Picture on a [`video_player`] (the shell adds a PiP affordance). No-op otherwise.
660#[must_use]
661pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
662/// A native web view showing the page / embedded player at `url` (`WKWebView` / Android `WebView` /
663/// `<iframe>`). General-purpose: docs, dashboards, or a hosted player embed (e.g. a Bunny.net /
664/// YouTube embed URL). NOT the default video player — use [`video_player`] for that. Give it room
665/// (a sized container or a card).
666#[must_use]
667pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
668
669/// An interactive map centered at (`center_lat`, `center_lng`) with the given `zoom` (≈ MapLibre/Google
670/// zoom levels: ~2 world, ~14 city, ~17 street). iOS MapKit / Android MapLibre / web MapLibre-GL — no
671/// API key. Add pins with [`with_markers`], a vector style with [`with_map_style`]. Taps arrive in
672/// [`MobilerApp::input`] as `Input { id: "{id}.tap", Text("lat,lng") }` / `{ "{id}.marker", Text(id) }`.
673/// Give it a height (a sized container or card).
674#[must_use]
675pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
676    Widget::Map {
677        id: id.into(),
678        center_lat,
679        center_lng,
680        zoom,
681        markers: Vec::new(),
682        style_url: None,
683        interactive: true,
684    }
685}
686/// Add/replace the pins on a [`map`] (no-op on any other widget).
687#[must_use]
688pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
689    match widget {
690        Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
691            Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
692        other => other,
693    }
694}
695/// Set the MapLibre vector-style URL (Android + web; iOS MapKit ignores it). None → a free default.
696#[must_use]
697pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
698    match widget {
699        Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
700            Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
701        other => other,
702    }
703}
704/// A map pin at (`lat`, `lng`); `id` is echoed on tap. Add a title with [`marker_titled`].
705#[must_use]
706pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
707    MapMarker { id: id.into(), lat, lng, title: None }
708}
709/// A titled map pin (the title shows in the marker's callout/popup).
710#[must_use]
711pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
712    MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
713}
714/// A single unnamed series wrapping `values` — the back-compat shape for `bar_chart`/`line_chart`.
715fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
716    vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
717}
718
719/// A bar chart of `values` (normalized to the max), with optional per-value `labels`.
720/// Single-series, no axis or legend — for richer charts use [`chart`].
721#[must_use]
722pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
723    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
724}
725/// A line chart of `values` (normalized to the max), with optional per-value `labels`.
726/// Single-series, no axis or legend — for richer charts use [`chart`].
727#[must_use]
728pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
729    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
730}
731/// A multi-series chart in the given `style`, with optional x-axis `labels`, y-`axis` gridlines/
732/// ticks (cartesian styles), and a series `legend`. The general builder behind the convenience
733/// constructors below.
734#[must_use]
735pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
736    Widget::Chart { series, labels, style, axis, legend }
737}
738/// Bars stacked to a total per x-slot. Axis + legend on by default.
739#[must_use]
740pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
741    chart(series, labels, ChartStyle::StackedBar, true, true)
742}
743/// Bars where each x-slot fills to 100% — series as proportions. Legend on, no value axis.
744#[must_use]
745pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
746    chart(series, labels, ChartStyle::StackedBar100, false, true)
747}
748/// A pie chart — each series is one wedge sized by its magnitude. Legend on.
749#[must_use]
750pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
751    chart(series, vec![], ChartStyle::Pie, false, true)
752}
753/// A donut chart (pie with a center hole). Legend on.
754#[must_use]
755pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
756    chart(series, vec![], ChartStyle::Donut, false, true)
757}
758/// Concentric progress rings — one per series, swept by `sum(values) / goal`. Legend on.
759/// Give each series a goal via [`ChartSeries::with_goal`].
760#[must_use]
761pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
762    chart(series, vec![], ChartStyle::Rings, false, true)
763}
764/// A single radial gauge — the first series' `value / goal` with the number in the center.
765#[must_use]
766pub fn gauge_chart(series: ChartSeries) -> Widget {
767    chart(vec![series], vec![], ChartStyle::Gauge, false, false)
768}
769
770/// A variable-width stacked-region ("coverage-gap" / Marimekko) chart. `regions` are rectangles in
771/// the `[0, x_max] × [0, y_max]` plane (build with [`ChartRegion::new`]); `ticks` label the
772/// irregular x-axis; `ref_lines` are horizontal target/max lines ([`ChartRefLine::target`]/`::max`);
773/// `legend` names the colors. Add a right-side bracket annotation with [`with_bracket`].
774#[must_use]
775pub fn region_chart(
776    regions: Vec<ChartRegion>,
777    ticks: Vec<ChartTick>,
778    x_max: f32,
779    y_max: f32,
780    ref_lines: Vec<ChartRefLine>,
781    legend: Vec<ChartLegendItem>,
782) -> Widget {
783    Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
784}
785
786/// Attach a right-side bracket annotation to a [`region_chart`] (no-op on any other widget).
787#[must_use]
788pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
789    match widget {
790        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
791            Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
792        }
793        other => other,
794    }
795}
796
797/// Days in `month` (1–12) of `year`, leap-year aware.
798fn days_in_month(year: u32, month: u8) -> u8 {
799    match month {
800        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
801        4 | 6 | 9 | 11 => 30,
802        2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
803        _ => 30,
804    }
805}
806
807/// Weekday of `year-month-day` as 0=Sunday..6=Saturday (Sakamoto's algorithm).
808fn weekday(year: u32, month: u8, day: u8) -> u8 {
809    const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
810    let y = if month < 3 { year - 1 } else { year };
811    let m = month as usize - 1;
812    ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
813}
814
815/// An inline month calendar for `year`/`month` (1–12). `on_day(d)` builds the tap event for each
816/// day `d` in the month; `selected` highlights a day. Leading blanks + weekday header are handled
817/// by the shells from the computed `first_weekday`.
818#[must_use]
819pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
820    let n = days_in_month(year, month);
821    let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
822    Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
823}
824
825/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
826/// tappable. On web the actions render inline (no gesture).
827#[must_use]
828pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
829    Widget::SwipeAction {
830        child: Box::new(child),
831        actions: actions
832            .into_iter()
833            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
834            .collect(),
835    }
836}
837#[must_use]
838pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
839
840#[must_use]
841pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
842#[must_use]
843pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
844#[must_use]
845pub fn card(child: Widget, style: CardStyle) -> Widget {
846    Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
847}
848/// A tappable card carrying a typed press event.
849#[must_use]
850pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
851    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
852}
853/// Attach a long-press (press-and-hold) event to a `Card`. No-op on any other widget.
854/// Combines with `card` / `card_button` — a card can carry both a tap and a long-press.
855#[must_use]
856pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
857    match widget {
858        Widget::Card { child, style, on_press, .. } => Widget::Card {
859            child,
860            style,
861            on_press,
862            on_long_press: Some(tok(on_long_press)),
863        },
864        other => other,
865    }
866}
867/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
868/// darkened background and the rest render on top.
869#[must_use]
870pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
871    Widget::Box { children, align, scrim }
872}
873#[must_use]
874pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
875/// A two-pane master-detail layout ([`Widget::Split`]). Side-by-side on a wide screen (tablet /
876/// landscape); one pane on a phone — `primary` until `show_detail` (the app sets it on selection),
877/// then `detail` with a back chevron firing `on_back`. On wide, `detail` should show a placeholder
878/// until a row is selected.
879#[must_use]
880pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
881    Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
882}
883/// Horizontally scrolling row of children (a carousel / chip rail).
884#[must_use]
885pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
886/// A circular avatar image.
887#[must_use]
888pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
889/// A circular avatar image with a colored status dot.
890#[must_use]
891pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
892    Widget::Avatar { source: source.into(), status: Some(status) }
893}
894/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
895#[must_use]
896pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
897/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
898#[must_use]
899pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
900    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
901}
902
903#[must_use]
904pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
905    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
906}
907#[must_use]
908pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
909    Widget::IconButton { icon, on_press: tok(on_press) }
910}
911#[must_use]
912pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
913    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
914}
915#[must_use]
916pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
917    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
918}
919/// A text field with full control over [`FieldKind`] and an optional inline
920/// validation `error`. The kind-specific helpers below ([`secure_field`],
921/// [`email_field`], …) wrap this for the common cases.
922#[must_use]
923pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
924    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
925}
926/// A masked password field ([`FieldKind::Secure`]).
927#[must_use]
928pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
929    field(id, placeholder, value, FieldKind::Secure, None)
930}
931/// An email-keyboard field ([`FieldKind::Email`]).
932#[must_use]
933pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
934    field(id, placeholder, value, FieldKind::Email, None)
935}
936/// A whole-number keypad field ([`FieldKind::Number`]).
937#[must_use]
938pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
939    field(id, placeholder, value, FieldKind::Number, None)
940}
941/// A decimal keypad field ([`FieldKind::Decimal`]).
942#[must_use]
943pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
944    field(id, placeholder, value, FieldKind::Decimal, None)
945}
946/// A phone-keypad field ([`FieldKind::Phone`]).
947#[must_use]
948pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
949    field(id, placeholder, value, FieldKind::Phone, None)
950}
951/// A URL-keyboard field ([`FieldKind::Url`]).
952#[must_use]
953pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
954    field(id, placeholder, value, FieldKind::Url, None)
955}
956/// A growable multi-line text area ([`FieldKind::Multiline`]).
957#[must_use]
958pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
959    field(id, placeholder, value, FieldKind::Multiline, None)
960}
961/// Attach an inline validation message to a [`Widget::TextField`], marking it
962/// invalid. No-op on any other widget.
963#[must_use]
964pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
965    match widget {
966        Widget::TextField { id, placeholder, value, kind, .. } =>
967            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
968        other => other,
969    }
970}
971
972/// Wrap `child` so a screen reader (VoiceOver / TalkBack) announces the subtree as ONE element named
973/// `label` — gives an unlabeled `icon_button`/`image` a name, or groups a card's children into one
974/// announced element. Add `with_a11y_hint` / `with_a11y_role` for the activation hint + control type.
975#[must_use]
976pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
977    Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
978}
979/// Set the accessibility activation hint (e.g. "Opens your bookings"); wraps `widget` if it isn't an
980/// [`a11y`] wrapper yet.
981#[must_use]
982pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
983    match widget {
984        Widget::A11y { child, label, role, .. } =>
985            Widget::A11y { child, label, hint: Some(hint.into()), role },
986        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
987    }
988}
989/// Set the accessibility role / control type; wraps `widget` if it isn't an [`a11y`] wrapper yet.
990#[must_use]
991pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
992    match widget {
993        Widget::A11y { child, label, hint, .. } =>
994            Widget::A11y { child, label, hint, role: Some(role) },
995        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
996    }
997}
998/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
999#[must_use]
1000pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1001    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1002}
1003/// One option in a [`segmented`] control, carrying a typed selection event.
1004#[must_use]
1005pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1006    Segment { label: label.into(), selected, on_select: tok(on_select) }
1007}
1008/// A single-choice segmented control (exclusive options in a pill).
1009#[must_use]
1010pub fn segmented(segments: Vec<Segment>) -> Widget {
1011    Widget::Segmented { segments }
1012}
1013#[must_use]
1014pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1015    Widget::Toggle { id: id.into(), label: label.into(), value }
1016}
1017#[must_use]
1018pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1019    Widget::Checkbox { id: id.into(), label: label.into(), value }
1020}
1021#[must_use]
1022pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1023    Widget::Slider { id: id.into(), value, max }
1024}
1025#[must_use]
1026pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1027    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1028}
1029
1030/// A bottom-nav tab carrying a typed selection event (label-only).
1031#[must_use]
1032pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1033    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1034}
1035
1036/// A bottom-nav tab with a leading icon (icon tab bar).
1037#[must_use]
1038pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1039    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1040}
1041
1042/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
1043/// theme-as-data (the shell themes the whole app from it).
1044#[must_use]
1045pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1046    let title = title.into();
1047    // route defaults to the title; root depth = 1.
1048    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 }
1049}
1050
1051/// Like [`scaffold`], but the top bar (and the system back button) navigate back
1052/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
1053/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
1054#[must_use]
1055pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1056    let title = title.into();
1057    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 }
1058}
1059
1060/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
1061/// serialization) and `depth` (stack depth) so the shell animates transitions,
1062/// and shows a back affordance (top-bar arrow + system back button) firing
1063/// `on_back` whenever the stack can pop.
1064#[must_use]
1065pub fn nav_scaffold<R, E>(
1066    title: impl Into<String>,
1067    dark_mode: bool,
1068    tabs: Vec<Tab>,
1069    body: Widget,
1070    nav: &Nav<R>,
1071    on_back: E,
1072) -> Widget
1073where
1074    R: Clone + Serialize,
1075    E: Serialize,
1076{
1077    Widget::Scaffold {
1078        title: title.into(),
1079        body: Box::new(body),
1080        tabs,
1081        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1082        dark_mode,
1083        theme: None,
1084        fab: None,
1085        sheet: None,
1086        on_refresh: None,
1087        refreshing: false,
1088        route: nav.route_key(),
1089        depth: nav.depth(),
1090    }
1091}
1092
1093/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
1094/// other widget. Lets an app brand its UI without new scaffold builder overloads:
1095/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
1096pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1097    match widget {
1098        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1099            title,
1100            body,
1101            tabs,
1102            back,
1103            dark_mode,
1104            theme: Some(theme),
1105            fab,
1106            sheet,
1107            on_refresh,
1108            refreshing,
1109            route,
1110            depth,
1111        },
1112        other => other,
1113    }
1114}
1115
1116/// Anchor a floating action button over a scaffold's body (the raised primary action).
1117/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
1118pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1119    match widget {
1120        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1121            title,
1122            body,
1123            tabs,
1124            back,
1125            dark_mode,
1126            theme,
1127            fab: Some(Fab { icon, on_press: tok(on_press) }),
1128            sheet,
1129            on_refresh,
1130            refreshing,
1131            route,
1132            depth,
1133        },
1134        other => other,
1135    }
1136}
1137
1138/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
1139/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
1140pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1141    match widget {
1142        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1143            title: t,
1144            body,
1145            tabs,
1146            back,
1147            dark_mode,
1148            theme,
1149            fab,
1150            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1151            on_refresh,
1152            refreshing,
1153            route,
1154            depth,
1155        },
1156        other => other,
1157    }
1158}
1159
1160/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
1161/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
1162/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
1163pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1164    match widget {
1165        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1166            title,
1167            body,
1168            tabs,
1169            back,
1170            dark_mode,
1171            theme,
1172            fab,
1173            sheet,
1174            on_refresh: Some(tok(on_refresh)),
1175            refreshing,
1176            route,
1177            depth,
1178        },
1179        // Pull-to-refresh on a LazyList's top — same API as on a Scaffold. Leaves the load-more
1180        // fields intact.
1181        Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1182            children,
1183            on_load_more,
1184            loading,
1185            has_more,
1186            on_refresh: Some(tok(on_refresh)),
1187            refreshing,
1188        },
1189        other => other,
1190    }
1191}
1192
1193/// A scrollable list for long/paged feeds that fires `on_load_more` when the user scrolls near the
1194/// end. The app owns the state: append to `children` on each load-more event, set `loading` true
1195/// while the page loads (the shell shows a spinner and won't re-fire), and `has_more=false` when
1196/// the feed is exhausted. Add pull-to-refresh at the top with [`with_refresh`]. Give it room — a
1197/// `LazyList` nested in a scrollable body needs a bounded height to scroll on its own.
1198#[must_use]
1199pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1200    Widget::LazyList {
1201        children,
1202        on_load_more: Some(tok(on_load_more)),
1203        loading,
1204        has_more,
1205        on_refresh: None,
1206        refreshing: false,
1207    }
1208}
1209
1210/// A scrollable list with no load-more and no refresh — a plain virtualized list of `children`.
1211#[must_use]
1212pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1213    Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218    use super::*;
1219    use serde::Serialize;
1220
1221    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1222    enum Route {
1223        Home,
1224        Detail(u32),
1225    }
1226
1227    #[derive(Serialize)]
1228    enum Ev {
1229        Tap,
1230        Open(u32),
1231    }
1232
1233    // ---- PluginResponse ----
1234
1235    #[test]
1236    fn plugin_response_carries_bytes_and_converts_text() {
1237        let r = PluginResponse::text(true, "hello");
1238        assert!(r.ok);
1239        assert_eq!(r.output, b"hello".to_vec());
1240        assert_eq!(r.as_text(), Some("hello"));
1241
1242        let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1243        assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1244    }
1245
1246    // ---- Nav ----
1247
1248    #[test]
1249    fn nav_push_pop_depth() {
1250        let mut nav = Nav::new(Route::Home);
1251        assert_eq!(nav.depth(), 1);
1252        assert!(!nav.can_go_back());
1253
1254        nav.push(Route::Detail(7));
1255        assert_eq!(nav.depth(), 2);
1256        assert!(nav.can_go_back());
1257        assert!(matches!(nav.current(), Route::Detail(7)));
1258
1259        nav.pop();
1260        assert_eq!(nav.depth(), 1);
1261        assert!(matches!(nav.current(), Route::Home));
1262
1263        nav.pop(); // no-op at the root
1264        assert_eq!(nav.depth(), 1);
1265    }
1266
1267    #[test]
1268    fn nav_reset_replaces_stack() {
1269        let mut nav = Nav::new(Route::Home);
1270        nav.push(Route::Detail(1));
1271        nav.push(Route::Detail(2));
1272        nav.reset(Route::Detail(9));
1273        assert_eq!(nav.depth(), 1);
1274        assert!(matches!(nav.current(), Route::Detail(9)));
1275    }
1276
1277    #[test]
1278    fn nav_route_key_is_serialization() {
1279        let nav = Nav::new(Route::Detail(3));
1280        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1281    }
1282
1283    // ---- builders ----
1284
1285    #[test]
1286    fn scaffold_sets_route_depth_and_no_back() {
1287        match scaffold("Home", false, vec![], text("x")) {
1288            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1289                assert_eq!(route, "Home");
1290                assert_eq!(depth, 1);
1291                assert!(back.is_none());
1292                assert!(!dark_mode);
1293            }
1294            other => panic!("expected Scaffold, got {other:?}"),
1295        }
1296    }
1297
1298    #[test]
1299    fn scaffold_back_is_depth_2_with_back() {
1300        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1301            Widget::Scaffold { depth, back, dark_mode, .. } => {
1302                assert_eq!(depth, 2);
1303                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1304                assert!(dark_mode);
1305            }
1306            other => panic!("expected Scaffold, got {other:?}"),
1307        }
1308    }
1309
1310    #[test]
1311    fn nav_scaffold_shows_back_only_when_poppable() {
1312        let mut nav = Nav::new(Route::Home);
1313        // at the root: no back, depth 1, route = serialized current route
1314        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1315            Widget::Scaffold { back, depth, route, .. } => {
1316                assert!(back.is_none());
1317                assert_eq!(depth, 1);
1318                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1319            }
1320            other => panic!("expected Scaffold, got {other:?}"),
1321        }
1322        // after a push: back present, depth 2
1323        nav.push(Route::Detail(2));
1324        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1325            Widget::Scaffold { back, depth, .. } => {
1326                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1327                assert_eq!(depth, 2);
1328            }
1329            other => panic!("expected Scaffold, got {other:?}"),
1330        }
1331    }
1332
1333    #[test]
1334    fn buttons_carry_serialized_event_tokens() {
1335        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1336            Widget::Button { label, on_press, .. } => {
1337                assert_eq!(label, "Go");
1338                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1339            }
1340            other => panic!("expected Button, got {other:?}"),
1341        }
1342        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1343            Widget::Card { on_press, .. } => {
1344                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1345            }
1346            other => panic!("expected Card, got {other:?}"),
1347        }
1348        // a plain card is not tappable
1349        match card(text("c"), CardStyle::Elevated) {
1350            Widget::Card { on_press, on_long_press, .. } => {
1351                assert!(on_press.is_none());
1352                assert!(on_long_press.is_none());
1353            }
1354            other => panic!("expected Card, got {other:?}"),
1355        }
1356        // with_long_press attaches a long-press, keeping any existing tap
1357        match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1358            Widget::Card { on_press, on_long_press, .. } => {
1359                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1360                assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1361            }
1362            other => panic!("expected Card, got {other:?}"),
1363        }
1364        // with_long_press on a non-Card is a no-op
1365        assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1366    }
1367
1368    // ---- Cx capabilities ----
1369
1370    #[test]
1371    fn cx_notify_and_save_enqueue_notifications() {
1372        let mut cx = Cx::<Ev>::default();
1373        cx.notify("toast", "show", "hi");
1374        cx.save("blob");
1375        assert_eq!(cx.notifications.len(), 2);
1376        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1377        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1378        assert!(cx.requests.is_empty());
1379    }
1380
1381    #[test]
1382    fn cx_http_helpers_build_requests() {
1383        let mut cx = Cx::<Ev>::default();
1384        cx.get("http://h/x", |_| Ev::Tap);
1385        cx.post("http://h/y", "hello", |_| Ev::Tap);
1386        cx.put("http://h/p", "putbody", |_| Ev::Tap);
1387        cx.patch("http://h/z", "patch", |_| Ev::Tap);
1388        cx.delete("http://h/d", |_| Ev::Tap);
1389
1390        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1391        assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1392        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1393
1394        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1395        assert_eq!(get_input["url"], "http://h/x");
1396        assert!(get_input["body"].is_null());
1397
1398        let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1399        assert_eq!(put_input["url"], "http://h/p");
1400        assert_eq!(put_input["body"], "putbody");
1401    }
1402
1403    #[test]
1404    fn request_builder_emits_headers_in_order() {
1405        let mut cx = Cx::<Ev>::default();
1406        cx.request("PUT", "http://h/access-key")
1407            .bearer("tok123")
1408            .header("X-Trace-Id", "abc")
1409            .body("{}")
1410            .send(|_| Ev::Tap);
1411
1412        assert_eq!(cx.requests.len(), 1);
1413        let (call, _) = &cx.requests[0];
1414        assert_eq!(call.plugin, "http");
1415        assert_eq!(call.op, "PUT");
1416
1417        let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1418        assert_eq!(input["url"], "http://h/access-key");
1419        assert_eq!(input["body"], "{}");
1420        assert_eq!(input["headers"][0]["name"], "Authorization");
1421        assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1422        assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1423        assert_eq!(input["headers"][1]["value"], "abc");
1424    }
1425
1426    #[test]
1427    fn helpers_emit_no_headers_field_content() {
1428        let mut cx = Cx::<Ev>::default();
1429        cx.get("http://h/x", |_| Ev::Tap);
1430        let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1431        assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1432    }
1433
1434    #[test]
1435    fn continuation_receives_decoded_outcome() {
1436        #[derive(Debug, PartialEq)]
1437        enum Got { Conflict, Offline, Other }
1438
1439        let classify = |r: PluginResponse| -> Got {
1440            match HttpOutcome::decode(&r.output).unwrap() {
1441                HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1442                HttpOutcome::TransportError { .. } => Got::Offline,
1443                _ => Got::Other,
1444            }
1445        };
1446
1447        let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1448        assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1449
1450        let offline = HttpOutcome::TransportError { message: "refused".into() };
1451        assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1452    }
1453
1454    #[test]
1455    fn decode_failure_in_continuation_surfaces_as_transport_error() {
1456        // Drives the actual `send()` callback path (not just `HttpOutcome::decode`
1457        // directly): stores a continuation via `cx.request(...).send(...)`, then
1458        // invokes it with a `PluginResponse` whose `output` is malformed bytes, the
1459        // way the shell would if it returned something undecodable.
1460        let mut cx = Cx::<Ev>::default();
1461
1462        cx.request("GET", "http://h/x").send(|outcome| {
1463            match outcome {
1464                HttpOutcome::TransportError { message } => {
1465                    assert!(
1466                        message.contains("malformed http response"),
1467                        "unexpected message: {message}"
1468                    );
1469                }
1470                HttpOutcome::Response { .. } => {
1471                    panic!("garbage bytes must not decode as a Response")
1472                }
1473            }
1474            Ev::Tap
1475        });
1476
1477        assert_eq!(cx.requests.len(), 1);
1478        let (_, continuation) = cx.requests.remove(0);
1479        // Must not panic: a malformed `output` has to surface as `TransportError`,
1480        // asserted inside the callback above.
1481        continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1482    }
1483
1484    #[test]
1485    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1486        let mut cx = Cx::<Ev>::default();
1487        cx.pick_photo(|_| Ev::Tap);
1488        cx.capture_photo(|_| Ev::Tap);
1489        assert_eq!(cx.requests.len(), 2);
1490        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1491        // carry empty input (the shell needs no parameters to launch picker/camera).
1492        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", ""));
1493        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", ""));
1494    }
1495
1496    #[test]
1497    fn cx_capture_photo_routes_success_and_cancel() {
1498        // Happy path: ok=true delivers the URI to the success branch.
1499        let mut cx = Cx::<Ev>::default();
1500        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1501        let (_, then) = cx.requests.pop().unwrap();
1502        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1503
1504        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1505        let mut cx = Cx::<Ev>::default();
1506        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1507        let (_, then) = cx.requests.pop().unwrap();
1508        assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1509    }
1510
1511    #[test]
1512    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1513        let mut cx = Cx::<Ev>::default();
1514        cx.copy("c");
1515        cx.share("s");
1516        cx.open_url("u");
1517        cx.toast("t");
1518        cx.haptic("heavy");
1519        let got: Vec<(&str, &str, &str)> = cx
1520            .notifications
1521            .iter()
1522            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1523            .collect();
1524        assert_eq!(
1525            got,
1526            vec![
1527                ("clipboard", "copy", "c"),
1528                ("share", "text", "s"),
1529                ("browser", "open", "u"),
1530                ("toast", "show", "t"),
1531                ("haptics", "heavy", ""), // haptic style is the op, input empty
1532            ]
1533        );
1534        assert!(cx.requests.is_empty());
1535    }
1536
1537    #[test]
1538    fn cx_device_model_is_a_request_not_a_notification() {
1539        let mut cx = Cx::<Ev>::default();
1540        cx.device_model(|_| Ev::Tap);
1541        assert!(cx.notifications.is_empty());
1542        assert_eq!(cx.requests.len(), 1);
1543        let (call, _) = &cx.requests[0];
1544        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1545    }
1546
1547    #[test]
1548    fn cx_device_locale_requests_the_device_locale_op() {
1549        let mut cx = Cx::<Ev>::default();
1550        cx.device_locale(|_| Ev::Tap);
1551        assert!(cx.notifications.is_empty());
1552        assert_eq!(cx.requests.len(), 1);
1553        let (call, _) = &cx.requests[0];
1554        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1555    }
1556
1557    #[test]
1558    fn cx_now_requests_the_datetime_now_op() {
1559        let mut cx = Cx::<Ev>::default();
1560        cx.now(|_| Ev::Tap);
1561        assert_eq!(cx.requests.len(), 1);
1562        let (call, _) = &cx.requests[0];
1563        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1564    }
1565
1566    #[test]
1567    fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1568        let mut cx = Cx::<Ev>::default();
1569        cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1570        // It's a stream, not a one-shot request or a notification.
1571        assert!(cx.notifications.is_empty());
1572        assert!(cx.requests.is_empty());
1573        assert_eq!(cx.streams.len(), 1);
1574        let (call, on_event) = &cx.streams[0];
1575        assert_eq!(
1576            (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1577            ("ws", "websocket", "stream", "wss://h/x")
1578        );
1579        // The continuation is `Fn` — it can map MANY events, not just one.
1580        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1581        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1582        assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1583    }
1584
1585    #[test]
1586    fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1587        let mut cx = Cx::<Ev>::default();
1588        cx.unsubscribe("ws");
1589        assert!(cx.streams.is_empty());
1590        assert_eq!(cx.notifications.len(), 1);
1591        // The shell tears down the native source registered under this key.
1592        assert_eq!(
1593            cx.notifications[0],
1594            PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1595        );
1596    }
1597
1598    #[test]
1599    fn cx_confirm_serializes_title_message_and_routes_ok() {
1600        let mut cx = Cx::<Ev>::default();
1601        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1602        let (call, then) = cx.requests.pop().unwrap();
1603        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1604        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1605        assert_eq!(v["title"], "Delete?");
1606        assert_eq!(v["message"], "This cannot be undone.");
1607        // ok=true → confirmed branch; ok=false would take the else branch.
1608        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1609    }
1610
1611    // ---- widget builders ----
1612
1613    #[test]
1614    fn text_builders_carry_their_style() {
1615        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1616        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1617        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1618        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1619        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1620    }
1621
1622    #[test]
1623    fn layout_and_content_builders_produce_their_variants() {
1624        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1625        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1626        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1627        assert!(matches!(divider(), Widget::Divider));
1628        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1629        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1630        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1631        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)));
1632        let rc = with_bracket(
1633            region_chart(
1634                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1635                vec![ChartTick::new(3.0, "3 Mt.")],
1636                65.0, 80.0,
1637                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1638                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1639            ),
1640            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1641        );
1642        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1643        // June 2026 has 30 days and starts on a Monday (weekday 1).
1644        assert!(matches!(
1645            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1646            Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1647        ));
1648        assert!(matches!(
1649            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1650            Widget::SwipeAction { actions, .. } if actions.len() == 1
1651        ));
1652        // lazy_list carries the load-more token + app-owned flags; no refresh by default.
1653        assert!(matches!(
1654            lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1655            Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1656                if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1657        ));
1658        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1659        // with_refresh adds pull-to-refresh to a LazyList without disturbing the load-more fields.
1660        assert!(matches!(
1661            with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1662            Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1663                if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1664        ));
1665        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1666        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1667        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1668        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1669        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1670        // a scrim z-stack keeps its align + scrim flag
1671        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1672        // split: children boxed, show_detail + on_back carried.
1673        assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1674            Widget::Split { show_detail: true, on_back: Some(_), .. }));
1675    }
1676
1677    #[test]
1678    fn input_builders_carry_ids_values_and_event_tokens() {
1679        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1680        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1681        assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1682        // video_player defaults + the cosmetic modifiers (match-and-rebind like with_refresh).
1683        assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1684            Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1685        assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1686            Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1687        // v2 defaults + modifiers.
1688        assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1689            Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1690                if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1691        let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1692            with_captions(video_player("v", "u", true, -1, Ev::Tap),
1693                vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1694            "p.jpg"), 9000), 1.5), 0.5));
1695        assert!(matches!(tuned,
1696            Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1697                if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1698        // playlist builder: url defaults to the first clip; urls/start_index carried; seek_index jumps.
1699        assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1700            Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1701        // modifiers are no-ops on non-Video widgets.
1702        assert!(matches!(with_pip(divider()), Widget::Divider));
1703        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1704        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1705        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1706        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1707        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1708        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1709        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1710        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1711
1712        match chip("Latte", true, Ev::Open(2)) {
1713            Widget::Chip { selected, on_press, .. } => {
1714                assert!(selected);
1715                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1716            }
1717            other => panic!("expected Chip, got {other:?}"),
1718        }
1719        match stepper(5, Ev::Tap, Ev::Open(1)) {
1720            Widget::Stepper { value, on_decrement, on_increment } => {
1721                assert_eq!(value, 5);
1722                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1723                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1724            }
1725            other => panic!("expected Stepper, got {other:?}"),
1726        }
1727        let t = tab("Home", true, Ev::Tap);
1728        assert_eq!(t.label, "Home");
1729        assert!(t.selected);
1730        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1731    }
1732
1733    // ---- ABI serialization round-trips (structural stability of the wire types) ----
1734
1735    #[test]
1736    fn widget_tree_round_trips_through_serde() {
1737        let tree = scaffold(
1738            "Home",
1739            true,
1740            vec![tab("A", true, Ev::Tap)],
1741            column(vec![
1742                title("Hi"),
1743                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1744                image("u", ImageShape::Rounded, ImageRatio::Wide),
1745                slider("s", 2, 5),
1746            ]),
1747        );
1748        let s = serde_json::to_string(&tree).unwrap();
1749        let back: Widget = serde_json::from_str(&s).unwrap();
1750        assert_eq!(s, serde_json::to_string(&back).unwrap());
1751    }
1752
1753    #[test]
1754    fn actions_and_input_values_round_trip() {
1755        let actions = vec![
1756            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1757            Action::Input { id: "n".into(), value: InputValue::Int(7) },
1758            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1759            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1760            Action::Restore { data: "blob".into() },
1761            Action::Start,
1762        ];
1763        for a in actions {
1764            let s = serde_json::to_string(&a).unwrap();
1765            let back: Action = serde_json::from_str(&s).unwrap();
1766            assert_eq!(s, serde_json::to_string(&back).unwrap());
1767        }
1768    }
1769
1770    // ---- MobilerShell: the fixed-ABI action dispatch ----
1771
1772    #[derive(Default)]
1773    struct CounterModel {
1774        count: i32,
1775        restored: String,
1776        started: bool,
1777        last_input: String,
1778    }
1779
1780    #[derive(serde::Serialize, serde::Deserialize)]
1781    enum CounterEv {
1782        Inc,
1783        Add(i32),
1784    }
1785
1786    #[derive(Default)]
1787    struct CounterApp;
1788
1789    impl MobilerApp for CounterApp {
1790        type Event = CounterEv;
1791        type Model = CounterModel;
1792        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1793            match ev {
1794                CounterEv::Inc => model.count += 1,
1795                CounterEv::Add(n) => model.count += n,
1796            }
1797        }
1798        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1799            if let InputValue::Text(t) = value {
1800                model.last_input = format!("{id}={t}");
1801            }
1802        }
1803        fn restore(&self, data: &str, model: &mut CounterModel) {
1804            model.restored = data.to_string();
1805        }
1806        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1807            model.started = true;
1808        }
1809        fn view(&self, model: &CounterModel) -> Widget {
1810            text(format!("{}", model.count))
1811        }
1812    }
1813
1814    #[test]
1815    fn shell_dispatches_fired_input_restore_and_start() {
1816        use crux_core::App as _;
1817        let shell = MobilerShell::<CounterApp>::default();
1818        let mut m = CounterModel::default();
1819
1820        // Fired with a valid token → the typed event reaches app.update.
1821        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1822        assert_eq!(m.count, 5);
1823        // Input → app.input.
1824        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1825        assert_eq!(m.last_input, "name=bob");
1826        // Restore → app.restore.
1827        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1828        assert_eq!(m.restored, "saved");
1829        // Start → app.init.
1830        let _ = shell.update(Action::Start, &mut m);
1831        assert!(m.started);
1832        // view renders the (mutated) model through the ABI.
1833        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1834    }
1835
1836    #[test]
1837    fn shell_ignores_a_malformed_fired_token() {
1838        use crux_core::App as _;
1839        let shell = MobilerShell::<CounterApp>::default();
1840        let mut m = CounterModel::default();
1841        // A token that doesn't deserialize to the app's event type is dropped — no
1842        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1843        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1844        assert_eq!(m.count, 0);
1845    }
1846
1847    // ---- transfer builders (cx.upload / cx.download) ----
1848
1849    #[test]
1850    fn upload_builder_emits_transfer_stream_call() {
1851        let mut cx = Cx::<Ev>::default();
1852        let key = cx
1853            .upload("https://h/put", "file:///tmp/a.enc")
1854            .bearer("tok")
1855            .header("Content-Type", "application/octet-stream")
1856            .start("up-1", |_ev| Ev::Tap);
1857
1858        assert_eq!(key, "up-1");
1859        assert_eq!(cx.streams.len(), 1);
1860        let (call, _) = &cx.streams[0];
1861        assert_eq!(call.key, "up-1");
1862        assert_eq!(call.plugin, "transfer");
1863        assert_eq!(call.op, "upload");
1864
1865        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1866        assert_eq!(v["url"], "https://h/put");
1867        assert_eq!(v["source"], "file:///tmp/a.enc");
1868        assert_eq!(v["method"], "PUT"); // default
1869        assert_eq!(v["headers"][0]["name"], "Authorization");
1870        assert_eq!(v["headers"][0]["value"], "Bearer tok");
1871        assert_eq!(v["headers"][1]["name"], "Content-Type");
1872    }
1873
1874    #[test]
1875    fn download_builder_uses_dest_and_no_default_method() {
1876        let mut cx = Cx::<Ev>::default();
1877        cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
1878        let (call, _) = &cx.streams[0];
1879        assert_eq!(call.op, "download");
1880        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1881        assert_eq!(v["dest"], "/data/att-9.enc");
1882        assert!(v.get("source").is_none());
1883    }
1884
1885    #[test]
1886    fn start_continuation_decodes_progress_and_done() {
1887        use crate::http::HttpOutcome;
1888
1889        // Local to this test (not module-scope `Ev`, which isn't `PartialEq`) so the
1890        // continuation's return type can be compared with `assert_eq!`.
1891        #[derive(Debug, PartialEq)]
1892        enum Got {
1893            Prog(u64),
1894            Done(u16),
1895            Bad,
1896        }
1897        #[derive(Debug, PartialEq)]
1898        struct GotEv(Got);
1899
1900        let mut cx = Cx::<GotEv>::default();
1901        cx.download("https://h/get", "/d").start("k", |ev| match ev {
1902            TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
1903            TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
1904                Some(s) => Got::Done(s),
1905                None => Got::Bad,
1906            }),
1907        });
1908        let (_, cont) = &cx.streams[0];
1909
1910        let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
1911        assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
1912
1913        let done = TransferEvent::Done {
1914            outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
1915            handle: Some("/d".into()),
1916        };
1917        assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
1918    }
1919}