1use 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#[effect(facet_typegen)]
29#[derive(Debug)]
30pub enum Effect {
31 Render(RenderOperation),
32 PluginNotify(PluginNotify),
34 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
66pub 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 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 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 pub fn save(&mut self, data: impl Into<String>) {
100 self.notify("storage", "save", data);
101 }
102
103 pub fn copy(&mut self, text: impl Into<String>) {
105 self.notify("clipboard", "copy", text);
106 }
107
108 pub fn share(&mut self, text: impl Into<String>) {
110 self.notify("share", "text", text);
111 }
112
113 pub fn open_url(&mut self, url: impl Into<String>) {
116 self.notify("browser", "open", url);
117 }
118
119 pub fn toast(&mut self, text: impl Into<String>) {
121 self.notify("toast", "show", text);
122 }
123
124 pub fn haptic(&mut self, style: impl Into<String>) {
127 self.notify("haptics", style, "");
128 }
129
130 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 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 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 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 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 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
172 self.plugin("device", "model", "", then);
173 }
174
175 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
180 self.plugin("photo", "pick", "", then);
181 }
182
183 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
190 self.plugin("camera", "capture", "", then);
191 }
192
193 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 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
217 self.plugin("datetime", "date", "", then);
218 }
219
220 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
225 self.plugin("datetime", "time", "", then);
226 }
227}
228
229pub 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 fn restore(&self, data: &str, model: &mut Self::Model) {
246 let _ = (data, model);
247 }
248
249 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
258pub 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#[derive(Clone, Debug)]
323pub struct Nav<R> {
324 stack: Vec<R>,
325}
326
327impl<R: Clone + Serialize> Nav<R> {
328 #[must_use]
330 pub fn new(root: R) -> Self {
331 Self { stack: vec![root] }
332 }
333 pub fn push(&mut self, route: R) {
335 self.stack.push(route);
336 }
337 pub fn pop(&mut self) {
339 if self.stack.len() > 1 {
340 self.stack.pop();
341 }
342 }
343 pub fn reset(&mut self, root: R) {
345 self.stack = vec![root];
346 }
347 #[must_use]
349 pub fn current(&self) -> &R {
350 self.stack.last().expect("nav stack is never empty")
351 }
352 #[must_use]
354 pub fn depth(&self) -> u32 {
355 self.stack.len() as u32
356 }
357 #[must_use]
359 pub fn can_go_back(&self) -> bool {
360 self.stack.len() > 1
361 }
362 fn route_key(&self) -> String {
365 serde_json::to_string(self.current()).expect("serialize route")
366 }
367}
368
369fn 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#[must_use]
401pub fn color_dot(color: ProjectColor) -> Widget {
402 Widget::ColorDot { color }
403}
404#[must_use]
405pub fn divider() -> Widget { Widget::Divider }
406#[must_use]
407pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
408
409#[must_use]
410pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
411#[must_use]
412pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
413#[must_use]
414pub fn card(child: Widget, style: CardStyle) -> Widget {
415 Widget::Card { child: Box::new(child), style, on_press: None }
416}
417#[must_use]
419pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
420 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
421}
422#[must_use]
425pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
426 Widget::Box { children, align, scrim }
427}
428#[must_use]
429pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
430#[must_use]
432pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
433#[must_use]
435pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
436#[must_use]
438pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
439 Widget::Avatar { source: source.into(), status: Some(status) }
440}
441#[must_use]
443pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
444#[must_use]
446pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
447 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
448}
449
450#[must_use]
451pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
452 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
453}
454#[must_use]
455pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
456 Widget::IconButton { icon, on_press: tok(on_press) }
457}
458#[must_use]
459pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
460 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
461}
462#[must_use]
463pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
464 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
465}
466#[must_use]
468pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
469 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
470}
471#[must_use]
473pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
474 Segment { label: label.into(), selected, on_select: tok(on_select) }
475}
476#[must_use]
478pub fn segmented(segments: Vec<Segment>) -> Widget {
479 Widget::Segmented { segments }
480}
481#[must_use]
482pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
483 Widget::Toggle { id: id.into(), label: label.into(), value }
484}
485#[must_use]
486pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
487 Widget::Checkbox { id: id.into(), label: label.into(), value }
488}
489#[must_use]
490pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
491 Widget::Slider { id: id.into(), value, max }
492}
493#[must_use]
494pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
495 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
496}
497
498#[must_use]
500pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
501 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
502}
503
504#[must_use]
506pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
507 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
508}
509
510#[must_use]
513pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
514 let title = title.into();
515 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, theme: None, fab: None, sheet: None, depth: 1 }
517}
518
519#[must_use]
523pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
524 let title = title.into();
525 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 }
526}
527
528#[must_use]
533pub fn nav_scaffold<R, E>(
534 title: impl Into<String>,
535 dark_mode: bool,
536 tabs: Vec<Tab>,
537 body: Widget,
538 nav: &Nav<R>,
539 on_back: E,
540) -> Widget
541where
542 R: Clone + Serialize,
543 E: Serialize,
544{
545 Widget::Scaffold {
546 title: title.into(),
547 body: Box::new(body),
548 tabs,
549 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
550 dark_mode,
551 theme: None,
552 fab: None,
553 sheet: None,
554 route: nav.route_key(),
555 depth: nav.depth(),
556 }
557}
558
559pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
563 match widget {
564 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, route, depth, .. } => Widget::Scaffold {
565 title,
566 body,
567 tabs,
568 back,
569 dark_mode,
570 theme: Some(theme),
571 fab,
572 sheet,
573 route,
574 depth,
575 },
576 other => other,
577 }
578}
579
580pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
583 match widget {
584 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, route, depth, .. } => Widget::Scaffold {
585 title,
586 body,
587 tabs,
588 back,
589 dark_mode,
590 theme,
591 fab: Some(Fab { icon, on_press: tok(on_press) }),
592 sheet,
593 route,
594 depth,
595 },
596 other => other,
597 }
598}
599
600pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
603 match widget {
604 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, route, depth, .. } => Widget::Scaffold {
605 title: t,
606 body,
607 tabs,
608 back,
609 dark_mode,
610 theme,
611 fab,
612 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
613 route,
614 depth,
615 },
616 other => other,
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623 use serde::Serialize;
624
625 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
626 enum Route {
627 Home,
628 Detail(u32),
629 }
630
631 #[derive(Serialize)]
632 enum Ev {
633 Tap,
634 Open(u32),
635 }
636
637 #[test]
640 fn nav_push_pop_depth() {
641 let mut nav = Nav::new(Route::Home);
642 assert_eq!(nav.depth(), 1);
643 assert!(!nav.can_go_back());
644
645 nav.push(Route::Detail(7));
646 assert_eq!(nav.depth(), 2);
647 assert!(nav.can_go_back());
648 assert!(matches!(nav.current(), Route::Detail(7)));
649
650 nav.pop();
651 assert_eq!(nav.depth(), 1);
652 assert!(matches!(nav.current(), Route::Home));
653
654 nav.pop(); assert_eq!(nav.depth(), 1);
656 }
657
658 #[test]
659 fn nav_reset_replaces_stack() {
660 let mut nav = Nav::new(Route::Home);
661 nav.push(Route::Detail(1));
662 nav.push(Route::Detail(2));
663 nav.reset(Route::Detail(9));
664 assert_eq!(nav.depth(), 1);
665 assert!(matches!(nav.current(), Route::Detail(9)));
666 }
667
668 #[test]
669 fn nav_route_key_is_serialization() {
670 let nav = Nav::new(Route::Detail(3));
671 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
672 }
673
674 #[test]
677 fn scaffold_sets_route_depth_and_no_back() {
678 match scaffold("Home", false, vec![], text("x")) {
679 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
680 assert_eq!(route, "Home");
681 assert_eq!(depth, 1);
682 assert!(back.is_none());
683 assert!(!dark_mode);
684 }
685 other => panic!("expected Scaffold, got {other:?}"),
686 }
687 }
688
689 #[test]
690 fn scaffold_back_is_depth_2_with_back() {
691 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
692 Widget::Scaffold { depth, back, dark_mode, .. } => {
693 assert_eq!(depth, 2);
694 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
695 assert!(dark_mode);
696 }
697 other => panic!("expected Scaffold, got {other:?}"),
698 }
699 }
700
701 #[test]
702 fn nav_scaffold_shows_back_only_when_poppable() {
703 let mut nav = Nav::new(Route::Home);
704 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
706 Widget::Scaffold { back, depth, route, .. } => {
707 assert!(back.is_none());
708 assert_eq!(depth, 1);
709 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
710 }
711 other => panic!("expected Scaffold, got {other:?}"),
712 }
713 nav.push(Route::Detail(2));
715 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
716 Widget::Scaffold { back, depth, .. } => {
717 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
718 assert_eq!(depth, 2);
719 }
720 other => panic!("expected Scaffold, got {other:?}"),
721 }
722 }
723
724 #[test]
725 fn buttons_carry_serialized_event_tokens() {
726 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
727 Widget::Button { label, on_press, .. } => {
728 assert_eq!(label, "Go");
729 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
730 }
731 other => panic!("expected Button, got {other:?}"),
732 }
733 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
734 Widget::Card { on_press, .. } => {
735 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
736 }
737 other => panic!("expected Card, got {other:?}"),
738 }
739 match card(text("c"), CardStyle::Elevated) {
741 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
742 other => panic!("expected Card, got {other:?}"),
743 }
744 }
745
746 #[test]
749 fn cx_notify_and_save_enqueue_notifications() {
750 let mut cx = Cx::<Ev>::default();
751 cx.notify("toast", "show", "hi");
752 cx.save("blob");
753 assert_eq!(cx.notifications.len(), 2);
754 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
755 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
756 assert!(cx.requests.is_empty());
757 }
758
759 #[test]
760 fn cx_http_helpers_build_requests() {
761 let mut cx = Cx::<Ev>::default();
762 cx.get("http://h/x", |_| Ev::Tap);
763 cx.post("http://h/y", "hello", |_| Ev::Tap);
764 cx.patch("http://h/z", "patch", |_| Ev::Tap);
765 cx.delete("http://h/d", |_| Ev::Tap);
766
767 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
768 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
769 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
770
771 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
772 assert_eq!(get_input["url"], "http://h/x");
773 assert!(get_input["body"].is_null());
774
775 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
776 assert_eq!(post_input["url"], "http://h/y");
777 assert_eq!(post_input["body"], "hello");
778 }
779
780 #[test]
781 fn cx_pick_and_capture_photo_request_the_right_plugin() {
782 let mut cx = Cx::<Ev>::default();
783 cx.pick_photo(|_| Ev::Tap);
784 cx.capture_photo(|_| Ev::Tap);
785 assert_eq!(cx.requests.len(), 2);
786 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", ""));
789 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", ""));
790 }
791
792 #[test]
793 fn cx_capture_photo_routes_success_and_cancel() {
794 let mut cx = Cx::<Ev>::default();
796 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
797 let (_, then) = cx.requests.pop().unwrap();
798 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
799
800 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: false, output: String::new() }), Ev::Tap));
805 }
806
807 #[test]
808 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
809 let mut cx = Cx::<Ev>::default();
810 cx.copy("c");
811 cx.share("s");
812 cx.open_url("u");
813 cx.toast("t");
814 cx.haptic("heavy");
815 let got: Vec<(&str, &str, &str)> = cx
816 .notifications
817 .iter()
818 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
819 .collect();
820 assert_eq!(
821 got,
822 vec![
823 ("clipboard", "copy", "c"),
824 ("share", "text", "s"),
825 ("browser", "open", "u"),
826 ("toast", "show", "t"),
827 ("haptics", "heavy", ""), ]
829 );
830 assert!(cx.requests.is_empty());
831 }
832
833 #[test]
834 fn cx_device_model_is_a_request_not_a_notification() {
835 let mut cx = Cx::<Ev>::default();
836 cx.device_model(|_| Ev::Tap);
837 assert!(cx.notifications.is_empty());
838 assert_eq!(cx.requests.len(), 1);
839 let (call, _) = &cx.requests[0];
840 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
841 }
842
843 #[test]
844 fn cx_confirm_serializes_title_message_and_routes_ok() {
845 let mut cx = Cx::<Ev>::default();
846 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
847 let (call, then) = cx.requests.pop().unwrap();
848 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
849 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
850 assert_eq!(v["title"], "Delete?");
851 assert_eq!(v["message"], "This cannot be undone.");
852 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
854 }
855
856 #[test]
859 fn text_builders_carry_their_style() {
860 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
861 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
862 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
863 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
864 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
865 }
866
867 #[test]
868 fn layout_and_content_builders_produce_their_variants() {
869 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
870 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
871 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
872 assert!(matches!(divider(), Widget::Divider));
873 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
874 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
875 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
876 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
877 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
878 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
880 }
881
882 #[test]
883 fn input_builders_carry_ids_values_and_event_tokens() {
884 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { .. }));
885 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
886 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
887 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
888
889 match chip("Latte", true, Ev::Open(2)) {
890 Widget::Chip { selected, on_press, .. } => {
891 assert!(selected);
892 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
893 }
894 other => panic!("expected Chip, got {other:?}"),
895 }
896 match stepper(5, Ev::Tap, Ev::Open(1)) {
897 Widget::Stepper { value, on_decrement, on_increment } => {
898 assert_eq!(value, 5);
899 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
900 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
901 }
902 other => panic!("expected Stepper, got {other:?}"),
903 }
904 let t = tab("Home", true, Ev::Tap);
905 assert_eq!(t.label, "Home");
906 assert!(t.selected);
907 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
908 }
909
910 #[test]
913 fn widget_tree_round_trips_through_serde() {
914 let tree = scaffold(
915 "Home",
916 true,
917 vec![tab("A", true, Ev::Tap)],
918 column(vec![
919 title("Hi"),
920 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
921 image("u", ImageShape::Rounded, ImageRatio::Wide),
922 slider("s", 2, 5),
923 ]),
924 );
925 let s = serde_json::to_string(&tree).unwrap();
926 let back: Widget = serde_json::from_str(&s).unwrap();
927 assert_eq!(s, serde_json::to_string(&back).unwrap());
928 }
929
930 #[test]
931 fn actions_and_input_values_round_trip() {
932 let actions = vec![
933 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
934 Action::Input { id: "n".into(), value: InputValue::Int(7) },
935 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
936 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
937 Action::Restore { data: "blob".into() },
938 Action::Start,
939 ];
940 for a in actions {
941 let s = serde_json::to_string(&a).unwrap();
942 let back: Action = serde_json::from_str(&s).unwrap();
943 assert_eq!(s, serde_json::to_string(&back).unwrap());
944 }
945 }
946
947 #[derive(Default)]
950 struct CounterModel {
951 count: i32,
952 restored: String,
953 started: bool,
954 last_input: String,
955 }
956
957 #[derive(serde::Serialize, serde::Deserialize)]
958 enum CounterEv {
959 Inc,
960 Add(i32),
961 }
962
963 #[derive(Default)]
964 struct CounterApp;
965
966 impl MobilerApp for CounterApp {
967 type Event = CounterEv;
968 type Model = CounterModel;
969 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
970 match ev {
971 CounterEv::Inc => model.count += 1,
972 CounterEv::Add(n) => model.count += n,
973 }
974 }
975 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
976 if let InputValue::Text(t) = value {
977 model.last_input = format!("{id}={t}");
978 }
979 }
980 fn restore(&self, data: &str, model: &mut CounterModel) {
981 model.restored = data.to_string();
982 }
983 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
984 model.started = true;
985 }
986 fn view(&self, model: &CounterModel) -> Widget {
987 text(format!("{}", model.count))
988 }
989 }
990
991 #[test]
992 fn shell_dispatches_fired_input_restore_and_start() {
993 use crux_core::App as _;
994 let shell = MobilerShell::<CounterApp>::default();
995 let mut m = CounterModel::default();
996
997 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
999 assert_eq!(m.count, 5);
1000 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1002 assert_eq!(m.last_input, "name=bob");
1003 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1005 assert_eq!(m.restored, "saved");
1006 let _ = shell.update(Action::Start, &mut m);
1008 assert!(m.started);
1009 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1011 }
1012
1013 #[test]
1014 fn shell_ignores_a_malformed_fired_token() {
1015 use crux_core::App as _;
1016 let shell = MobilerShell::<CounterApp>::default();
1017 let mut m = CounterModel::default();
1018 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1021 assert_eq!(m.count, 0);
1022 }
1023}