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
10use crux_core::{
11    App, Command,
12    capability::Operation,
13    macros::effect,
14    render::{RenderOperation, render},
15};
16use facet::Facet;
17use serde::{Deserialize, Serialize, de::DeserializeOwned};
18
19pub use mobiler_ui::{
20    Action, BoxAlign, ButtonStyle, CardStyle, Corner, Density, Fab, FontFamily, Icon, ImageRatio,
21    ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, Tab, TextStyle, Theme, Tone,
22    Widget,
23};
24
25// ============================ capabilities ============================
26
27/// Built-in capabilities the generic shell fulfils.
28#[effect(facet_typegen)]
29#[derive(Debug)]
30pub enum Effect {
31    Render(RenderOperation),
32    /// Fire-and-forget plugin call (shell does not resolve).
33    PluginNotify(PluginNotify),
34    /// Request/response plugin call (shell resolves with a [`PluginResponse`]).
35    Plugin(PluginCall),
36}
37
38#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
39pub struct PluginNotify {
40    pub plugin: String,
41    pub op: String,
42    pub input: String,
43}
44impl Operation for PluginNotify {
45    type Output = ();
46}
47
48#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
49pub struct PluginCall {
50    pub plugin: String,
51    pub op: String,
52    pub input: String,
53}
54impl Operation for PluginCall {
55    type Output = PluginResponse;
56}
57
58#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
59pub struct PluginResponse {
60    pub ok: bool,
61    pub output: String,
62}
63
64type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
65
66/// Effects an app requests during `update`, generic over the app event type so
67/// continuations stay fully typed.
68pub struct Cx<E> {
69    notifications: Vec<PluginNotify>,
70    requests: Vec<(PluginCall, Continuation<E>)>,
71}
72
73impl<E> Default for Cx<E> {
74    fn default() -> Self {
75        Self { notifications: Vec::new(), requests: Vec::new() }
76    }
77}
78
79impl<E> Cx<E> {
80    /// Fire-and-forget call to a native plugin.
81    pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
82        self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
83    }
84
85    /// Request/response call: when the plugin replies, `then(response)` produces
86    /// the typed event delivered back to your `update`.
87    pub fn plugin(
88        &mut self,
89        plugin: impl Into<String>,
90        op: impl Into<String>,
91        input: impl Into<String>,
92        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
93    ) {
94        self.requests
95            .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
96    }
97
98    /// Persist `data` (handed back to [`MobilerApp::restore`] on next startup).
99    pub fn save(&mut self, data: impl Into<String>) {
100        self.notify("storage", "save", data);
101    }
102
103    /// Copy `text` to the system clipboard (built-in `clipboard` capability).
104    pub fn copy(&mut self, text: impl Into<String>) {
105        self.notify("clipboard", "copy", text);
106    }
107
108    /// Open the system share sheet with `text` (built-in `share` capability).
109    pub fn share(&mut self, text: impl Into<String>) {
110        self.notify("share", "text", text);
111    }
112
113    /// Open `url` in the platform browser / default handler (built-in `browser`
114    /// capability). Fire-and-forget: the app leaves the foreground.
115    pub fn open_url(&mut self, url: impl Into<String>) {
116        self.notify("browser", "open", url);
117    }
118
119    /// Show a transient toast / snackbar with `text` (built-in `toast` capability).
120    pub fn toast(&mut self, text: impl Into<String>) {
121        self.notify("toast", "show", text);
122    }
123
124    /// Fire a haptic tap (built-in `haptics` capability). `style` is `"light"`,
125    /// `"medium"`, or `"heavy"`; unknown styles fall back to medium.
126    pub fn haptic(&mut self, style: impl Into<String>) {
127        self.notify("haptics", style, "");
128    }
129
130    /// Perform an HTTP request via the shell's built-in `http` capability. When it
131    /// completes, `then(response)` produces the typed event delivered back to
132    /// `update` — `response.output` is the body, `response.ok` is success (2xx).
133    /// Rides the request/response plugin mechanism, so it resolves asynchronously.
134    pub fn http(
135        &mut self,
136        method: impl Into<String>,
137        url: impl Into<String>,
138        body: Option<String>,
139        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
140    ) {
141        #[derive(Serialize)]
142        struct HttpReq {
143            url: String,
144            body: Option<String>,
145        }
146        let input = serde_json::to_string(&HttpReq { url: url.into(), body })
147            .expect("serialize http request");
148        self.plugin("http", method, input, then);
149    }
150
151    /// `GET url`, delivering the response to `then`.
152    pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
153        self.http("GET", url, None, then);
154    }
155    /// `POST url` with a JSON `body`, delivering the response to `then`.
156    pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
157        self.http("POST", url, Some(body.into()), then);
158    }
159    /// `PATCH url` with a JSON `body`, delivering the response to `then`.
160    pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
161        self.http("PATCH", url, Some(body.into()), then);
162    }
163    /// `DELETE url`, delivering the response to `then`.
164    pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
165        self.http("DELETE", url, None, then);
166    }
167
168    /// Query the device model/name via the built-in `device` capability; the result
169    /// (`response.output`, e.g. "Google Pixel 7" / "Apple iPhone (iOS 18.0)") is
170    /// delivered to `then`.
171    pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
172        self.plugin("device", "model", "", then);
173    }
174
175    /// Let the user pick an image (built-in `photo` capability — the system photo
176    /// picker, no permission required). `then` receives the result: on success
177    /// `response.ok` is `true` and `response.output` is a local image URI you can
178    /// hand straight to the `image(...)` widget; on cancel, `ok` is `false`.
179    pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
180        self.plugin("photo", "pick", "", then);
181    }
182
183    /// Capture a photo with the device camera (built-in `camera` capability — launches
184    /// the system camera). `then` receives the result: on success `response.ok` is
185    /// `true` and `response.output` is a local image URI you can hand straight to the
186    /// `image(...)` widget; on cancel, `ok` is `false`. iOS requires an
187    /// `NSCameraUsageDescription` (the template ships one, opt-in); Android captures via
188    /// the system camera app, so no extra runtime permission is needed.
189    pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
190        self.plugin("camera", "capture", "", then);
191    }
192
193    /// Ask the user to confirm via a native dialog (built-in `dialog` capability).
194    /// `then` receives the choice: `response.ok` is `true` if confirmed, `false` if
195    /// cancelled/dismissed. Resolves asynchronously (the user replies whenever).
196    pub fn confirm(
197        &mut self,
198        title: impl Into<String>,
199        message: impl Into<String>,
200        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
201    ) {
202        #[derive(Serialize)]
203        struct Confirm {
204            title: String,
205            message: String,
206        }
207        let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
208            .expect("serialize confirm");
209        self.plugin("dialog", "confirm", input, then);
210    }
211
212    /// Let the user pick a date via the native date picker (built-in `datetime`
213    /// capability). On success `response.ok` is `true` and `response.output` is the
214    /// chosen date as an ISO `YYYY-MM-DD` string; on cancel/dismiss, `ok` is `false`.
215    /// Resolves asynchronously (the user replies whenever).
216    pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
217        self.plugin("datetime", "date", "", then);
218    }
219
220    /// Let the user pick a time via the native time picker (built-in `datetime`
221    /// capability). On success `response.ok` is `true` and `response.output` is the
222    /// chosen time as a 24-hour `HH:MM` string; on cancel/dismiss, `ok` is `false`.
223    /// Resolves asynchronously (the user replies whenever).
224    pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
225        self.plugin("datetime", "time", "", then);
226    }
227}
228
229// ============================ the app trait ============================
230
231/// What a Mobiler app implements. Write typed domain events; Mobiler serializes
232/// them into opaque tokens behind the scenes.
233pub trait MobilerApp: Default {
234    type Event: Serialize + DeserializeOwned + Send + 'static;
235    type Model: Default;
236
237    fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
238
239    fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
240        let _ = (id, value, model, cx);
241    }
242
243    /// Restore persisted state on startup. `data` is whatever you last passed to
244    /// `cx.save` (or empty if nothing was saved). Default: ignore.
245    fn restore(&self, data: &str, model: &mut Self::Model) {
246        let _ = (data, model);
247    }
248
249    /// Run once on startup, after [`restore`](Self::restore). The place to kick
250    /// off initial effects — e.g. fetch data with `cx.get`. Default: nothing.
251    fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
252        let _ = (model, cx);
253    }
254
255    fn view(&self, model: &Self::Model) -> Widget;
256}
257
258/// Crux adapter: turns a [`MobilerApp`] into an app speaking the fixed ABI.
259pub struct MobilerShell<A>(PhantomData<fn() -> A>);
260
261impl<A> Default for MobilerShell<A> {
262    fn default() -> Self {
263        Self(PhantomData)
264    }
265}
266
267impl<A: MobilerApp> App for MobilerShell<A> {
268    type Event = Action;
269    type Model = A::Model;
270    type ViewModel = Widget;
271    type Effect = Effect;
272
273    fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
274        let app = A::default();
275        let mut cx = Cx::<A::Event>::default();
276        match action {
277            Action::Fired { token } => {
278                if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
279                    app.update(event, model, &mut cx);
280                }
281            }
282            Action::Input { id, value } => app.input(&id, value, model, &mut cx),
283            Action::Restore { data } => app.restore(&data, model),
284            Action::Start => app.init(model, &mut cx),
285        }
286        let mut commands: Vec<Command<Effect, Action>> = Vec::new();
287        for op in cx.notifications {
288            commands.push(Command::notify_shell(op).build());
289        }
290        for (op, then) in cx.requests {
291            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
292                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
293            }));
294        }
295        commands.push(render());
296        Command::all(commands)
297    }
298
299    fn view(&self, model: &Self::Model) -> Widget {
300        A::default().view(model)
301    }
302}
303
304// ============================ navigation ============================
305
306/// A navigation stack the app holds in its `Model`. The **core owns the stack**
307/// (single source of truth); the framework reads its `route`/`depth` to drive
308/// the shell's push/pop transitions and back button.
309///
310/// `R` is your screen-route type (typically a small enum). Hold it in the model,
311/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
312/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
313/// `pop` so the back affordance works.
314///
315/// ```ignore
316/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
317/// // model.nav: Nav<Route> = Nav::new(Route::List);
318/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
319/// //         Msg::Back      => model.nav.pop(),
320/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
321/// ```
322#[derive(Clone, Debug)]
323pub struct Nav<R> {
324    stack: Vec<R>,
325}
326
327impl<R: Clone + Serialize> Nav<R> {
328    /// A stack containing a single root route.
329    #[must_use]
330    pub fn new(root: R) -> Self {
331        Self { stack: vec![root] }
332    }
333    /// Push a new screen onto the stack.
334    pub fn push(&mut self, route: R) {
335        self.stack.push(route);
336    }
337    /// Pop the top screen (no-op at the root).
338    pub fn pop(&mut self) {
339        if self.stack.len() > 1 {
340            self.stack.pop();
341        }
342    }
343    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
344    pub fn reset(&mut self, root: R) {
345        self.stack = vec![root];
346    }
347    /// The current (top) route — what `view` should render.
348    #[must_use]
349    pub fn current(&self) -> &R {
350        self.stack.last().expect("nav stack is never empty")
351    }
352    /// Stack depth (root = 1).
353    #[must_use]
354    pub fn depth(&self) -> u32 {
355        self.stack.len() as u32
356    }
357    /// Whether there is a screen to pop back to.
358    #[must_use]
359    pub fn can_go_back(&self) -> bool {
360        self.stack.len() > 1
361    }
362    /// Stable identity of the current route (its serialization), used by the shell
363    /// to decide when to animate a transition.
364    fn route_key(&self) -> String {
365        serde_json::to_string(self.current()).expect("serialize route")
366    }
367}
368
369// ============================ widget builders ============================
370// Action-carrying builders take a TYPED event and serialize it into a token.
371
372fn tok<E: Serialize>(event: E) -> String {
373    serde_json::to_string(&event).expect("serialize event")
374}
375
376#[must_use]
377pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
378    Widget::Text { content: content.into(), style }
379}
380#[must_use]
381pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
382#[must_use]
383pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
384#[must_use]
385pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
386#[must_use]
387pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
388#[must_use]
389pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
390
391#[must_use]
392pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
393    Widget::Image { source: source.into(), shape, ratio }
394}
395#[must_use]
396pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
397    Widget::Badge { label: label.into(), tone }
398}
399/// A small colored identity dot.
400#[must_use]
401pub fn color_dot(color: ProjectColor) -> Widget {
402    Widget::ColorDot { color }
403}
404#[must_use]
405pub fn divider() -> Widget { Widget::Divider }
406/// A progress bar (`Some(0.0..=1.0)`) or an indeterminate spinner (`None`).
407#[must_use]
408pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
409/// A shimmer placeholder shown while content loads.
410#[must_use]
411pub fn skeleton() -> Widget { Widget::Skeleton }
412#[must_use]
413pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
414
415#[must_use]
416pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
417#[must_use]
418pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
419#[must_use]
420pub fn card(child: Widget, style: CardStyle) -> Widget {
421    Widget::Card { child: Box::new(child), style, on_press: None }
422}
423/// A tappable card carrying a typed press event.
424#[must_use]
425pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
426    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
427}
428/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
429/// darkened background and the rest render on top.
430#[must_use]
431pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
432    Widget::Box { children, align, scrim }
433}
434#[must_use]
435pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
436/// Horizontally scrolling row of children (a carousel / chip rail).
437#[must_use]
438pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
439/// A circular avatar image.
440#[must_use]
441pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
442/// A circular avatar image with a colored status dot.
443#[must_use]
444pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
445    Widget::Avatar { source: source.into(), status: Some(status) }
446}
447/// A read-only star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars).
448#[must_use]
449pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
450/// A tappable star rating — `on_rate` carries one event per star (star *i* fires `on_rate[i]`).
451#[must_use]
452pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
453    Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
454}
455
456#[must_use]
457pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
458    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
459}
460#[must_use]
461pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
462    Widget::IconButton { icon, on_press: tok(on_press) }
463}
464#[must_use]
465pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
466    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
467}
468#[must_use]
469pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
470    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
471}
472/// A search input (leading magnifier, pill); emits `Input { id, Text }` like [`text_field`].
473#[must_use]
474pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
475    Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
476}
477/// One option in a [`segmented`] control, carrying a typed selection event.
478#[must_use]
479pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
480    Segment { label: label.into(), selected, on_select: tok(on_select) }
481}
482/// A single-choice segmented control (exclusive options in a pill).
483#[must_use]
484pub fn segmented(segments: Vec<Segment>) -> Widget {
485    Widget::Segmented { segments }
486}
487#[must_use]
488pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
489    Widget::Toggle { id: id.into(), label: label.into(), value }
490}
491#[must_use]
492pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
493    Widget::Checkbox { id: id.into(), label: label.into(), value }
494}
495#[must_use]
496pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
497    Widget::Slider { id: id.into(), value, max }
498}
499#[must_use]
500pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
501    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
502}
503
504/// A bottom-nav tab carrying a typed selection event (label-only).
505#[must_use]
506pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
507    Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
508}
509
510/// A bottom-nav tab with a leading icon (icon tab bar).
511#[must_use]
512pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
513    Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
514}
515
516/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
517/// theme-as-data (the shell themes the whole app from it).
518#[must_use]
519pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
520    let title = title.into();
521    // route defaults to the title; root depth = 1.
522    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, theme: None, fab: None, sheet: None, depth: 1 }
523}
524
525/// Like [`scaffold`], but the top bar (and the system back button) navigate back
526/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
527/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
528#[must_use]
529pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
530    let title = title.into();
531    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, theme: None, fab: None, sheet: None, depth: 2 }
532}
533
534/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
535/// serialization) and `depth` (stack depth) so the shell animates transitions,
536/// and shows a back affordance (top-bar arrow + system back button) firing
537/// `on_back` whenever the stack can pop.
538#[must_use]
539pub fn nav_scaffold<R, E>(
540    title: impl Into<String>,
541    dark_mode: bool,
542    tabs: Vec<Tab>,
543    body: Widget,
544    nav: &Nav<R>,
545    on_back: E,
546) -> Widget
547where
548    R: Clone + Serialize,
549    E: Serialize,
550{
551    Widget::Scaffold {
552        title: title.into(),
553        body: Box::new(body),
554        tabs,
555        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
556        dark_mode,
557        theme: None,
558        fab: None,
559        sheet: None,
560        route: nav.route_key(),
561        depth: nav.depth(),
562    }
563}
564
565/// Apply a [`Theme`] to a scaffold (brand color, corner, density, font). No-op on any
566/// other widget. Lets an app brand its UI without new scaffold builder overloads:
567/// `with_theme(nav_scaffold(...), Theme { seed, ..Default::default() })`.
568pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
569    match widget {
570        Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, route, depth, .. } => Widget::Scaffold {
571            title,
572            body,
573            tabs,
574            back,
575            dark_mode,
576            theme: Some(theme),
577            fab,
578            sheet,
579            route,
580            depth,
581        },
582        other => other,
583    }
584}
585
586/// Anchor a floating action button over a scaffold's body (the raised primary action).
587/// No-op on any other widget: `with_fab(scaffold(...), Icon::Add, Msg::New)`.
588pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
589    match widget {
590        Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, route, depth, .. } => Widget::Scaffold {
591            title,
592            body,
593            tabs,
594            back,
595            dark_mode,
596            theme,
597            fab: Some(Fab { icon, on_press: tok(on_press) }),
598            sheet,
599            route,
600            depth,
601        },
602        other => other,
603    }
604}
605
606/// Open a modal bottom sheet over a scaffold's body. No-op on any other widget — drive it from
607/// the model: `with_sheet(scaffold(...), title, sheet_body, Msg::CloseSheet)`.
608pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
609    match widget {
610        Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, route, depth, .. } => Widget::Scaffold {
611            title: t,
612            body,
613            tabs,
614            back,
615            dark_mode,
616            theme,
617            fab,
618            sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
619            route,
620            depth,
621        },
622        other => other,
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629    use serde::Serialize;
630
631    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
632    enum Route {
633        Home,
634        Detail(u32),
635    }
636
637    #[derive(Serialize)]
638    enum Ev {
639        Tap,
640        Open(u32),
641    }
642
643    // ---- Nav ----
644
645    #[test]
646    fn nav_push_pop_depth() {
647        let mut nav = Nav::new(Route::Home);
648        assert_eq!(nav.depth(), 1);
649        assert!(!nav.can_go_back());
650
651        nav.push(Route::Detail(7));
652        assert_eq!(nav.depth(), 2);
653        assert!(nav.can_go_back());
654        assert!(matches!(nav.current(), Route::Detail(7)));
655
656        nav.pop();
657        assert_eq!(nav.depth(), 1);
658        assert!(matches!(nav.current(), Route::Home));
659
660        nav.pop(); // no-op at the root
661        assert_eq!(nav.depth(), 1);
662    }
663
664    #[test]
665    fn nav_reset_replaces_stack() {
666        let mut nav = Nav::new(Route::Home);
667        nav.push(Route::Detail(1));
668        nav.push(Route::Detail(2));
669        nav.reset(Route::Detail(9));
670        assert_eq!(nav.depth(), 1);
671        assert!(matches!(nav.current(), Route::Detail(9)));
672    }
673
674    #[test]
675    fn nav_route_key_is_serialization() {
676        let nav = Nav::new(Route::Detail(3));
677        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
678    }
679
680    // ---- builders ----
681
682    #[test]
683    fn scaffold_sets_route_depth_and_no_back() {
684        match scaffold("Home", false, vec![], text("x")) {
685            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
686                assert_eq!(route, "Home");
687                assert_eq!(depth, 1);
688                assert!(back.is_none());
689                assert!(!dark_mode);
690            }
691            other => panic!("expected Scaffold, got {other:?}"),
692        }
693    }
694
695    #[test]
696    fn scaffold_back_is_depth_2_with_back() {
697        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
698            Widget::Scaffold { depth, back, dark_mode, .. } => {
699                assert_eq!(depth, 2);
700                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
701                assert!(dark_mode);
702            }
703            other => panic!("expected Scaffold, got {other:?}"),
704        }
705    }
706
707    #[test]
708    fn nav_scaffold_shows_back_only_when_poppable() {
709        let mut nav = Nav::new(Route::Home);
710        // at the root: no back, depth 1, route = serialized current route
711        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
712            Widget::Scaffold { back, depth, route, .. } => {
713                assert!(back.is_none());
714                assert_eq!(depth, 1);
715                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
716            }
717            other => panic!("expected Scaffold, got {other:?}"),
718        }
719        // after a push: back present, depth 2
720        nav.push(Route::Detail(2));
721        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
722            Widget::Scaffold { back, depth, .. } => {
723                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
724                assert_eq!(depth, 2);
725            }
726            other => panic!("expected Scaffold, got {other:?}"),
727        }
728    }
729
730    #[test]
731    fn buttons_carry_serialized_event_tokens() {
732        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
733            Widget::Button { label, on_press, .. } => {
734                assert_eq!(label, "Go");
735                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
736            }
737            other => panic!("expected Button, got {other:?}"),
738        }
739        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
740            Widget::Card { on_press, .. } => {
741                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
742            }
743            other => panic!("expected Card, got {other:?}"),
744        }
745        // a plain card is not tappable
746        match card(text("c"), CardStyle::Elevated) {
747            Widget::Card { on_press, .. } => assert!(on_press.is_none()),
748            other => panic!("expected Card, got {other:?}"),
749        }
750    }
751
752    // ---- Cx capabilities ----
753
754    #[test]
755    fn cx_notify_and_save_enqueue_notifications() {
756        let mut cx = Cx::<Ev>::default();
757        cx.notify("toast", "show", "hi");
758        cx.save("blob");
759        assert_eq!(cx.notifications.len(), 2);
760        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
761        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
762        assert!(cx.requests.is_empty());
763    }
764
765    #[test]
766    fn cx_http_helpers_build_requests() {
767        let mut cx = Cx::<Ev>::default();
768        cx.get("http://h/x", |_| Ev::Tap);
769        cx.post("http://h/y", "hello", |_| Ev::Tap);
770        cx.patch("http://h/z", "patch", |_| Ev::Tap);
771        cx.delete("http://h/d", |_| Ev::Tap);
772
773        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
774        assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
775        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
776
777        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
778        assert_eq!(get_input["url"], "http://h/x");
779        assert!(get_input["body"].is_null());
780
781        let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
782        assert_eq!(post_input["url"], "http://h/y");
783        assert_eq!(post_input["body"], "hello");
784    }
785
786    #[test]
787    fn cx_pick_and_capture_photo_request_the_right_plugin() {
788        let mut cx = Cx::<Ev>::default();
789        cx.pick_photo(|_| Ev::Tap);
790        cx.capture_photo(|_| Ev::Tap);
791        assert_eq!(cx.requests.len(), 2);
792        // photo picker = `photo`/`pick`; camera capture = `camera`/`capture`. Both
793        // carry empty input (the shell needs no parameters to launch picker/camera).
794        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", ""));
795        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", ""));
796    }
797
798    #[test]
799    fn cx_capture_photo_routes_success_and_cancel() {
800        // Happy path: ok=true delivers the URI to the success branch.
801        let mut cx = Cx::<Ev>::default();
802        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
803        let (_, then) = cx.requests.pop().unwrap();
804        assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
805
806        // Sad path: ok=false (user cancelled / permission denied) takes the else branch.
807        let mut cx = Cx::<Ev>::default();
808        cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
809        let (_, then) = cx.requests.pop().unwrap();
810        assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
811    }
812
813    #[test]
814    fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
815        let mut cx = Cx::<Ev>::default();
816        cx.copy("c");
817        cx.share("s");
818        cx.open_url("u");
819        cx.toast("t");
820        cx.haptic("heavy");
821        let got: Vec<(&str, &str, &str)> = cx
822            .notifications
823            .iter()
824            .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
825            .collect();
826        assert_eq!(
827            got,
828            vec![
829                ("clipboard", "copy", "c"),
830                ("share", "text", "s"),
831                ("browser", "open", "u"),
832                ("toast", "show", "t"),
833                ("haptics", "heavy", ""), // haptic style is the op, input empty
834            ]
835        );
836        assert!(cx.requests.is_empty());
837    }
838
839    #[test]
840    fn cx_device_model_is_a_request_not_a_notification() {
841        let mut cx = Cx::<Ev>::default();
842        cx.device_model(|_| Ev::Tap);
843        assert!(cx.notifications.is_empty());
844        assert_eq!(cx.requests.len(), 1);
845        let (call, _) = &cx.requests[0];
846        assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
847    }
848
849    #[test]
850    fn cx_confirm_serializes_title_message_and_routes_ok() {
851        let mut cx = Cx::<Ev>::default();
852        cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
853        let (call, then) = cx.requests.pop().unwrap();
854        assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
855        let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
856        assert_eq!(v["title"], "Delete?");
857        assert_eq!(v["message"], "This cannot be undone.");
858        // ok=true → confirmed branch; ok=false would take the else branch.
859        assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
860    }
861
862    // ---- widget builders ----
863
864    #[test]
865    fn text_builders_carry_their_style() {
866        assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
867        assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
868        assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
869        assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
870        assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
871    }
872
873    #[test]
874    fn layout_and_content_builders_produce_their_variants() {
875        assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
876        assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
877        assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
878        assert!(matches!(divider(), Widget::Divider));
879        assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
880        assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
881        assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
882        assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
883        assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
884        // a scrim z-stack keeps its align + scrim flag
885        assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
886    }
887
888    #[test]
889    fn input_builders_carry_ids_values_and_event_tokens() {
890        assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { .. }));
891        assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
892        assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
893        assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
894
895        match chip("Latte", true, Ev::Open(2)) {
896            Widget::Chip { selected, on_press, .. } => {
897                assert!(selected);
898                assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
899            }
900            other => panic!("expected Chip, got {other:?}"),
901        }
902        match stepper(5, Ev::Tap, Ev::Open(1)) {
903            Widget::Stepper { value, on_decrement, on_increment } => {
904                assert_eq!(value, 5);
905                assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
906                assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
907            }
908            other => panic!("expected Stepper, got {other:?}"),
909        }
910        let t = tab("Home", true, Ev::Tap);
911        assert_eq!(t.label, "Home");
912        assert!(t.selected);
913        assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
914    }
915
916    // ---- ABI serialization round-trips (structural stability of the wire types) ----
917
918    #[test]
919    fn widget_tree_round_trips_through_serde() {
920        let tree = scaffold(
921            "Home",
922            true,
923            vec![tab("A", true, Ev::Tap)],
924            column(vec![
925                title("Hi"),
926                row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
927                image("u", ImageShape::Rounded, ImageRatio::Wide),
928                slider("s", 2, 5),
929            ]),
930        );
931        let s = serde_json::to_string(&tree).unwrap();
932        let back: Widget = serde_json::from_str(&s).unwrap();
933        assert_eq!(s, serde_json::to_string(&back).unwrap());
934    }
935
936    #[test]
937    fn actions_and_input_values_round_trip() {
938        let actions = vec![
939            Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
940            Action::Input { id: "n".into(), value: InputValue::Int(7) },
941            Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
942            Action::Input { id: "n".into(), value: InputValue::Bool(true) },
943            Action::Restore { data: "blob".into() },
944            Action::Start,
945        ];
946        for a in actions {
947            let s = serde_json::to_string(&a).unwrap();
948            let back: Action = serde_json::from_str(&s).unwrap();
949            assert_eq!(s, serde_json::to_string(&back).unwrap());
950        }
951    }
952
953    // ---- MobilerShell: the fixed-ABI action dispatch ----
954
955    #[derive(Default)]
956    struct CounterModel {
957        count: i32,
958        restored: String,
959        started: bool,
960        last_input: String,
961    }
962
963    #[derive(serde::Serialize, serde::Deserialize)]
964    enum CounterEv {
965        Inc,
966        Add(i32),
967    }
968
969    #[derive(Default)]
970    struct CounterApp;
971
972    impl MobilerApp for CounterApp {
973        type Event = CounterEv;
974        type Model = CounterModel;
975        fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
976            match ev {
977                CounterEv::Inc => model.count += 1,
978                CounterEv::Add(n) => model.count += n,
979            }
980        }
981        fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
982            if let InputValue::Text(t) = value {
983                model.last_input = format!("{id}={t}");
984            }
985        }
986        fn restore(&self, data: &str, model: &mut CounterModel) {
987            model.restored = data.to_string();
988        }
989        fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
990            model.started = true;
991        }
992        fn view(&self, model: &CounterModel) -> Widget {
993            text(format!("{}", model.count))
994        }
995    }
996
997    #[test]
998    fn shell_dispatches_fired_input_restore_and_start() {
999        use crux_core::App as _;
1000        let shell = MobilerShell::<CounterApp>::default();
1001        let mut m = CounterModel::default();
1002
1003        // Fired with a valid token → the typed event reaches app.update.
1004        let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1005        assert_eq!(m.count, 5);
1006        // Input → app.input.
1007        let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1008        assert_eq!(m.last_input, "name=bob");
1009        // Restore → app.restore.
1010        let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1011        assert_eq!(m.restored, "saved");
1012        // Start → app.init.
1013        let _ = shell.update(Action::Start, &mut m);
1014        assert!(m.started);
1015        // view renders the (mutated) model through the ABI.
1016        assert!(matches!(shell.view(&m), Widget::Text { .. }));
1017    }
1018
1019    #[test]
1020    fn shell_ignores_a_malformed_fired_token() {
1021        use crux_core::App as _;
1022        let shell = MobilerShell::<CounterApp>::default();
1023        let mut m = CounterModel::default();
1024        // A token that doesn't deserialize to the app's event type is dropped — no
1025        // panic, model untouched (the `if let Ok(event)` guard in MobilerShell::update).
1026        let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1027        assert_eq!(m.count, 0);
1028    }
1029}