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