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        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), US English (Sunday-first). `on_day(d)`
816/// builds the tap event for each day `d`; `selected` highlights a day. See [`calendar_in`] for a
817/// localized calendar with per-day markers.
818#[must_use]
819pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
820    calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
821}
822
823/// A localized inline month calendar: the title, weekday header and week start follow `locale`
824/// (e.g. [`Locale::SrLatn`] → "Septembar 2026", Monday-first `P U S Č P S N`). `markers` is one
825/// busy-level per day (`markers[d-1]`, `0..=3`, drawn as that many dots; `0` = none) — pass `&[]`
826/// for no markers. Shorter slices pad with `0`; levels above 3 clamp to 3.
827#[must_use]
828pub fn calendar_in<E: Serialize>(
829    locale: Locale,
830    year: u32,
831    month: u8,
832    selected: Option<u8>,
833    markers: &[u8],
834    on_day: impl Fn(u8) -> E,
835) -> Widget {
836    let n = days_in_month(year, month);
837    let start = locale.week_start().sun0();
838    let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
839    let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
840    let markers = if markers.is_empty() {
841        Vec::new()
842    } else {
843        (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
844    };
845    Widget::Calendar {
846        year,
847        month,
848        title: format::month_year(year, u32::from(month), locale),
849        weekday_labels,
850        leading_blanks,
851        selected,
852        on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
853        markers,
854    }
855}
856
857/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
858/// tappable. On web the actions render inline (no gesture).
859#[must_use]
860pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
861    Widget::SwipeAction {
862        child: Box::new(child),
863        actions: actions
864            .into_iter()
865            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
866            .collect(),
867    }
868}
869#[must_use]
870pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
871
872#[must_use]
873pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
874#[must_use]
875pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
876#[must_use]
877pub fn card(child: Widget, style: CardStyle) -> Widget {
878    Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
879}
880/// A tappable card carrying a typed press event.
881#[must_use]
882pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
883    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
884}
885/// Attach a long-press (press-and-hold) event to a `Card`. No-op on any other widget.
886/// Combines with `card` / `card_button` — a card can carry both a tap and a long-press.
887#[must_use]
888pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
889    match widget {
890        Widget::Card { child, style, on_press, .. } => Widget::Card {
891            child,
892            style,
893            on_press,
894            on_long_press: Some(tok(on_long_press)),
895        },
896        other => other,
897    }
898}
899/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
900/// darkened background and the rest render on top.
901#[must_use]
902pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
903    Widget::Box { children, align, scrim }
904}
905#[must_use]
906pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
907/// A two-pane master-detail layout ([`Widget::Split`]). Side-by-side on a wide screen (tablet /
908/// landscape); one pane on a phone — `primary` until `show_detail` (the app sets it on selection),
909/// then `detail` with a back chevron firing `on_back`. On wide, `detail` should show a placeholder
910/// until a row is selected.
911#[must_use]
912pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
913    Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
914}
915/// Horizontally scrolling row of children (a carousel / chip rail).
916#[must_use]
917pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
918/// A [`scroller`] whose trailing edge fades out — a hint that it scrolls.
919#[must_use]
920pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
921/// A circular avatar image.
922#[must_use]
923pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
924/// A circular avatar image with a colored status dot.
925#[must_use]
926pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
927    Widget::Avatar { source: source.into(), status: Some(status) }
928}
929/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
930#[must_use]
931pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
932/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
933#[must_use]
934pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
935    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
936}
937
938/// Extra options for [`button_with`]; `ButtonOpts::default()` is a plain [`button`].
939///
940/// ```
941/// use mobiler_core::{ButtonOpts, Icon, Tone};
942/// let danger_wide = ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide();
943/// assert!(danger_wide.wide);
944/// ```
945#[derive(Clone, Copy, Debug, PartialEq, Eq)]
946pub struct ButtonOpts {
947    pub tone: Tone,
948    pub icon: Option<Icon>,
949    pub wide: bool,
950}
951
952impl Default for ButtonOpts {
953    fn default() -> Self {
954        Self { tone: Tone::Neutral, icon: None, wide: false }
955    }
956}
957
958impl ButtonOpts {
959    /// Recolor the button (`Tone::Danger` for destructive actions).
960    #[must_use]
961    pub const fn tone(mut self, tone: Tone) -> Self {
962        self.tone = tone;
963        self
964    }
965    /// A leading icon.
966    #[must_use]
967    pub const fn icon(mut self, icon: Icon) -> Self {
968        self.icon = Some(icon);
969        self
970    }
971    /// Stretch to the available width (a screen's main action).
972    #[must_use]
973    pub const fn wide(mut self) -> Self {
974        self.wide = true;
975        self
976    }
977}
978
979#[must_use]
980pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
981    button_with(label, style, on_press, ButtonOpts::default())
982}
983
984/// A button with a [`ButtonOpts`] tone, leading icon, and/or full width.
985#[must_use]
986pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
987    Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
988}
989#[must_use]
990pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
991    Widget::IconButton { icon, on_press: tok(on_press) }
992}
993#[must_use]
994pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
995    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
996}
997#[must_use]
998pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
999    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1000}
1001/// A text field with full control over [`FieldKind`] and an optional inline
1002/// validation `error`. The kind-specific helpers below ([`secure_field`],
1003/// [`email_field`], …) wrap this for the common cases.
1004#[must_use]
1005pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1006    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1007}
1008/// A masked password field ([`FieldKind::Secure`]).
1009#[must_use]
1010pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1011    field(id, placeholder, value, FieldKind::Secure, None)
1012}
1013/// An email-keyboard field ([`FieldKind::Email`]).
1014#[must_use]
1015pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1016    field(id, placeholder, value, FieldKind::Email, None)
1017}
1018/// A whole-number keypad field ([`FieldKind::Number`]).
1019#[must_use]
1020pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1021    field(id, placeholder, value, FieldKind::Number, None)
1022}
1023/// A decimal keypad field ([`FieldKind::Decimal`]).
1024#[must_use]
1025pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1026    field(id, placeholder, value, FieldKind::Decimal, None)
1027}
1028/// A phone-keypad field ([`FieldKind::Phone`]).
1029#[must_use]
1030pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1031    field(id, placeholder, value, FieldKind::Phone, None)
1032}
1033/// A URL-keyboard field ([`FieldKind::Url`]).
1034#[must_use]
1035pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1036    field(id, placeholder, value, FieldKind::Url, None)
1037}
1038/// A growable multi-line text area ([`FieldKind::Multiline`]).
1039#[must_use]
1040pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1041    field(id, placeholder, value, FieldKind::Multiline, None)
1042}
1043/// Attach an inline validation message to a [`Widget::TextField`], marking it
1044/// invalid. No-op on any other widget.
1045#[must_use]
1046pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1047    match widget {
1048        Widget::TextField { id, placeholder, value, kind, .. } =>
1049            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1050        other => other,
1051    }
1052}
1053
1054/// Wrap `child` so a screen reader (VoiceOver / TalkBack) announces the subtree as ONE element named
1055/// `label` — gives an unlabeled `icon_button`/`image` a name, or groups a card's children into one
1056/// announced element. Add `with_a11y_hint` / `with_a11y_role` for the activation hint + control type.
1057#[must_use]
1058pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1059    Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1060}
1061/// Set the accessibility activation hint (e.g. "Opens your bookings"); wraps `widget` if it isn't an
1062/// [`a11y`] wrapper yet.
1063#[must_use]
1064pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1065    match widget {
1066        Widget::A11y { child, label, role, .. } =>
1067            Widget::A11y { child, label, hint: Some(hint.into()), role },
1068        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1069    }
1070}
1071/// Set the accessibility role / control type; wraps `widget` if it isn't an [`a11y`] wrapper yet.
1072#[must_use]
1073pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1074    match widget {
1075        Widget::A11y { child, label, hint, .. } =>
1076            Widget::A11y { child, label, hint, role: Some(role) },
1077        other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1078    }
1079}
1080/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
1081#[must_use]
1082pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1083    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1084}
1085/// One option in a [`segmented`] control, carrying a typed selection event.
1086#[must_use]
1087pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1088    Segment { label: label.into(), selected, on_select: tok(on_select) }
1089}
1090/// A single-choice segmented control (exclusive options in a pill).
1091#[must_use]
1092pub fn segmented(segments: Vec<Segment>) -> Widget {
1093    Widget::Segmented { segments }
1094}
1095#[must_use]
1096pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1097    Widget::Toggle { id: id.into(), label: label.into(), value }
1098}
1099#[must_use]
1100pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1101    Widget::Checkbox { id: id.into(), label: label.into(), value }
1102}
1103#[must_use]
1104pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1105    Widget::Slider { id: id.into(), value, max }
1106}
1107#[must_use]
1108pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1109    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1110}
1111
1112/// A bottom-nav tab carrying a typed selection event (label-only).
1113#[must_use]
1114pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1115    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1116}
1117
1118/// A bottom-nav tab with a leading icon (icon tab bar).
1119#[must_use]
1120pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1121    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1122}
1123
1124/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
1125/// theme-as-data (the shell themes the whole app from it).
1126#[must_use]
1127pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1128    let title = title.into();
1129    // route defaults to the title; root depth = 1.
1130    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 }
1131}
1132
1133/// Like [`scaffold`], but the top bar (and the system back button) navigate back
1134/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
1135/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
1136#[must_use]
1137pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1138    let title = title.into();
1139    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 }
1140}
1141
1142/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
1143/// serialization) and `depth` (stack depth) so the shell animates transitions,
1144/// and shows a back affordance (top-bar arrow + system back button) firing
1145/// `on_back` whenever the stack can pop.
1146#[must_use]
1147pub fn nav_scaffold<R, E>(
1148    title: impl Into<String>,
1149    dark_mode: bool,
1150    tabs: Vec<Tab>,
1151    body: Widget,
1152    nav: &Nav<R>,
1153    on_back: E,
1154) -> Widget
1155where
1156    R: Clone + Serialize,
1157    E: Serialize,
1158{
1159    Widget::Scaffold {
1160        title: title.into(),
1161        body: Box::new(body),
1162        tabs,
1163        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1164        dark_mode,
1165        theme: None,
1166        fab: None,
1167        sheet: None,
1168        on_refresh: None,
1169        refreshing: false,
1170        route: nav.route_key(),
1171        depth: nav.depth(),
1172    }
1173}
1174
1175/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
1176/// other widget. Lets an app brand its UI without new scaffold builder overloads:
1177/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
1178pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1179    match widget {
1180        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1181            title,
1182            body,
1183            tabs,
1184            back,
1185            dark_mode,
1186            theme: Some(theme),
1187            fab,
1188            sheet,
1189            on_refresh,
1190            refreshing,
1191            route,
1192            depth,
1193        },
1194        other => other,
1195    }
1196}
1197
1198/// Anchor a floating action button over a scaffold's body (the raised primary action).
1199/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
1200pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1201    match widget {
1202        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1203            title,
1204            body,
1205            tabs,
1206            back,
1207            dark_mode,
1208            theme,
1209            fab: Some(Fab { icon, on_press: tok(on_press) }),
1210            sheet,
1211            on_refresh,
1212            refreshing,
1213            route,
1214            depth,
1215        },
1216        other => other,
1217    }
1218}
1219
1220/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
1221/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
1222pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1223    match widget {
1224        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1225            title: t,
1226            body,
1227            tabs,
1228            back,
1229            dark_mode,
1230            theme,
1231            fab,
1232            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1233            on_refresh,
1234            refreshing,
1235            route,
1236            depth,
1237        },
1238        other => other,
1239    }
1240}
1241
1242/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
1243/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
1244/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
1245pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1246    match widget {
1247        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1248            title,
1249            body,
1250            tabs,
1251            back,
1252            dark_mode,
1253            theme,
1254            fab,
1255            sheet,
1256            on_refresh: Some(tok(on_refresh)),
1257            refreshing,
1258            route,
1259            depth,
1260        },
1261        // Pull-to-refresh on a LazyList's top — same API as on a Scaffold. Leaves the load-more
1262        // fields intact.
1263        Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1264            children,
1265            on_load_more,
1266            loading,
1267            has_more,
1268            on_refresh: Some(tok(on_refresh)),
1269            refreshing,
1270        },
1271        other => other,
1272    }
1273}
1274
1275/// A scrollable list for long/paged feeds that fires `on_load_more` when the user scrolls near the
1276/// end. The app owns the state: append to `children` on each load-more event, set `loading` true
1277/// while the page loads (the shell shows a spinner and won't re-fire), and `has_more=false` when
1278/// the feed is exhausted. Add pull-to-refresh at the top with [`with_refresh`]. Give it room — a
1279/// `LazyList` nested in a scrollable body needs a bounded height to scroll on its own.
1280#[must_use]
1281pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1282    Widget::LazyList {
1283        children,
1284        on_load_more: Some(tok(on_load_more)),
1285        loading,
1286        has_more,
1287        on_refresh: None,
1288        refreshing: false,
1289    }
1290}
1291
1292/// A scrollable list with no load-more and no refresh — a plain virtualized list of `children`.
1293#[must_use]
1294pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1295    Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300    use super::*;
1301    use serde::Serialize;
1302
1303    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1304    enum Route {
1305        Home,
1306        Detail(u32),
1307    }
1308
1309    #[derive(Serialize)]
1310    enum Ev {
1311        Tap,
1312        Open(u32),
1313    }
1314
1315    // ---- PluginResponse ----
1316
1317    #[test]
1318    fn plugin_response_carries_bytes_and_converts_text() {
1319        let r = PluginResponse::text(true, "hello");
1320        assert!(r.ok);
1321        assert_eq!(r.output, b"hello".to_vec());
1322        assert_eq!(r.as_text(), Some("hello"));
1323
1324        let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1325        assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1326    }
1327
1328    // ---- Nav ----
1329
1330    #[test]
1331    fn nav_push_pop_depth() {
1332        let mut nav = Nav::new(Route::Home);
1333        assert_eq!(nav.depth(), 1);
1334        assert!(!nav.can_go_back());
1335
1336        nav.push(Route::Detail(7));
1337        assert_eq!(nav.depth(), 2);
1338        assert!(nav.can_go_back());
1339        assert!(matches!(nav.current(), Route::Detail(7)));
1340
1341        nav.pop();
1342        assert_eq!(nav.depth(), 1);
1343        assert!(matches!(nav.current(), Route::Home));
1344
1345        nav.pop(); // no-op at the root
1346        assert_eq!(nav.depth(), 1);
1347    }
1348
1349    #[test]
1350    fn nav_reset_replaces_stack() {
1351        let mut nav = Nav::new(Route::Home);
1352        nav.push(Route::Detail(1));
1353        nav.push(Route::Detail(2));
1354        nav.reset(Route::Detail(9));
1355        assert_eq!(nav.depth(), 1);
1356        assert!(matches!(nav.current(), Route::Detail(9)));
1357    }
1358
1359    #[test]
1360    fn nav_route_key_is_serialization() {
1361        let nav = Nav::new(Route::Detail(3));
1362        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1363    }
1364
1365    // ---- builders ----
1366
1367    #[test]
1368    fn scaffold_sets_route_depth_and_no_back() {
1369        match scaffold("Home", false, vec![], text("x")) {
1370            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1371                assert_eq!(route, "Home");
1372                assert_eq!(depth, 1);
1373                assert!(back.is_none());
1374                assert!(!dark_mode);
1375            }
1376            other => panic!("expected Scaffold, got {other:?}"),
1377        }
1378    }
1379
1380    #[test]
1381    fn scaffold_back_is_depth_2_with_back() {
1382        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1383            Widget::Scaffold { depth, back, dark_mode, .. } => {
1384                assert_eq!(depth, 2);
1385                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1386                assert!(dark_mode);
1387            }
1388            other => panic!("expected Scaffold, got {other:?}"),
1389        }
1390    }
1391
1392    #[test]
1393    fn nav_scaffold_shows_back_only_when_poppable() {
1394        let mut nav = Nav::new(Route::Home);
1395        // at the root: no back, depth 1, route = serialized current route
1396        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1397            Widget::Scaffold { back, depth, route, .. } => {
1398                assert!(back.is_none());
1399                assert_eq!(depth, 1);
1400                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1401            }
1402            other => panic!("expected Scaffold, got {other:?}"),
1403        }
1404        // after a push: back present, depth 2
1405        nav.push(Route::Detail(2));
1406        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1407            Widget::Scaffold { back, depth, .. } => {
1408                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1409                assert_eq!(depth, 2);
1410            }
1411            other => panic!("expected Scaffold, got {other:?}"),
1412        }
1413    }
1414
1415    #[test]
1416    fn button_with_carries_tone_icon_and_width() {
1417        assert!(matches!(
1418            button("Go", ButtonStyle::Filled, Ev::Tap),
1419            Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1420        ));
1421        assert!(matches!(
1422            button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1423            Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1424        ));
1425    }
1426
1427    #[test]
1428    fn buttons_carry_serialized_event_tokens() {
1429        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1430            Widget::Button { label, on_press, .. } => {
1431                assert_eq!(label, "Go");
1432                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1433            }
1434            other => panic!("expected Button, got {other:?}"),
1435        }
1436        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1437            Widget::Card { on_press, .. } => {
1438                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1439            }
1440            other => panic!("expected Card, got {other:?}"),
1441        }
1442        // a plain card is not tappable
1443        match card(text("c"), CardStyle::Elevated) {
1444            Widget::Card { on_press, on_long_press, .. } => {
1445                assert!(on_press.is_none());
1446                assert!(on_long_press.is_none());
1447            }
1448            other => panic!("expected Card, got {other:?}"),
1449        }
1450        // with_long_press attaches a long-press, keeping any existing tap
1451        match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1452            Widget::Card { on_press, on_long_press, .. } => {
1453                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1454                assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1455            }
1456            other => panic!("expected Card, got {other:?}"),
1457        }
1458        // with_long_press on a non-Card is a no-op
1459        assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1460    }
1461
1462    // ---- Cx capabilities ----
1463
1464    #[test]
1465    fn cx_notify_and_save_enqueue_notifications() {
1466        let mut cx = Cx::<Ev>::default();
1467        cx.notify("toast", "show", "hi");
1468        cx.save("blob");
1469        assert_eq!(cx.notifications.len(), 2);
1470        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1471        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1472        assert!(cx.requests.is_empty());
1473    }
1474
1475    #[test]
1476    fn cx_http_helpers_build_requests() {
1477        let mut cx = Cx::<Ev>::default();
1478        cx.get("http://h/x", |_| Ev::Tap);
1479        cx.post("http://h/y", "hello", |_| Ev::Tap);
1480        cx.put("http://h/p", "putbody", |_| Ev::Tap);
1481        cx.patch("http://h/z", "patch", |_| Ev::Tap);
1482        cx.delete("http://h/d", |_| Ev::Tap);
1483
1484        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1485        assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1486        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1487
1488        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1489        assert_eq!(get_input["url"], "http://h/x");
1490        assert!(get_input["body"].is_null());
1491
1492        let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1493        assert_eq!(put_input["url"], "http://h/p");
1494        assert_eq!(put_input["body"], "putbody");
1495    }
1496
1497    #[test]
1498    fn request_builder_emits_headers_in_order() {
1499        let mut cx = Cx::<Ev>::default();
1500        cx.request("PUT", "http://h/access-key")
1501            .bearer("tok123")
1502            .header("X-Trace-Id", "abc")
1503            .body("{}")
1504            .send(|_| Ev::Tap);
1505
1506        assert_eq!(cx.requests.len(), 1);
1507        let (call, _) = &cx.requests[0];
1508        assert_eq!(call.plugin, "http");
1509        assert_eq!(call.op, "PUT");
1510
1511        let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1512        assert_eq!(input["url"], "http://h/access-key");
1513        assert_eq!(input["body"], "{}");
1514        assert_eq!(input["headers"][0]["name"], "Authorization");
1515        assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1516        assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1517        assert_eq!(input["headers"][1]["value"], "abc");
1518    }
1519
1520    #[test]
1521    fn helpers_emit_no_headers_field_content() {
1522        let mut cx = Cx::<Ev>::default();
1523        cx.get("http://h/x", |_| Ev::Tap);
1524        let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1525        assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1526    }
1527
1528    #[test]
1529    fn continuation_receives_decoded_outcome() {
1530        #[derive(Debug, PartialEq)]
1531        enum Got { Conflict, Offline, Other }
1532
1533        let classify = |r: PluginResponse| -> Got {
1534            match HttpOutcome::decode(&r.output).unwrap() {
1535                HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1536                HttpOutcome::TransportError { .. } => Got::Offline,
1537                _ => Got::Other,
1538            }
1539        };
1540
1541        let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1542        assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1543
1544        let offline = HttpOutcome::TransportError { message: "refused".into() };
1545        assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1546    }
1547
1548    #[test]
1549    fn decode_failure_in_continuation_surfaces_as_transport_error() {
1550        // Drives the actual `send()` callback path (not just `HttpOutcome::decode`
1551        // directly): stores a continuation via `cx.request(...).send(...)`, then
1552        // invokes it with a `PluginResponse` whose `output` is malformed bytes, the
1553        // way the shell would if it returned something undecodable.
1554        let mut cx = Cx::<Ev>::default();
1555
1556        cx.request("GET", "http://h/x").send(|outcome| {
1557            match outcome {
1558                HttpOutcome::TransportError { message } => {
1559                    assert!(
1560                        message.contains("malformed http response"),
1561                        "unexpected message: {message}"
1562                    );
1563                }
1564                HttpOutcome::Response { .. } => {
1565                    panic!("garbage bytes must not decode as a Response")
1566                }
1567            }
1568            Ev::Tap
1569        });
1570
1571        assert_eq!(cx.requests.len(), 1);
1572        let (_, continuation) = cx.requests.remove(0);
1573        // Must not panic: a malformed `output` has to surface as `TransportError`,
1574        // asserted inside the callback above.
1575        continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1576    }
1577
1578    #[test]
1579    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1580        let mut cx = Cx::<Ev>::default();
1581        cx.pick_photo(|_| Ev::Tap);
1582        cx.capture_photo(|_| Ev::Tap);
1583        assert_eq!(cx.requests.len(), 2);
1584        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1585        // carry empty input (the shell needs no parameters to launch picker/camera).
1586        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", ""));
1587        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", ""));
1588    }
1589
1590    #[test]
1591    fn cx_capture_photo_routes_success_and_cancel() {
1592        // Happy path: ok=true delivers the URI to the success branch.
1593        let mut cx = Cx::<Ev>::default();
1594        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1595        let (_, then) = cx.requests.pop().unwrap();
1596        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1597
1598        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1599        let mut cx = Cx::<Ev>::default();
1600        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1601        let (_, then) = cx.requests.pop().unwrap();
1602        assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1603    }
1604
1605    #[test]
1606    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1607        let mut cx = Cx::<Ev>::default();
1608        cx.copy("c");
1609        cx.share("s");
1610        cx.open_url("u");
1611        cx.toast("t");
1612        cx.haptic("heavy");
1613        let got: Vec<(&str, &str, &str)> = cx
1614            .notifications
1615            .iter()
1616            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1617            .collect();
1618        assert_eq!(
1619            got,
1620            vec![
1621                ("clipboard", "copy", "c"),
1622                ("share", "text", "s"),
1623                ("browser", "open", "u"),
1624                ("toast", "show", "t"),
1625                ("haptics", "heavy", ""), // haptic style is the op, input empty
1626            ]
1627        );
1628        assert!(cx.requests.is_empty());
1629    }
1630
1631    #[test]
1632    fn cx_device_model_is_a_request_not_a_notification() {
1633        let mut cx = Cx::<Ev>::default();
1634        cx.device_model(|_| Ev::Tap);
1635        assert!(cx.notifications.is_empty());
1636        assert_eq!(cx.requests.len(), 1);
1637        let (call, _) = &cx.requests[0];
1638        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1639    }
1640
1641    #[test]
1642    fn cx_device_locale_requests_the_device_locale_op() {
1643        let mut cx = Cx::<Ev>::default();
1644        cx.device_locale(|_| Ev::Tap);
1645        assert!(cx.notifications.is_empty());
1646        assert_eq!(cx.requests.len(), 1);
1647        let (call, _) = &cx.requests[0];
1648        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1649    }
1650
1651    #[test]
1652    fn cx_now_requests_the_datetime_now_op() {
1653        let mut cx = Cx::<Ev>::default();
1654        cx.now(|_| Ev::Tap);
1655        assert_eq!(cx.requests.len(), 1);
1656        let (call, _) = &cx.requests[0];
1657        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1658    }
1659
1660    #[test]
1661    fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1662        let mut cx = Cx::<Ev>::default();
1663        cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1664        // It's a stream, not a one-shot request or a notification.
1665        assert!(cx.notifications.is_empty());
1666        assert!(cx.requests.is_empty());
1667        assert_eq!(cx.streams.len(), 1);
1668        let (call, on_event) = &cx.streams[0];
1669        assert_eq!(
1670            (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1671            ("ws", "websocket", "stream", "wss://h/x")
1672        );
1673        // The continuation is `Fn` — it can map MANY events, not just one.
1674        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1675        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1676        assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1677    }
1678
1679    #[test]
1680    fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1681        let mut cx = Cx::<Ev>::default();
1682        cx.unsubscribe("ws");
1683        assert!(cx.streams.is_empty());
1684        assert_eq!(cx.notifications.len(), 1);
1685        // The shell tears down the native source registered under this key.
1686        assert_eq!(
1687            cx.notifications[0],
1688            PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1689        );
1690    }
1691
1692    #[test]
1693    fn cx_confirm_serializes_title_message_and_routes_ok() {
1694        let mut cx = Cx::<Ev>::default();
1695        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1696        let (call, then) = cx.requests.pop().unwrap();
1697        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1698        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1699        assert_eq!(v["title"], "Delete?");
1700        assert_eq!(v["message"], "This cannot be undone.");
1701        // ok=true → confirmed branch; ok=false would take the else branch.
1702        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1703    }
1704
1705    // ---- widget builders ----
1706
1707    #[test]
1708    fn text_builders_carry_their_style() {
1709        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1710        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1711        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1712        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1713        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1714    }
1715
1716    #[test]
1717    fn layout_and_content_builders_produce_their_variants() {
1718        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1719        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1720        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1721        assert!(matches!(divider(), Widget::Divider));
1722        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1723        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1724        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1725        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)));
1726        let rc = with_bracket(
1727            region_chart(
1728                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1729                vec![ChartTick::new(3.0, "3 Mt.")],
1730                65.0, 80.0,
1731                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1732                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1733            ),
1734            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1735        );
1736        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1737        // June 2026 has 30 days and starts on a Monday; US English is Sunday-first → 1 blank.
1738        assert!(matches!(
1739            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1740            Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
1741                if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
1742        ));
1743        assert!(matches!(
1744            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1745            Widget::SwipeAction { actions, .. } if actions.len() == 1
1746        ));
1747        // lazy_list carries the load-more token + app-owned flags; no refresh by default.
1748        assert!(matches!(
1749            lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1750            Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1751                if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1752        ));
1753        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1754        // with_refresh adds pull-to-refresh to a LazyList without disturbing the load-more fields.
1755        assert!(matches!(
1756            with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1757            Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1758                if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1759        ));
1760        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1761        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1762        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1763        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1764        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1765        // a scrim z-stack keeps its align + scrim flag
1766        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1767        // split: children boxed, show_detail + on_back carried.
1768        assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1769            Widget::Split { show_detail: true, on_back: Some(_), .. }));
1770    }
1771
1772    #[test]
1773    fn input_builders_carry_ids_values_and_event_tokens() {
1774        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1775        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1776        assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1777        // video_player defaults + the cosmetic modifiers (match-and-rebind like with_refresh).
1778        assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1779            Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1780        assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1781            Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1782        // v2 defaults + modifiers.
1783        assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1784            Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1785                if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1786        let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1787            with_captions(video_player("v", "u", true, -1, Ev::Tap),
1788                vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1789            "p.jpg"), 9000), 1.5), 0.5));
1790        assert!(matches!(tuned,
1791            Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1792                if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1793        // playlist builder: url defaults to the first clip; urls/start_index carried; seek_index jumps.
1794        assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1795            Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1796        // modifiers are no-ops on non-Video widgets.
1797        assert!(matches!(with_pip(divider()), Widget::Divider));
1798        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1799        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1800        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1801        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1802        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1803        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1804        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1805        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1806
1807        match chip("Latte", true, Ev::Open(2)) {
1808            Widget::Chip { selected, on_press, .. } => {
1809                assert!(selected);
1810                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1811            }
1812            other => panic!("expected Chip, got {other:?}"),
1813        }
1814        match stepper(5, Ev::Tap, Ev::Open(1)) {
1815            Widget::Stepper { value, on_decrement, on_increment } => {
1816                assert_eq!(value, 5);
1817                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1818                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1819            }
1820            other => panic!("expected Stepper, got {other:?}"),
1821        }
1822        let t = tab("Home", true, Ev::Tap);
1823        assert_eq!(t.label, "Home");
1824        assert!(t.selected);
1825        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1826    }
1827
1828    // ---- ABI serialization round-trips (structural stability of the wire types) ----
1829
1830    #[test]
1831    fn widget_tree_round_trips_through_serde() {
1832        let tree = scaffold(
1833            "Home",
1834            true,
1835            vec![tab("A", true, Ev::Tap)],
1836            column(vec![
1837                title("Hi"),
1838                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1839                image("u", ImageShape::Rounded, ImageRatio::Wide),
1840                slider("s", 2, 5),
1841            ]),
1842        );
1843        let s = serde_json::to_string(&tree).unwrap();
1844        let back: Widget = serde_json::from_str(&s).unwrap();
1845        assert_eq!(s, serde_json::to_string(&back).unwrap());
1846    }
1847
1848    #[test]
1849    fn actions_and_input_values_round_trip() {
1850        let actions = vec![
1851            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1852            Action::Input { id: "n".into(), value: InputValue::Int(7) },
1853            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1854            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1855            Action::Restore { data: "blob".into() },
1856            Action::Start,
1857        ];
1858        for a in actions {
1859            let s = serde_json::to_string(&a).unwrap();
1860            let back: Action = serde_json::from_str(&s).unwrap();
1861            assert_eq!(s, serde_json::to_string(&back).unwrap());
1862        }
1863    }
1864
1865    // ---- MobilerShell: the fixed-ABI action dispatch ----
1866
1867    #[derive(Default)]
1868    struct CounterModel {
1869        count: i32,
1870        restored: String,
1871        started: bool,
1872        last_input: String,
1873    }
1874
1875    #[derive(serde::Serialize, serde::Deserialize)]
1876    enum CounterEv {
1877        Inc,
1878        Add(i32),
1879    }
1880
1881    #[derive(Default)]
1882    struct CounterApp;
1883
1884    impl MobilerApp for CounterApp {
1885        type Event = CounterEv;
1886        type Model = CounterModel;
1887        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1888            match ev {
1889                CounterEv::Inc => model.count += 1,
1890                CounterEv::Add(n) => model.count += n,
1891            }
1892        }
1893        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1894            if let InputValue::Text(t) = value {
1895                model.last_input = format!("{id}={t}");
1896            }
1897        }
1898        fn restore(&self, data: &str, model: &mut CounterModel) {
1899            model.restored = data.to_string();
1900        }
1901        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1902            model.started = true;
1903        }
1904        fn view(&self, model: &CounterModel) -> Widget {
1905            text(format!("{}", model.count))
1906        }
1907    }
1908
1909    #[test]
1910    fn shell_dispatches_fired_input_restore_and_start() {
1911        use crux_core::App as _;
1912        let shell = MobilerShell::<CounterApp>::default();
1913        let mut m = CounterModel::default();
1914
1915        // Fired with a valid token → the typed event reaches app.update.
1916        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1917        assert_eq!(m.count, 5);
1918        // Input → app.input.
1919        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1920        assert_eq!(m.last_input, "name=bob");
1921        // Restore → app.restore.
1922        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1923        assert_eq!(m.restored, "saved");
1924        // Start → app.init.
1925        let _ = shell.update(Action::Start, &mut m);
1926        assert!(m.started);
1927        // view renders the (mutated) model through the ABI.
1928        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1929    }
1930
1931    #[test]
1932    fn shell_ignores_a_malformed_fired_token() {
1933        use crux_core::App as _;
1934        let shell = MobilerShell::<CounterApp>::default();
1935        let mut m = CounterModel::default();
1936        // A token that doesn't deserialize to the app's event type is dropped — no
1937        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1938        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1939        assert_eq!(m.count, 0);
1940    }
1941
1942    // ---- transfer builders (cx.upload / cx.download) ----
1943
1944    #[test]
1945    fn upload_builder_emits_transfer_stream_call() {
1946        let mut cx = Cx::<Ev>::default();
1947        let key = cx
1948            .upload("https://h/put", "file:///tmp/a.enc")
1949            .bearer("tok")
1950            .header("Content-Type", "application/octet-stream")
1951            .start("up-1", |_ev| Ev::Tap);
1952
1953        assert_eq!(key, "up-1");
1954        assert_eq!(cx.streams.len(), 1);
1955        let (call, _) = &cx.streams[0];
1956        assert_eq!(call.key, "up-1");
1957        assert_eq!(call.plugin, "transfer");
1958        assert_eq!(call.op, "upload");
1959
1960        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1961        assert_eq!(v["url"], "https://h/put");
1962        assert_eq!(v["source"], "file:///tmp/a.enc");
1963        assert_eq!(v["method"], "PUT"); // default
1964        assert_eq!(v["headers"][0]["name"], "Authorization");
1965        assert_eq!(v["headers"][0]["value"], "Bearer tok");
1966        assert_eq!(v["headers"][1]["name"], "Content-Type");
1967    }
1968
1969    #[test]
1970    fn download_builder_uses_dest_and_no_default_method() {
1971        let mut cx = Cx::<Ev>::default();
1972        cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
1973        let (call, _) = &cx.streams[0];
1974        assert_eq!(call.op, "download");
1975        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1976        assert_eq!(v["dest"], "/data/att-9.enc");
1977        assert!(v.get("source").is_none());
1978    }
1979
1980    #[test]
1981    fn start_continuation_decodes_progress_and_done() {
1982        use crate::http::HttpOutcome;
1983
1984        // Local to this test (not module-scope `Ev`, which isn't `PartialEq`) so the
1985        // continuation's return type can be compared with `assert_eq!`.
1986        #[derive(Debug, PartialEq)]
1987        enum Got {
1988            Prog(u64),
1989            Done(u16),
1990            Bad,
1991        }
1992        #[derive(Debug, PartialEq)]
1993        struct GotEv(Got);
1994
1995        let mut cx = Cx::<GotEv>::default();
1996        cx.download("https://h/get", "/d").start("k", |ev| match ev {
1997            TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
1998            TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
1999                Some(s) => Got::Done(s),
2000                None => Got::Bad,
2001            }),
2002        });
2003        let (_, cont) = &cx.streams[0];
2004
2005        let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2006        assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2007
2008        let done = TransferEvent::Done {
2009            outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2010            handle: Some("/d".into()),
2011        };
2012        assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2013    }
2014
2015    #[test]
2016    fn calendar_in_localizes_layout_and_clamps_markers() {
2017        // 1 September 2026 is a Tuesday; Serbian weeks start Monday → 1 leading blank, "U" 2nd column.
2018        let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2019        let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2020        assert_eq!(title, "Septembar 2026");
2021        assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2022        assert_eq!(leading_blanks, 1);
2023        assert_eq!(on_day.len(), 30);
2024        assert_eq!(markers.len(), 30, "padded to one level per day");
2025        assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2026        // Same month, US English (Sunday-first) → 2 leading blanks.
2027        assert!(matches!(
2028            calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2029            Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2030        ));
2031    }
2032
2033    #[test]
2034    fn scroller_hint_is_opt_in() {
2035        assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2036        assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2037    }
2038}