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