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, Icon, ImageRatio, ImageShape, InputValue,
21    ProjectColor, Spacing, Tab, TextStyle, 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    /// Ask the user to confirm via a native dialog (built-in `dialog` capability).
175    /// `then` receives the choice: `response.ok` is `true` if confirmed, `false` if
176    /// cancelled/dismissed. Resolves asynchronously (the user replies whenever).
177    pub fn confirm(
178        &mut self,
179        title: impl Into<String>,
180        message: impl Into<String>,
181        then: impl FnOnce(PluginResponse) -> E + Send + 'static,
182    ) {
183        #[derive(Serialize)]
184        struct Confirm {
185            title: String,
186            message: String,
187        }
188        let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
189            .expect("serialize confirm");
190        self.plugin("dialog", "confirm", input, then);
191    }
192}
193
194// ============================ the app trait ============================
195
196/// What a Mobiler app implements. Write typed domain events; Mobiler serializes
197/// them into opaque tokens behind the scenes.
198pub trait MobilerApp: Default {
199    type Event: Serialize + DeserializeOwned + Send + 'static;
200    type Model: Default;
201
202    fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
203
204    fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
205        let _ = (id, value, model, cx);
206    }
207
208    /// Restore persisted state on startup. `data` is whatever you last passed to
209    /// `cx.save` (or empty if nothing was saved). Default: ignore.
210    fn restore(&self, data: &str, model: &mut Self::Model) {
211        let _ = (data, model);
212    }
213
214    /// Run once on startup, after [`restore`](Self::restore). The place to kick
215    /// off initial effects — e.g. fetch data with `cx.get`. Default: nothing.
216    fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
217        let _ = (model, cx);
218    }
219
220    fn view(&self, model: &Self::Model) -> Widget;
221}
222
223/// Crux adapter: turns a [`MobilerApp`] into an app speaking the fixed ABI.
224pub struct MobilerShell<A>(PhantomData<fn() -> A>);
225
226impl<A> Default for MobilerShell<A> {
227    fn default() -> Self {
228        Self(PhantomData)
229    }
230}
231
232impl<A: MobilerApp> App for MobilerShell<A> {
233    type Event = Action;
234    type Model = A::Model;
235    type ViewModel = Widget;
236    type Effect = Effect;
237
238    fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
239        let app = A::default();
240        let mut cx = Cx::<A::Event>::default();
241        match action {
242            Action::Fired { token } => {
243                if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
244                    app.update(event, model, &mut cx);
245                }
246            }
247            Action::Input { id, value } => app.input(&id, value, model, &mut cx),
248            Action::Restore { data } => app.restore(&data, model),
249            Action::Start => app.init(model, &mut cx),
250        }
251        let mut commands: Vec<Command<Effect, Action>> = Vec::new();
252        for op in cx.notifications {
253            commands.push(Command::notify_shell(op).build());
254        }
255        for (op, then) in cx.requests {
256            commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
257                Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
258            }));
259        }
260        commands.push(render());
261        Command::all(commands)
262    }
263
264    fn view(&self, model: &Self::Model) -> Widget {
265        A::default().view(model)
266    }
267}
268
269// ============================ navigation ============================
270
271/// A navigation stack the app holds in its `Model`. The **core owns the stack**
272/// (single source of truth); the framework reads its `route`/`depth` to drive
273/// the shell's push/pop transitions and back button.
274///
275/// `R` is your screen-route type (typically a small enum). Hold it in the model,
276/// mutate it in `update` (`push`/`pop`/`reset`), match `current()` in `view`, and
277/// build the shell with [`nav_scaffold`]. Wire a `Msg::Back` (or similar) event to
278/// `pop` so the back affordance works.
279///
280/// ```ignore
281/// #[derive(Clone, Serialize)] enum Route { List, Detail(u32) }
282/// // model.nav: Nav<Route> = Nav::new(Route::List);
283/// // update: Msg::Open(id) => model.nav.push(Route::Detail(id)),
284/// //         Msg::Back      => model.nav.pop(),
285/// // view:   nav_scaffold(title, dark, tabs, body, &model.nav, Msg::Back)
286/// ```
287#[derive(Clone, Debug)]
288pub struct Nav<R> {
289    stack: Vec<R>,
290}
291
292impl<R: Clone + Serialize> Nav<R> {
293    /// A stack containing a single root route.
294    #[must_use]
295    pub fn new(root: R) -> Self {
296        Self { stack: vec![root] }
297    }
298    /// Push a new screen onto the stack.
299    pub fn push(&mut self, route: R) {
300        self.stack.push(route);
301    }
302    /// Pop the top screen (no-op at the root).
303    pub fn pop(&mut self) {
304        if self.stack.len() > 1 {
305            self.stack.pop();
306        }
307    }
308    /// Replace the whole stack with a fresh root (e.g. switching bottom-nav tabs).
309    pub fn reset(&mut self, root: R) {
310        self.stack = vec![root];
311    }
312    /// The current (top) route — what `view` should render.
313    #[must_use]
314    pub fn current(&self) -> &R {
315        self.stack.last().expect("nav stack is never empty")
316    }
317    /// Stack depth (root = 1).
318    #[must_use]
319    pub fn depth(&self) -> u32 {
320        self.stack.len() as u32
321    }
322    /// Whether there is a screen to pop back to.
323    #[must_use]
324    pub fn can_go_back(&self) -> bool {
325        self.stack.len() > 1
326    }
327    /// Stable identity of the current route (its serialization), used by the shell
328    /// to decide when to animate a transition.
329    fn route_key(&self) -> String {
330        serde_json::to_string(self.current()).expect("serialize route")
331    }
332}
333
334// ============================ widget builders ============================
335// Action-carrying builders take a TYPED event and serialize it into a token.
336
337fn tok<E: Serialize>(event: E) -> String {
338    serde_json::to_string(&event).expect("serialize event")
339}
340
341#[must_use]
342pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
343    Widget::Text { content: content.into(), style }
344}
345#[must_use]
346pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
347#[must_use]
348pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
349#[must_use]
350pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
351#[must_use]
352pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
353#[must_use]
354pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
355
356#[must_use]
357pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
358    Widget::Image { source: source.into(), shape, ratio }
359}
360#[must_use]
361pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
362    Widget::Badge { label: label.into(), tone }
363}
364/// A small colored identity dot.
365#[must_use]
366pub fn color_dot(color: ProjectColor) -> Widget {
367    Widget::ColorDot { color }
368}
369#[must_use]
370pub fn divider() -> Widget { Widget::Divider }
371#[must_use]
372pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
373
374#[must_use]
375pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
376#[must_use]
377pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
378#[must_use]
379pub fn card(child: Widget, style: CardStyle) -> Widget {
380    Widget::Card { child: Box::new(child), style, on_press: None }
381}
382/// A tappable card carrying a typed press event.
383#[must_use]
384pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
385    Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
386}
387/// Z-stack/overlay (the `Box` widget). With `scrim`, the first child is a
388/// darkened background and the rest render on top.
389#[must_use]
390pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
391    Widget::Box { children, align, scrim }
392}
393#[must_use]
394pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
395
396#[must_use]
397pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
398    Widget::Button { label: label.into(), style, on_press: tok(on_press) }
399}
400#[must_use]
401pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
402    Widget::IconButton { icon, on_press: tok(on_press) }
403}
404#[must_use]
405pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
406    Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
407}
408#[must_use]
409pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
410    Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
411}
412#[must_use]
413pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
414    Widget::Toggle { id: id.into(), label: label.into(), value }
415}
416#[must_use]
417pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
418    Widget::Checkbox { id: id.into(), label: label.into(), value }
419}
420#[must_use]
421pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
422    Widget::Slider { id: id.into(), value, max }
423}
424#[must_use]
425pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
426    Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
427}
428
429/// A bottom-nav tab carrying a typed selection event.
430#[must_use]
431pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
432    Tab { label: label.into(), selected, on_select: tok(on_select) }
433}
434
435/// App shell: top bar + bottom-nav `tabs` + scrollable `body`. `dark_mode` is
436/// theme-as-data (the shell themes the whole app from it).
437#[must_use]
438pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
439    let title = title.into();
440    // route defaults to the title; root depth = 1.
441    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, depth: 1 }
442}
443
444/// Like [`scaffold`], but the top bar (and the system back button) navigate back
445/// via `back` — e.g. a detail screen pushed over a tab (treated as depth 2).
446/// For multi-level stacks, drive navigation with [`Nav`] + [`nav_scaffold`].
447#[must_use]
448pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
449    let title = title.into();
450    Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, depth: 2 }
451}
452
453/// Scaffold driven by a [`Nav`] stack: fills `route` (from the current route's
454/// serialization) and `depth` (stack depth) so the shell animates transitions,
455/// and shows a back affordance (top-bar arrow + system back button) firing
456/// `on_back` whenever the stack can pop.
457#[must_use]
458pub fn nav_scaffold<R, E>(
459    title: impl Into<String>,
460    dark_mode: bool,
461    tabs: Vec<Tab>,
462    body: Widget,
463    nav: &Nav<R>,
464    on_back: E,
465) -> Widget
466where
467    R: Clone + Serialize,
468    E: Serialize,
469{
470    Widget::Scaffold {
471        title: title.into(),
472        body: Box::new(body),
473        tabs,
474        back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
475        dark_mode,
476        route: nav.route_key(),
477        depth: nav.depth(),
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484    use serde::Serialize;
485
486    #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
487    enum Route {
488        Home,
489        Detail(u32),
490    }
491
492    #[derive(Serialize)]
493    enum Ev {
494        Tap,
495        Open(u32),
496    }
497
498    // ---- Nav ----
499
500    #[test]
501    fn nav_push_pop_depth() {
502        let mut nav = Nav::new(Route::Home);
503        assert_eq!(nav.depth(), 1);
504        assert!(!nav.can_go_back());
505
506        nav.push(Route::Detail(7));
507        assert_eq!(nav.depth(), 2);
508        assert!(nav.can_go_back());
509        assert!(matches!(nav.current(), Route::Detail(7)));
510
511        nav.pop();
512        assert_eq!(nav.depth(), 1);
513        assert!(matches!(nav.current(), Route::Home));
514
515        nav.pop(); // no-op at the root
516        assert_eq!(nav.depth(), 1);
517    }
518
519    #[test]
520    fn nav_reset_replaces_stack() {
521        let mut nav = Nav::new(Route::Home);
522        nav.push(Route::Detail(1));
523        nav.push(Route::Detail(2));
524        nav.reset(Route::Detail(9));
525        assert_eq!(nav.depth(), 1);
526        assert!(matches!(nav.current(), Route::Detail(9)));
527    }
528
529    #[test]
530    fn nav_route_key_is_serialization() {
531        let nav = Nav::new(Route::Detail(3));
532        assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
533    }
534
535    // ---- builders ----
536
537    #[test]
538    fn scaffold_sets_route_depth_and_no_back() {
539        match scaffold("Home", false, vec![], text("x")) {
540            Widget::Scaffold { route, depth, back, dark_mode, .. } => {
541                assert_eq!(route, "Home");
542                assert_eq!(depth, 1);
543                assert!(back.is_none());
544                assert!(!dark_mode);
545            }
546            other => panic!("expected Scaffold, got {other:?}"),
547        }
548    }
549
550    #[test]
551    fn scaffold_back_is_depth_2_with_back() {
552        match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
553            Widget::Scaffold { depth, back, dark_mode, .. } => {
554                assert_eq!(depth, 2);
555                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
556                assert!(dark_mode);
557            }
558            other => panic!("expected Scaffold, got {other:?}"),
559        }
560    }
561
562    #[test]
563    fn nav_scaffold_shows_back_only_when_poppable() {
564        let mut nav = Nav::new(Route::Home);
565        // at the root: no back, depth 1, route = serialized current route
566        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
567            Widget::Scaffold { back, depth, route, .. } => {
568                assert!(back.is_none());
569                assert_eq!(depth, 1);
570                assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
571            }
572            other => panic!("expected Scaffold, got {other:?}"),
573        }
574        // after a push: back present, depth 2
575        nav.push(Route::Detail(2));
576        match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
577            Widget::Scaffold { back, depth, .. } => {
578                assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
579                assert_eq!(depth, 2);
580            }
581            other => panic!("expected Scaffold, got {other:?}"),
582        }
583    }
584
585    #[test]
586    fn buttons_carry_serialized_event_tokens() {
587        match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
588            Widget::Button { label, on_press, .. } => {
589                assert_eq!(label, "Go");
590                assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
591            }
592            other => panic!("expected Button, got {other:?}"),
593        }
594        match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
595            Widget::Card { on_press, .. } => {
596                assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
597            }
598            other => panic!("expected Card, got {other:?}"),
599        }
600        // a plain card is not tappable
601        match card(text("c"), CardStyle::Elevated) {
602            Widget::Card { on_press, .. } => assert!(on_press.is_none()),
603            other => panic!("expected Card, got {other:?}"),
604        }
605    }
606
607    // ---- Cx capabilities ----
608
609    #[test]
610    fn cx_notify_and_save_enqueue_notifications() {
611        let mut cx = Cx::<Ev>::default();
612        cx.notify("toast", "show", "hi");
613        cx.save("blob");
614        assert_eq!(cx.notifications.len(), 2);
615        assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
616        assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
617        assert!(cx.requests.is_empty());
618    }
619
620    #[test]
621    fn cx_http_helpers_build_requests() {
622        let mut cx = Cx::<Ev>::default();
623        cx.get("http://h/x", |_| Ev::Tap);
624        cx.post("http://h/y", "hello", |_| Ev::Tap);
625        cx.patch("http://h/z", "patch", |_| Ev::Tap);
626        cx.delete("http://h/d", |_| Ev::Tap);
627
628        let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
629        assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
630        assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
631
632        let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
633        assert_eq!(get_input["url"], "http://h/x");
634        assert!(get_input["body"].is_null());
635
636        let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
637        assert_eq!(post_input["url"], "http://h/y");
638        assert_eq!(post_input["body"], "hello");
639    }
640}