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 format;
11pub use format::{Currency, Locale};
12
13use crux_core::{
14    App, Command,
15    capability::Operation,
16    macros::effect,
17    render::{RenderOperation, render},
18};
19use facet::Facet;
20use serde::{Deserialize, Serialize, de::DeserializeOwned};
21
22pub use mobiler_ui::{
23    Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
24    ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
25    ImageRatio, ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
26    TextStyle, Theme, Tone, Widget,
27};
28
29// ============================ capabilities ============================
30
31/// Built-in capabilities the generic shell fulfils.
32#[effect(facet_typegen)]
33#[derive(Debug)]
34pub enum Effect {
35    Render(RenderOperation),
36    /// Fire-and-forget plugin call (shell does not resolve).
37    PluginNotify(PluginNotify),
38    /// Request/response plugin call (shell resolves with a [`PluginResponse`]).
39    Plugin(PluginCall),
40    /// Long-lived subscription: the shell starts a native source and resolves
41    /// **repeatedly** (a [`PluginResponse`] per event) until it's torn down. Powers
42    /// [`Cx::subscribe`]. Stop it with [`Cx::unsubscribe`] (a `stream`/`unsubscribe`
43    /// notify keyed by [`PluginStreamCall::key`]).
44    PluginStream(PluginStreamCall),
45}
46
47#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct PluginNotify {
49    pub plugin: String,
50    pub op: String,
51    pub input: String,
52}
53impl Operation for PluginNotify {
54    type Output = ();
55}
56
57#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
58pub struct PluginCall {
59    pub plugin: String,
60    pub op: String,
61    pub input: String,
62}
63impl Operation for PluginCall {
64    type Output = PluginResponse;
65}
66
67/// A streaming plugin subscription (powers [`Effect::PluginStream`]). Like
68/// [`PluginCall`] but carries a caller-chosen `key` so the subscription can be torn
69/// down ([`Cx::unsubscribe`]) — the shell registers the native source under `key`.
70#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
71pub struct PluginStreamCall {
72    pub key: String,
73    pub plugin: String,
74    pub op: String,
75    pub input: String,
76}
77impl Operation for PluginStreamCall {
78    type Output = PluginResponse;
79}
80
81#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginResponse {
83    pub ok: bool,
84    pub output: String,
85}
86
87type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
88/// A streaming continuation — fires once **per event** (so `Fn`, not `FnOnce`).
89type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
90
91/// Effects an app requests during `update`, generic over the app event type so
92/// continuations stay fully typed.
93pub struct Cx<E> {
94    notifications: Vec<PluginNotify>,
95    requests: Vec<(PluginCall, Continuation<E>)>,
96    streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
97}
98
99impl<E> Default for Cx<E> {
100    fn default() -> Self {
101        Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
102    }
103}
104
105impl<E> Cx<E> {
106    /// Fire-and-forget call to a native plugin.
107    pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
108        self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
109    }
110
111    /// Request/response call: when the plugin replies, `then(response)` produces
112    /// the typed event delivered back to your `update`.
113    pub fn plugin(
114        &mut self,
115        plugin: impl Into<String>,
116        op: impl Into<String>,
117        input: impl Into<String>,
118        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
119    ) {
120        self.requests
121            .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
122    }
123
124    /// Subscribe to a streaming plugin: the shell starts a native source and delivers
125    /// **every** event it produces to `on_event` (which fires repeatedly, once per
126    /// event), each producing a typed event into your `update`. `key` is a
127    /// caller-chosen id for this subscription — pass the same `key` to
128    /// [`unsubscribe`](Self::unsubscribe) to stop it. Call `subscribe` **once** per
129    /// key (e.g. in [`init`](MobilerApp::init) or on a connect event); calling it
130    /// again with a live key starts a second source.
131    pub fn subscribe(
132        &mut self,
133        key: impl Into<String>,
134        plugin: impl Into<String>,
135        op: impl Into<String>,
136        input: impl Into<String>,
137        on_event: impl Fn(PluginResponse) -> E + Send + 'static,
138    ) {
139        self.streams.push((
140            PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
141            Box::new(on_event),
142        ));
143    }
144
145    /// Stop the streaming subscription started under `key` by [`subscribe`](Self::subscribe).
146    /// The shell tears down the native source registered under `key`, so it stops
147    /// producing events. No-op if `key` isn't subscribed.
148    pub fn unsubscribe(&mut self, key: impl Into<String>) {
149        self.notify("stream", "unsubscribe", key);
150    }
151
152    /// Persist `data` (handed back to [`MobilerApp::restore`] on next startup).
153    pub fn save(&mut self, data: impl Into<String>) {
154        self.notify("storage", "save", data);
155    }
156
157    /// Copy `text` to the system clipboard (built-in `clipboard` capability).
158    pub fn copy(&mut self, text: impl Into<String>) {
159        self.notify("clipboard", "copy", text);
160    }
161
162    /// Open the system share sheet with `text` (built-in `share` capability).
163    pub fn share(&mut self, text: impl Into<String>) {
164        self.notify("share", "text", text);
165    }
166
167    /// Open `url` in the platform browser / default handler (built-in `browser`
168    /// capability). Fire-and-forget: the app leaves the foreground.
169    pub fn open_url(&mut self, url: impl Into<String>) {
170        self.notify("browser", "open", url);
171    }
172
173    /// Show a transient toast / snackbar with `text` (built-in `toast` capability).
174    pub fn toast(&mut self, text: impl Into<String>) {
175        self.notify("toast", "show", text);
176    }
177
178    /// Fire a haptic tap (built-in `haptics` capability). `style` is `"light"`,
179    /// `"medium"`, or `"heavy"`; unknown styles fall back to medium.
180    pub fn haptic(&mut self, style: impl Into<String>) {
181        self.notify("haptics", style, "");
182    }
183
184    /// Perform an HTTP request via the shell's built-in `http` capability. When it
185    /// completes, `then(response)` produces the typed event delivered back to
186    /// `update` — `response.output` is the body, `response.ok` is success (2xx).
187    /// Rides the request/response plugin mechanism, so it resolves asynchronously.
188    pub fn http(
189        &mut self,
190        method: impl Into<String>,
191        url: impl Into<String>,
192        body: Option<String>,
193        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
194    ) {
195        #[derive(Serialize)]
196        struct HttpReq {
197            url: String,
198            body: Option<String>,
199        }
200        let input = serde_json::to_string(&HttpReq { url: url.into(), body })
201            .expect("serialize http request");
202        self.plugin("http", method, input, then);
203    }
204
205    /// `GET url`, delivering the response to `then`.
206    pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
207        self.http("GET", url, None, then);
208    }
209    /// `POST url` with a JSON `body`, delivering the response to `then`.
210    pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
211        self.http("POST", url, Some(body.into()), then);
212    }
213    /// `PATCH url` with a JSON `body`, delivering the response to `then`.
214    pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
215        self.http("PATCH", url, Some(body.into()), then);
216    }
217    /// `DELETE url`, delivering the response to `then`.
218    pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
219        self.http("DELETE", url, None, then);
220    }
221
222    /// Query the device model/name via the built-in `device` capability; the result
223    /// (`response.output`, e.g. "Google Pixel 7" / "Apple iPhone (iOS 18.0)") is
224    /// delivered to `then`.
225    pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
226        self.plugin("device", "model", "", then);
227    }
228
229    /// Query the device's preferred locale as a BCP-47 language tag (e.g. `"de-CH"`, `"en-US"`)
230    /// via the built-in `device` capability; `then` receives it in `response.output`. Pair with
231    /// [`Locale::from_tag`](crate::format::Locale::from_tag) to choose the app's language /
232    /// formatting locale at startup. Works on iOS, Android, and web.
233    pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
234        self.plugin("device", "locale", "", then);
235    }
236
237    /// Let the user pick an image (built-in `photo` capability — the system photo
238    /// picker, no permission required). `then` receives the result: on success
239    /// `response.ok` is `true` and `response.output` is a local image URI you can
240    /// hand straight to the `image(...)` widget; on cancel, `ok` is `false`.
241    pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
242        self.plugin("photo", "pick", "", then);
243    }
244
245    /// Capture a photo with the device camera (built-in `camera` capability — launches
246    /// the system camera). `then` receives the result: on success `response.ok` is
247    /// `true` and `response.output` is a local image URI you can hand straight to the
248    /// `image(...)` widget; on cancel, `ok` is `false`. iOS requires an
249    /// `NSCameraUsageDescription` (the template ships one, opt-in); Android captures via
250    /// the system camera app, so no extra runtime permission is needed.
251    pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
252        self.plugin("camera", "capture", "", then);
253    }
254
255    /// Ask the user to confirm via a native dialog (built-in `dialog` capability).
256    /// `then` receives the choice: `response.ok` is `true` if confirmed, `false` if
257    /// cancelled/dismissed. Resolves asynchronously (the user replies whenever).
258    pub fn confirm(
259        &mut self,
260        title: impl Into<String>,
261        message: impl Into<String>,
262        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
263    ) {
264        #[derive(Serialize)]
265        struct Confirm {
266            title: String,
267            message: String,
268        }
269        let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
270            .expect("serialize confirm");
271        self.plugin("dialog", "confirm", input, then);
272    }
273
274    /// Let the user pick a date via the native date picker (built-in `datetime`
275    /// capability). On success `response.ok` is `true` and `response.output` is the
276    /// chosen date as an ISO `YYYY-MM-DD` string; on cancel/dismiss, `ok` is `false`.
277    /// Resolves asynchronously (the user replies whenever).
278    pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
279        self.plugin("datetime", "date", "", then);
280    }
281
282    /// Let the user pick a time via the native time picker (built-in `datetime`
283    /// capability). On success `response.ok` is `true` and `response.output` is the
284    /// chosen time as a 24-hour `HH:MM` string; on cancel/dismiss, `ok` is `false`.
285    /// Resolves asynchronously (the user replies whenever).
286    pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
287        self.plugin("datetime", "time", "", then);
288    }
289}
290
291// ============================ the app trait ============================
292
293/// What a Mobiler app implements. Write typed domain events; Mobiler serializes
294/// them into opaque tokens behind the scenes.
295pub trait MobilerApp: Default {
296    type Event: Serialize + DeserializeOwned + Send + 'static;
297    type Model: Default;
298
299    fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
300
301    fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
302        let _ = (id, value, model, cx);
303    }
304
305    /// Restore persisted state on startup. `data` is whatever you last passed to
306    /// `cx.save` (or empty if nothing was saved). Default: ignore.
307    fn restore(&self, data: &str, model: &mut Self::Model) {
308        let _ = (data, model);
309    }
310
311    /// Run once on startup, after [`restore`](Self::restore). The place to kick
312    /// off initial effects — e.g. fetch data with `cx.get`. Default: nothing.
313    fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
314        let _ = (model, cx);
315    }
316
317    fn view(&self, model: &Self::Model) -> Widget;
318}
319
320/// Crux adapter: turns a [`MobilerApp`] into an app speaking the fixed ABI.
321pub struct MobilerShell<A>(PhantomData<fn() -> A>);
322
323impl<A> Default for MobilerShell<A> {
324    fn default() -> Self {
325        Self(PhantomData)
326    }
327}
328
329impl<A: MobilerApp> App for MobilerShell<A> {
330    type Event = Action;
331    type Model = A::Model;
332    type ViewModel = Widget;
333    type Effect = Effect;
334
335    fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
336        let app = A::default();
337        let mut cx = Cx::<A::Event>::default();
338        match action {
339            Action::Fired { token } => {
340                if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
341                    app.update(event, model, &mut cx);
342                }
343            }
344            Action::Input { id, value } => app.input(&id, value, model, &mut cx),
345            Action::Restore { data } => app.restore(&data, model),
346            Action::Start => app.init(model, &mut cx),
347        }
348        let mut commands: Vec<Command<Effect, Action>> = Vec::new();
349        for op in cx.notifications {
350            commands.push(Command::notify_shell(op).build());
351        }
352        for (op, then) in cx.requests {
353            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
354                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
355            }));
356        }
357        for (op, then) in cx.streams {
358            // A long-lived shell stream: `then_send` fires `then` once per emitted
359            // event (it's `Fn`), each re-entering `update` as a `Fired` action.
360            commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
361                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
362            }));
363        }
364        commands.push(render());
365        Command::all(commands)
366    }
367
368    fn view(&self, model: &Self::Model) -> Widget {
369        A::default().view(model)
370    }
371}
372
373// ============================ navigation ============================
374
375/// A navigation stack the app holds in its `Model`. The **core owns the stack**
376/// (single source of truth); the framework reads its `route`/`depth` to drive
377/// the shell's push/pop transitions and back button.
378///
379/// `R` is your screen-route type (typically a small enum). Hold it in the model,
380/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
381/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
382/// `pop` so the back affordance works.
383///
384/// ```ignore
385/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
386/// // model.nav: Nav<Route> = Nav::new(Route::List);
387/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
388/// //         Msg::Back      => model.nav.pop(),
389/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
390/// ```
391#[derive(Clone, Debug)]
392pub struct Nav<R> {
393    stack: Vec<R>,
394}
395
396impl<R: Clone + Serialize> Nav<R> {
397    /// A stack containing a single root route.
398    #[must_use]
399    pub fn new(root: R) -> Self {
400        Self { stack: vec![root] }
401    }
402    /// Push a new screen onto the stack.
403    pub fn push(&mut self, route: R) {
404        self.stack.push(route);
405    }
406    /// Pop the top screen (no-op at the root).
407    pub fn pop(&mut self) {
408        if self.stack.len() > 1 {
409            self.stack.pop();
410        }
411    }
412    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
413    pub fn reset(&mut self, root: R) {
414        self.stack = vec![root];
415    }
416    /// The current (top) route — what `view` should render.
417    #[must_use]
418    pub fn current(&self) -> &R {
419        self.stack.last().expect("nav stack is never empty")
420    }
421    /// Stack depth (root = 1).
422    #[must_use]
423    pub fn depth(&self) -> u32 {
424        self.stack.len() as u32
425    }
426    /// Whether there is a screen to pop back to.
427    #[must_use]
428    pub fn can_go_back(&self) -> bool {
429        self.stack.len() > 1
430    }
431    /// Stable identity of the current route (its serialization), used by the shell
432    /// to decide when to animate a transition.
433    fn route_key(&self) -> String {
434        serde_json::to_string(self.current()).expect("serialize route")
435    }
436}
437
438// ============================ widget builders ============================
439// Action-carrying builders take a TYPED event and serialize it into a token.
440
441fn tok<E: Serialize>(event: E) -> String {
442    serde_json::to_string(&event).expect("serialize event")
443}
444
445#[must_use]
446pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
447    Widget::Text { content: content.into(), style }
448}
449#[must_use]
450pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
451#[must_use]
452pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
453#[must_use]
454pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
455#[must_use]
456pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
457#[must_use]
458pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
459
460#[must_use]
461pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
462    Widget::Image { source: source.into(), shape, ratio }
463}
464#[must_use]
465pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
466    Widget::Badge { label: label.into(), tone }
467}
468/// A small colored identity dot.
469#[must_use]
470pub fn color_dot(color: ProjectColor) -> Widget {
471    Widget::ColorDot { color }
472}
473#[must_use]
474pub fn divider() -> Widget { Widget::Divider }
475/// A progress bar (`Some(0.0..=1.0)`) or an indeterminate spinner (`None`).
476#[must_use]
477pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
478/// A shimmer placeholder shown while content loads.
479#[must_use]
480pub fn skeleton() -> Widget { Widget::Skeleton }
481/// An in-app PDF viewer for the document at `url` (remote https URL or local file URI) — rendered
482/// natively per platform (PDFKit / `PdfRenderer` / `<iframe>`). The app just supplies the URL, e.g.
483/// a backend-generated report. Give it room (place in a sized container or a scroller).
484#[must_use]
485pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
486/// A single unnamed series wrapping `values` — the back-compat shape for `bar_chart`/`line_chart`.
487fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
488    vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
489}
490
491/// A bar chart of `values` (normalized to the max), with optional per-value `labels`.
492/// Single-series, no axis or legend — for richer charts use [`chart`].
493#[must_use]
494pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
495    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
496}
497/// A line chart of `values` (normalized to the max), with optional per-value `labels`.
498/// Single-series, no axis or legend — for richer charts use [`chart`].
499#[must_use]
500pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
501    Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
502}
503/// A multi-series chart in the given `style`, with optional x-axis `labels`, y-`axis` gridlines/
504/// ticks (cartesian styles), and a series `legend`. The general builder behind the convenience
505/// constructors below.
506#[must_use]
507pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
508    Widget::Chart { series, labels, style, axis, legend }
509}
510/// Bars stacked to a total per x-slot. Axis + legend on by default.
511#[must_use]
512pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
513    chart(series, labels, ChartStyle::StackedBar, true, true)
514}
515/// Bars where each x-slot fills to 100% — series as proportions. Legend on, no value axis.
516#[must_use]
517pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
518    chart(series, labels, ChartStyle::StackedBar100, false, true)
519}
520/// A pie chart — each series is one wedge sized by its magnitude. Legend on.
521#[must_use]
522pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
523    chart(series, vec![], ChartStyle::Pie, false, true)
524}
525/// A donut chart (pie with a center hole). Legend on.
526#[must_use]
527pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
528    chart(series, vec![], ChartStyle::Donut, false, true)
529}
530/// Concentric progress rings — one per series, swept by `sum(values) / goal`. Legend on.
531/// Give each series a goal via [`ChartSeries::with_goal`].
532#[must_use]
533pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
534    chart(series, vec![], ChartStyle::Rings, false, true)
535}
536/// A single radial gauge — the first series' `value / goal` with the number in the center.
537#[must_use]
538pub fn gauge_chart(series: ChartSeries) -> Widget {
539    chart(vec![series], vec![], ChartStyle::Gauge, false, false)
540}
541
542/// A variable-width stacked-region ("coverage-gap" / Marimekko) chart. `regions` are rectangles in
543/// the `[0, x_max] × [0, y_max]` plane (build with [`ChartRegion::new`]); `ticks` label the
544/// irregular x-axis; `ref_lines` are horizontal target/max lines ([`ChartRefLine::target`]/`::max`);
545/// `legend` names the colors. Add a right-side bracket annotation with [`with_bracket`].
546#[must_use]
547pub fn region_chart(
548    regions: Vec<ChartRegion>,
549    ticks: Vec<ChartTick>,
550    x_max: f32,
551    y_max: f32,
552    ref_lines: Vec<ChartRefLine>,
553    legend: Vec<ChartLegendItem>,
554) -> Widget {
555    Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
556}
557
558/// Attach a right-side bracket annotation to a [`region_chart`] (no-op on any other widget).
559#[must_use]
560pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
561    match widget {
562        Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
563            Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
564        }
565        other => other,
566    }
567}
568
569/// Days in `month` (1–12) of `year`, leap-year aware.
570fn days_in_month(year: u32, month: u8) -> u8 {
571    match month {
572        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
573        4 | 6 | 9 | 11 => 30,
574        2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
575        _ => 30,
576    }
577}
578
579/// Weekday of `year-month-day` as 0=Sunday..6=Saturday (Sakamoto's algorithm).
580fn weekday(year: u32, month: u8, day: u8) -> u8 {
581    const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
582    let y = if month < 3 { year - 1 } else { year };
583    let m = month as usize - 1;
584    ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
585}
586
587/// An inline month calendar for `year`/`month` (1–12). `on_day(d)` builds the tap event for each
588/// day `d` in the month; `selected` highlights a day. Leading blanks + weekday header are handled
589/// by the shells from the computed `first_weekday`.
590#[must_use]
591pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
592    let n = days_in_month(year, month);
593    let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
594    Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
595}
596
597/// A list row that reveals trailing `actions` (label, tone, event) on horizontal swipe; each is
598/// tappable. On web the actions render inline (no gesture).
599#[must_use]
600pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
601    Widget::SwipeAction {
602        child: Box::new(child),
603        actions: actions
604            .into_iter()
605            .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
606            .collect(),
607    }
608}
609#[must_use]
610pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
611
612#[must_use]
613pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
614#[must_use]
615pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
616#[must_use]
617pub fn card(child: Widget, style: CardStyle) -> Widget {
618    Widget::Card { child: Box::new(child), style, on_press: None }
619}
620/// A tappable card carrying a typed press event.
621#[must_use]
622pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
623    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
624}
625/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
626/// darkened background and the rest render on top.
627#[must_use]
628pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
629    Widget::Box { children, align, scrim }
630}
631#[must_use]
632pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
633/// Horizontally scrolling row of children (a carousel / chip rail).
634#[must_use]
635pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
636/// A circular avatar image.
637#[must_use]
638pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
639/// A circular avatar image with a colored status dot.
640#[must_use]
641pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
642    Widget::Avatar { source: source.into(), status: Some(status) }
643}
644/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
645#[must_use]
646pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
647/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
648#[must_use]
649pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
650    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
651}
652
653#[must_use]
654pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
655    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
656}
657#[must_use]
658pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
659    Widget::IconButton { icon, on_press: tok(on_press) }
660}
661#[must_use]
662pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
663    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
664}
665#[must_use]
666pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
667    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
668}
669/// A text field with full control over [`FieldKind`] and an optional inline
670/// validation `error`. The kind-specific helpers below ([`secure_field`],
671/// [`email_field`], …) wrap this for the common cases.
672#[must_use]
673pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
674    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
675}
676/// A masked password field ([`FieldKind::Secure`]).
677#[must_use]
678pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
679    field(id, placeholder, value, FieldKind::Secure, None)
680}
681/// An email-keyboard field ([`FieldKind::Email`]).
682#[must_use]
683pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
684    field(id, placeholder, value, FieldKind::Email, None)
685}
686/// A whole-number keypad field ([`FieldKind::Number`]).
687#[must_use]
688pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
689    field(id, placeholder, value, FieldKind::Number, None)
690}
691/// A decimal keypad field ([`FieldKind::Decimal`]).
692#[must_use]
693pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
694    field(id, placeholder, value, FieldKind::Decimal, None)
695}
696/// A phone-keypad field ([`FieldKind::Phone`]).
697#[must_use]
698pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
699    field(id, placeholder, value, FieldKind::Phone, None)
700}
701/// A URL-keyboard field ([`FieldKind::Url`]).
702#[must_use]
703pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
704    field(id, placeholder, value, FieldKind::Url, None)
705}
706/// A growable multi-line text area ([`FieldKind::Multiline`]).
707#[must_use]
708pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
709    field(id, placeholder, value, FieldKind::Multiline, None)
710}
711/// Attach an inline validation message to a [`Widget::TextField`], marking it
712/// invalid. No-op on any other widget.
713#[must_use]
714pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
715    match widget {
716        Widget::TextField { id, placeholder, value, kind, .. } =>
717            Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
718        other => other,
719    }
720}
721/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
722#[must_use]
723pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
724    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
725}
726/// One option in a [`segmented`] control, carrying a typed selection event.
727#[must_use]
728pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
729    Segment { label: label.into(), selected, on_select: tok(on_select) }
730}
731/// A single-choice segmented control (exclusive options in a pill).
732#[must_use]
733pub fn segmented(segments: Vec<Segment>) -> Widget {
734    Widget::Segmented { segments }
735}
736#[must_use]
737pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
738    Widget::Toggle { id: id.into(), label: label.into(), value }
739}
740#[must_use]
741pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
742    Widget::Checkbox { id: id.into(), label: label.into(), value }
743}
744#[must_use]
745pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
746    Widget::Slider { id: id.into(), value, max }
747}
748#[must_use]
749pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
750    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
751}
752
753/// A bottom-nav tab carrying a typed selection event (label-only).
754#[must_use]
755pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
756    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
757}
758
759/// A bottom-nav tab with a leading icon (icon tab bar).
760#[must_use]
761pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
762    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
763}
764
765/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
766/// theme-as-data (the shell themes the whole app from it).
767#[must_use]
768pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
769    let title = title.into();
770    // route defaults to the title; root depth = 1.
771    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 }
772}
773
774/// Like [`scaffold`], but the top bar (and the system back button) navigate back
775/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
776/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
777#[must_use]
778pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
779    let title = title.into();
780    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 }
781}
782
783/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
784/// serialization) and `depth` (stack depth) so the shell animates transitions,
785/// and shows a back affordance (top-bar arrow + system back button) firing
786/// `on_back` whenever the stack can pop.
787#[must_use]
788pub fn nav_scaffold<R, E>(
789    title: impl Into<String>,
790    dark_mode: bool,
791    tabs: Vec<Tab>,
792    body: Widget,
793    nav: &Nav<R>,
794    on_back: E,
795) -> Widget
796where
797    R: Clone + Serialize,
798    E: Serialize,
799{
800    Widget::Scaffold {
801        title: title.into(),
802        body: Box::new(body),
803        tabs,
804        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
805        dark_mode,
806        theme: None,
807        fab: None,
808        sheet: None,
809        on_refresh: None,
810        refreshing: false,
811        route: nav.route_key(),
812        depth: nav.depth(),
813    }
814}
815
816/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
817/// other widget. Lets an app brand its UI without new scaffold builder overloads:
818/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
819pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
820    match widget {
821        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
822            title,
823            body,
824            tabs,
825            back,
826            dark_mode,
827            theme: Some(theme),
828            fab,
829            sheet,
830            on_refresh,
831            refreshing,
832            route,
833            depth,
834        },
835        other => other,
836    }
837}
838
839/// Anchor a floating action button over a scaffold's body (the raised primary action).
840/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
841pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
842    match widget {
843        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
844            title,
845            body,
846            tabs,
847            back,
848            dark_mode,
849            theme,
850            fab: Some(Fab { icon, on_press: tok(on_press) }),
851            sheet,
852            on_refresh,
853            refreshing,
854            route,
855            depth,
856        },
857        other => other,
858    }
859}
860
861/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
862/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
863pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
864    match widget {
865        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
866            title: t,
867            body,
868            tabs,
869            back,
870            dark_mode,
871            theme,
872            fab,
873            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
874            on_refresh,
875            refreshing,
876            route,
877            depth,
878        },
879        other => other,
880    }
881}
882
883/// Enable pull-to-refresh on a scaffold's body: the body becomes pull-refreshable and fires
884/// `on_refresh` on pull. `refreshing` is app-owned — set it true when the pull fires and clear it
885/// when the async reload completes (the shell shows a spinner while true). No-op on other widgets.
886pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
887    match widget {
888        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
889            title,
890            body,
891            tabs,
892            back,
893            dark_mode,
894            theme,
895            fab,
896            sheet,
897            on_refresh: Some(tok(on_refresh)),
898            refreshing,
899            route,
900            depth,
901        },
902        // Pull-to-refresh on a LazyList's top — same API as on a Scaffold. Leaves the load-more
903        // fields intact.
904        Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
905            children,
906            on_load_more,
907            loading,
908            has_more,
909            on_refresh: Some(tok(on_refresh)),
910            refreshing,
911        },
912        other => other,
913    }
914}
915
916/// A scrollable list for long/paged feeds that fires `on_load_more` when the user scrolls near the
917/// end. The app owns the state: append to `children` on each load-more event, set `loading` true
918/// while the page loads (the shell shows a spinner and won't re-fire), and `has_more=false` when
919/// the feed is exhausted. Add pull-to-refresh at the top with [`with_refresh`]. Give it room — a
920/// `LazyList` nested in a scrollable body needs a bounded height to scroll on its own.
921#[must_use]
922pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
923    Widget::LazyList {
924        children,
925        on_load_more: Some(tok(on_load_more)),
926        loading,
927        has_more,
928        on_refresh: None,
929        refreshing: false,
930    }
931}
932
933/// A scrollable list with no load-more and no refresh — a plain virtualized list of `children`.
934#[must_use]
935pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
936    Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
937}
938
939#[cfg(test)]
940mod tests {
941    use super::*;
942    use serde::Serialize;
943
944    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
945    enum Route {
946        Home,
947        Detail(u32),
948    }
949
950    #[derive(Serialize)]
951    enum Ev {
952        Tap,
953        Open(u32),
954    }
955
956    // ---- Nav ----
957
958    #[test]
959    fn nav_push_pop_depth() {
960        let mut nav = Nav::new(Route::Home);
961        assert_eq!(nav.depth(), 1);
962        assert!(!nav.can_go_back());
963
964        nav.push(Route::Detail(7));
965        assert_eq!(nav.depth(), 2);
966        assert!(nav.can_go_back());
967        assert!(matches!(nav.current(), Route::Detail(7)));
968
969        nav.pop();
970        assert_eq!(nav.depth(), 1);
971        assert!(matches!(nav.current(), Route::Home));
972
973        nav.pop(); // no-op at the root
974        assert_eq!(nav.depth(), 1);
975    }
976
977    #[test]
978    fn nav_reset_replaces_stack() {
979        let mut nav = Nav::new(Route::Home);
980        nav.push(Route::Detail(1));
981        nav.push(Route::Detail(2));
982        nav.reset(Route::Detail(9));
983        assert_eq!(nav.depth(), 1);
984        assert!(matches!(nav.current(), Route::Detail(9)));
985    }
986
987    #[test]
988    fn nav_route_key_is_serialization() {
989        let nav = Nav::new(Route::Detail(3));
990        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
991    }
992
993    // ---- builders ----
994
995    #[test]
996    fn scaffold_sets_route_depth_and_no_back() {
997        match scaffold("Home", false, vec![], text("x")) {
998            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
999                assert_eq!(route, "Home");
1000                assert_eq!(depth, 1);
1001                assert!(back.is_none());
1002                assert!(!dark_mode);
1003            }
1004            other => panic!("expected Scaffold, got {other:?}"),
1005        }
1006    }
1007
1008    #[test]
1009    fn scaffold_back_is_depth_2_with_back() {
1010        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1011            Widget::Scaffold { depth, back, dark_mode, .. } => {
1012                assert_eq!(depth, 2);
1013                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1014                assert!(dark_mode);
1015            }
1016            other => panic!("expected Scaffold, got {other:?}"),
1017        }
1018    }
1019
1020    #[test]
1021    fn nav_scaffold_shows_back_only_when_poppable() {
1022        let mut nav = Nav::new(Route::Home);
1023        // at the root: no back, depth 1, route = serialized current route
1024        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1025            Widget::Scaffold { back, depth, route, .. } => {
1026                assert!(back.is_none());
1027                assert_eq!(depth, 1);
1028                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1029            }
1030            other => panic!("expected Scaffold, got {other:?}"),
1031        }
1032        // after a push: back present, depth 2
1033        nav.push(Route::Detail(2));
1034        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1035            Widget::Scaffold { back, depth, .. } => {
1036                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1037                assert_eq!(depth, 2);
1038            }
1039            other => panic!("expected Scaffold, got {other:?}"),
1040        }
1041    }
1042
1043    #[test]
1044    fn buttons_carry_serialized_event_tokens() {
1045        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1046            Widget::Button { label, on_press, .. } => {
1047                assert_eq!(label, "Go");
1048                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1049            }
1050            other => panic!("expected Button, got {other:?}"),
1051        }
1052        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1053            Widget::Card { on_press, .. } => {
1054                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1055            }
1056            other => panic!("expected Card, got {other:?}"),
1057        }
1058        // a plain card is not tappable
1059        match card(text("c"), CardStyle::Elevated) {
1060            Widget::Card { on_press, .. } => assert!(on_press.is_none()),
1061            other => panic!("expected Card, got {other:?}"),
1062        }
1063    }
1064
1065    // ---- Cx capabilities ----
1066
1067    #[test]
1068    fn cx_notify_and_save_enqueue_notifications() {
1069        let mut cx = Cx::<Ev>::default();
1070        cx.notify("toast", "show", "hi");
1071        cx.save("blob");
1072        assert_eq!(cx.notifications.len(), 2);
1073        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1074        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1075        assert!(cx.requests.is_empty());
1076    }
1077
1078    #[test]
1079    fn cx_http_helpers_build_requests() {
1080        let mut cx = Cx::<Ev>::default();
1081        cx.get("http://h/x", |_| Ev::Tap);
1082        cx.post("http://h/y", "hello", |_| Ev::Tap);
1083        cx.patch("http://h/z", "patch", |_| Ev::Tap);
1084        cx.delete("http://h/d", |_| Ev::Tap);
1085
1086        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1087        assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1088        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1089
1090        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1091        assert_eq!(get_input["url"], "http://h/x");
1092        assert!(get_input["body"].is_null());
1093
1094        let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1095        assert_eq!(post_input["url"], "http://h/y");
1096        assert_eq!(post_input["body"], "hello");
1097    }
1098
1099    #[test]
1100    fn cx_pick_and_capture_photo_request_the_right_plugin() {
1101        let mut cx = Cx::<Ev>::default();
1102        cx.pick_photo(|_| Ev::Tap);
1103        cx.capture_photo(|_| Ev::Tap);
1104        assert_eq!(cx.requests.len(), 2);
1105        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
1106        // carry empty input (the shell needs no parameters to launch picker/camera).
1107        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", ""));
1108        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", ""));
1109    }
1110
1111    #[test]
1112    fn cx_capture_photo_routes_success_and_cancel() {
1113        // Happy path: ok=true delivers the URI to the success branch.
1114        let mut cx = Cx::<Ev>::default();
1115        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1116        let (_, then) = cx.requests.pop().unwrap();
1117        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1118
1119        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
1120        let mut cx = Cx::<Ev>::default();
1121        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1122        let (_, then) = cx.requests.pop().unwrap();
1123        assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1124    }
1125
1126    #[test]
1127    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1128        let mut cx = Cx::<Ev>::default();
1129        cx.copy("c");
1130        cx.share("s");
1131        cx.open_url("u");
1132        cx.toast("t");
1133        cx.haptic("heavy");
1134        let got: Vec<(&str, &str, &str)> = cx
1135            .notifications
1136            .iter()
1137            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1138            .collect();
1139        assert_eq!(
1140            got,
1141            vec![
1142                ("clipboard", "copy", "c"),
1143                ("share", "text", "s"),
1144                ("browser", "open", "u"),
1145                ("toast", "show", "t"),
1146                ("haptics", "heavy", ""), // haptic style is the op, input empty
1147            ]
1148        );
1149        assert!(cx.requests.is_empty());
1150    }
1151
1152    #[test]
1153    fn cx_device_model_is_a_request_not_a_notification() {
1154        let mut cx = Cx::<Ev>::default();
1155        cx.device_model(|_| Ev::Tap);
1156        assert!(cx.notifications.is_empty());
1157        assert_eq!(cx.requests.len(), 1);
1158        let (call, _) = &cx.requests[0];
1159        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1160    }
1161
1162    #[test]
1163    fn cx_device_locale_requests_the_device_locale_op() {
1164        let mut cx = Cx::<Ev>::default();
1165        cx.device_locale(|_| Ev::Tap);
1166        assert!(cx.notifications.is_empty());
1167        assert_eq!(cx.requests.len(), 1);
1168        let (call, _) = &cx.requests[0];
1169        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1170    }
1171
1172    #[test]
1173    fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1174        let mut cx = Cx::<Ev>::default();
1175        cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1176        // It's a stream, not a one-shot request or a notification.
1177        assert!(cx.notifications.is_empty());
1178        assert!(cx.requests.is_empty());
1179        assert_eq!(cx.streams.len(), 1);
1180        let (call, on_event) = &cx.streams[0];
1181        assert_eq!(
1182            (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1183            ("ws", "websocket", "stream", "wss://h/x")
1184        );
1185        // The continuation is `Fn` — it can map MANY events, not just one.
1186        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1187        assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1188        assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1189    }
1190
1191    #[test]
1192    fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1193        let mut cx = Cx::<Ev>::default();
1194        cx.unsubscribe("ws");
1195        assert!(cx.streams.is_empty());
1196        assert_eq!(cx.notifications.len(), 1);
1197        // The shell tears down the native source registered under this key.
1198        assert_eq!(
1199            cx.notifications[0],
1200            PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1201        );
1202    }
1203
1204    #[test]
1205    fn cx_confirm_serializes_title_message_and_routes_ok() {
1206        let mut cx = Cx::<Ev>::default();
1207        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1208        let (call, then) = cx.requests.pop().unwrap();
1209        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1210        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1211        assert_eq!(v["title"], "Delete?");
1212        assert_eq!(v["message"], "This cannot be undone.");
1213        // ok=true → confirmed branch; ok=false would take the else branch.
1214        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1215    }
1216
1217    // ---- widget builders ----
1218
1219    #[test]
1220    fn text_builders_carry_their_style() {
1221        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1222        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1223        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1224        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1225        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1226    }
1227
1228    #[test]
1229    fn layout_and_content_builders_produce_their_variants() {
1230        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1231        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1232        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1233        assert!(matches!(divider(), Widget::Divider));
1234        assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1235        assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1236        assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1237        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)));
1238        let rc = with_bracket(
1239            region_chart(
1240                vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1241                vec![ChartTick::new(3.0, "3 Mt.")],
1242                65.0, 80.0,
1243                vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1244                vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1245            ),
1246            ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1247        );
1248        assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1249        // June 2026 has 30 days and starts on a Monday (weekday 1).
1250        assert!(matches!(
1251            calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1252            Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1253        ));
1254        assert!(matches!(
1255            swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1256            Widget::SwipeAction { actions, .. } if actions.len() == 1
1257        ));
1258        // lazy_list carries the load-more token + app-owned flags; no refresh by default.
1259        assert!(matches!(
1260            lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1261            Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1262                if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1263        ));
1264        assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1265        // with_refresh adds pull-to-refresh to a LazyList without disturbing the load-more fields.
1266        assert!(matches!(
1267            with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1268            Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1269                if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1270        ));
1271        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1272        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1273        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1274        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1275        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1276        // a scrim z-stack keeps its align + scrim flag
1277        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1278    }
1279
1280    #[test]
1281    fn input_builders_carry_ids_values_and_event_tokens() {
1282        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1283        assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1284        assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1285        assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1286        assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1287        assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1288        assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1289        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1290        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1291        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1292
1293        match chip("Latte", true, Ev::Open(2)) {
1294            Widget::Chip { selected, on_press, .. } => {
1295                assert!(selected);
1296                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1297            }
1298            other => panic!("expected Chip, got {other:?}"),
1299        }
1300        match stepper(5, Ev::Tap, Ev::Open(1)) {
1301            Widget::Stepper { value, on_decrement, on_increment } => {
1302                assert_eq!(value, 5);
1303                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1304                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1305            }
1306            other => panic!("expected Stepper, got {other:?}"),
1307        }
1308        let t = tab("Home", true, Ev::Tap);
1309        assert_eq!(t.label, "Home");
1310        assert!(t.selected);
1311        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1312    }
1313
1314    // ---- ABI serialization round-trips (structural stability of the wire types) ----
1315
1316    #[test]
1317    fn widget_tree_round_trips_through_serde() {
1318        let tree = scaffold(
1319            "Home",
1320            true,
1321            vec![tab("A", true, Ev::Tap)],
1322            column(vec![
1323                title("Hi"),
1324                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1325                image("u", ImageShape::Rounded, ImageRatio::Wide),
1326                slider("s", 2, 5),
1327            ]),
1328        );
1329        let s = serde_json::to_string(&tree).unwrap();
1330        let back: Widget = serde_json::from_str(&s).unwrap();
1331        assert_eq!(s, serde_json::to_string(&back).unwrap());
1332    }
1333
1334    #[test]
1335    fn actions_and_input_values_round_trip() {
1336        let actions = vec![
1337            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1338            Action::Input { id: "n".into(), value: InputValue::Int(7) },
1339            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1340            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1341            Action::Restore { data: "blob".into() },
1342            Action::Start,
1343        ];
1344        for a in actions {
1345            let s = serde_json::to_string(&a).unwrap();
1346            let back: Action = serde_json::from_str(&s).unwrap();
1347            assert_eq!(s, serde_json::to_string(&back).unwrap());
1348        }
1349    }
1350
1351    // ---- MobilerShell: the fixed-ABI action dispatch ----
1352
1353    #[derive(Default)]
1354    struct CounterModel {
1355        count: i32,
1356        restored: String,
1357        started: bool,
1358        last_input: String,
1359    }
1360
1361    #[derive(serde::Serialize, serde::Deserialize)]
1362    enum CounterEv {
1363        Inc,
1364        Add(i32),
1365    }
1366
1367    #[derive(Default)]
1368    struct CounterApp;
1369
1370    impl MobilerApp for CounterApp {
1371        type Event = CounterEv;
1372        type Model = CounterModel;
1373        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1374            match ev {
1375                CounterEv::Inc => model.count += 1,
1376                CounterEv::Add(n) => model.count += n,
1377            }
1378        }
1379        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1380            if let InputValue::Text(t) = value {
1381                model.last_input = format!("{id}={t}");
1382            }
1383        }
1384        fn restore(&self, data: &str, model: &mut CounterModel) {
1385            model.restored = data.to_string();
1386        }
1387        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1388            model.started = true;
1389        }
1390        fn view(&self, model: &CounterModel) -> Widget {
1391            text(format!("{}", model.count))
1392        }
1393    }
1394
1395    #[test]
1396    fn shell_dispatches_fired_input_restore_and_start() {
1397        use crux_core::App as _;
1398        let shell = MobilerShell::<CounterApp>::default();
1399        let mut m = CounterModel::default();
1400
1401        // Fired with a valid token → the typed event reaches app.update.
1402        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1403        assert_eq!(m.count, 5);
1404        // Input → app.input.
1405        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1406        assert_eq!(m.last_input, "name=bob");
1407        // Restore → app.restore.
1408        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1409        assert_eq!(m.restored, "saved");
1410        // Start → app.init.
1411        let _ = shell.update(Action::Start, &mut m);
1412        assert!(m.started);
1413        // view renders the (mutated) model through the ABI.
1414        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1415    }
1416
1417    #[test]
1418    fn shell_ignores_a_malformed_fired_token() {
1419        use crux_core::App as _;
1420        let shell = MobilerShell::<CounterApp>::default();
1421        let mut m = CounterModel::default();
1422        // A token that doesn't deserialize to the app's event type is dropped — no
1423        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1424        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1425        assert_eq!(m.count, 0);
1426    }
1427}