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, Icon, ImageRatio, ImageShape, InputValue,
21 ProjectColor, Spacing, Tab, TextStyle, Tone, Widget,
22};
23
24#[effect(facet_typegen)]
28#[derive(Debug)]
29pub enum Effect {
30 Render(RenderOperation),
31 PluginNotify(PluginNotify),
33 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
65pub 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 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 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 pub fn save(&mut self, data: impl Into<String>) {
99 self.notify("storage", "save", data);
100 }
101
102 pub fn copy(&mut self, text: impl Into<String>) {
104 self.notify("clipboard", "copy", text);
105 }
106
107 pub fn share(&mut self, text: impl Into<String>) {
109 self.notify("share", "text", text);
110 }
111
112 pub fn open_url(&mut self, url: impl Into<String>) {
115 self.notify("browser", "open", url);
116 }
117
118 pub fn toast(&mut self, text: impl Into<String>) {
120 self.notify("toast", "show", text);
121 }
122
123 pub fn haptic(&mut self, style: impl Into<String>) {
126 self.notify("haptics", style, "");
127 }
128
129 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 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 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 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 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 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
171 self.plugin("device", "model", "", then);
172 }
173
174 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
179 self.plugin("photo", "pick", "", then);
180 }
181
182 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
189 self.plugin("camera", "capture", "", then);
190 }
191
192 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
212pub 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 fn restore(&self, data: &str, model: &mut Self::Model) {
229 let _ = (data, model);
230 }
231
232 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
241pub 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#[derive(Clone, Debug)]
306pub struct Nav<R> {
307 stack: Vec<R>,
308}
309
310impl<R: Clone + Serialize> Nav<R> {
311 #[must_use]
313 pub fn new(root: R) -> Self {
314 Self { stack: vec![root] }
315 }
316 pub fn push(&mut self, route: R) {
318 self.stack.push(route);
319 }
320 pub fn pop(&mut self) {
322 if self.stack.len() > 1 {
323 self.stack.pop();
324 }
325 }
326 pub fn reset(&mut self, root: R) {
328 self.stack = vec![root];
329 }
330 #[must_use]
332 pub fn current(&self) -> &R {
333 self.stack.last().expect("nav stack is never empty")
334 }
335 #[must_use]
337 pub fn depth(&self) -> u32 {
338 self.stack.len() as u32
339 }
340 #[must_use]
342 pub fn can_go_back(&self) -> bool {
343 self.stack.len() > 1
344 }
345 fn route_key(&self) -> String {
348 serde_json::to_string(self.current()).expect("serialize route")
349 }
350}
351
352fn 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#[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#[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#[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#[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#[must_use]
456pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
457 let title = title.into();
458 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, depth: 1 }
460}
461
462#[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, depth: 2 }
469}
470
471#[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 route: nav.route_key(),
495 depth: nav.depth(),
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502 use serde::Serialize;
503
504 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
505 enum Route {
506 Home,
507 Detail(u32),
508 }
509
510 #[derive(Serialize)]
511 enum Ev {
512 Tap,
513 Open(u32),
514 }
515
516 #[test]
519 fn nav_push_pop_depth() {
520 let mut nav = Nav::new(Route::Home);
521 assert_eq!(nav.depth(), 1);
522 assert!(!nav.can_go_back());
523
524 nav.push(Route::Detail(7));
525 assert_eq!(nav.depth(), 2);
526 assert!(nav.can_go_back());
527 assert!(matches!(nav.current(), Route::Detail(7)));
528
529 nav.pop();
530 assert_eq!(nav.depth(), 1);
531 assert!(matches!(nav.current(), Route::Home));
532
533 nav.pop(); assert_eq!(nav.depth(), 1);
535 }
536
537 #[test]
538 fn nav_reset_replaces_stack() {
539 let mut nav = Nav::new(Route::Home);
540 nav.push(Route::Detail(1));
541 nav.push(Route::Detail(2));
542 nav.reset(Route::Detail(9));
543 assert_eq!(nav.depth(), 1);
544 assert!(matches!(nav.current(), Route::Detail(9)));
545 }
546
547 #[test]
548 fn nav_route_key_is_serialization() {
549 let nav = Nav::new(Route::Detail(3));
550 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
551 }
552
553 #[test]
556 fn scaffold_sets_route_depth_and_no_back() {
557 match scaffold("Home", false, vec![], text("x")) {
558 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
559 assert_eq!(route, "Home");
560 assert_eq!(depth, 1);
561 assert!(back.is_none());
562 assert!(!dark_mode);
563 }
564 other => panic!("expected Scaffold, got {other:?}"),
565 }
566 }
567
568 #[test]
569 fn scaffold_back_is_depth_2_with_back() {
570 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
571 Widget::Scaffold { depth, back, dark_mode, .. } => {
572 assert_eq!(depth, 2);
573 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
574 assert!(dark_mode);
575 }
576 other => panic!("expected Scaffold, got {other:?}"),
577 }
578 }
579
580 #[test]
581 fn nav_scaffold_shows_back_only_when_poppable() {
582 let mut nav = Nav::new(Route::Home);
583 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
585 Widget::Scaffold { back, depth, route, .. } => {
586 assert!(back.is_none());
587 assert_eq!(depth, 1);
588 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
589 }
590 other => panic!("expected Scaffold, got {other:?}"),
591 }
592 nav.push(Route::Detail(2));
594 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
595 Widget::Scaffold { back, depth, .. } => {
596 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
597 assert_eq!(depth, 2);
598 }
599 other => panic!("expected Scaffold, got {other:?}"),
600 }
601 }
602
603 #[test]
604 fn buttons_carry_serialized_event_tokens() {
605 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
606 Widget::Button { label, on_press, .. } => {
607 assert_eq!(label, "Go");
608 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
609 }
610 other => panic!("expected Button, got {other:?}"),
611 }
612 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
613 Widget::Card { on_press, .. } => {
614 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
615 }
616 other => panic!("expected Card, got {other:?}"),
617 }
618 match card(text("c"), CardStyle::Elevated) {
620 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
621 other => panic!("expected Card, got {other:?}"),
622 }
623 }
624
625 #[test]
628 fn cx_notify_and_save_enqueue_notifications() {
629 let mut cx = Cx::<Ev>::default();
630 cx.notify("toast", "show", "hi");
631 cx.save("blob");
632 assert_eq!(cx.notifications.len(), 2);
633 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
634 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
635 assert!(cx.requests.is_empty());
636 }
637
638 #[test]
639 fn cx_http_helpers_build_requests() {
640 let mut cx = Cx::<Ev>::default();
641 cx.get("http://h/x", |_| Ev::Tap);
642 cx.post("http://h/y", "hello", |_| Ev::Tap);
643 cx.patch("http://h/z", "patch", |_| Ev::Tap);
644 cx.delete("http://h/d", |_| Ev::Tap);
645
646 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
647 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
648 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
649
650 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
651 assert_eq!(get_input["url"], "http://h/x");
652 assert!(get_input["body"].is_null());
653
654 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
655 assert_eq!(post_input["url"], "http://h/y");
656 assert_eq!(post_input["body"], "hello");
657 }
658
659 #[test]
660 fn cx_pick_and_capture_photo_request_the_right_plugin() {
661 let mut cx = Cx::<Ev>::default();
662 cx.pick_photo(|_| Ev::Tap);
663 cx.capture_photo(|_| Ev::Tap);
664 assert_eq!(cx.requests.len(), 2);
665 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", ""));
668 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", ""));
669 }
670
671 #[test]
672 fn cx_capture_photo_routes_success_and_cancel() {
673 let mut cx = Cx::<Ev>::default();
675 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
676 let (_, then) = cx.requests.pop().unwrap();
677 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
678
679 let mut cx = Cx::<Ev>::default();
681 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
682 let (_, then) = cx.requests.pop().unwrap();
683 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
684 }
685
686 #[test]
687 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
688 let mut cx = Cx::<Ev>::default();
689 cx.copy("c");
690 cx.share("s");
691 cx.open_url("u");
692 cx.toast("t");
693 cx.haptic("heavy");
694 let got: Vec<(&str, &str, &str)> = cx
695 .notifications
696 .iter()
697 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
698 .collect();
699 assert_eq!(
700 got,
701 vec![
702 ("clipboard", "copy", "c"),
703 ("share", "text", "s"),
704 ("browser", "open", "u"),
705 ("toast", "show", "t"),
706 ("haptics", "heavy", ""), ]
708 );
709 assert!(cx.requests.is_empty());
710 }
711
712 #[test]
713 fn cx_device_model_is_a_request_not_a_notification() {
714 let mut cx = Cx::<Ev>::default();
715 cx.device_model(|_| Ev::Tap);
716 assert!(cx.notifications.is_empty());
717 assert_eq!(cx.requests.len(), 1);
718 let (call, _) = &cx.requests[0];
719 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
720 }
721
722 #[test]
723 fn cx_confirm_serializes_title_message_and_routes_ok() {
724 let mut cx = Cx::<Ev>::default();
725 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
726 let (call, then) = cx.requests.pop().unwrap();
727 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
728 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
729 assert_eq!(v["title"], "Delete?");
730 assert_eq!(v["message"], "This cannot be undone.");
731 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
733 }
734
735 #[test]
738 fn text_builders_carry_their_style() {
739 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
740 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
741 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
742 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
743 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
744 }
745
746 #[test]
747 fn layout_and_content_builders_produce_their_variants() {
748 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
749 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
750 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
751 assert!(matches!(divider(), Widget::Divider));
752 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
753 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
754 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
755 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
756 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
757 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
759 }
760
761 #[test]
762 fn input_builders_carry_ids_values_and_event_tokens() {
763 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { .. }));
764 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
765 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
766 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
767
768 match chip("Latte", true, Ev::Open(2)) {
769 Widget::Chip { selected, on_press, .. } => {
770 assert!(selected);
771 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
772 }
773 other => panic!("expected Chip, got {other:?}"),
774 }
775 match stepper(5, Ev::Tap, Ev::Open(1)) {
776 Widget::Stepper { value, on_decrement, on_increment } => {
777 assert_eq!(value, 5);
778 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
779 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
780 }
781 other => panic!("expected Stepper, got {other:?}"),
782 }
783 let t = tab("Home", true, Ev::Tap);
784 assert_eq!(t.label, "Home");
785 assert!(t.selected);
786 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
787 }
788
789 #[test]
792 fn widget_tree_round_trips_through_serde() {
793 let tree = scaffold(
794 "Home",
795 true,
796 vec![tab("A", true, Ev::Tap)],
797 column(vec![
798 title("Hi"),
799 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
800 image("u", ImageShape::Rounded, ImageRatio::Wide),
801 slider("s", 2, 5),
802 ]),
803 );
804 let s = serde_json::to_string(&tree).unwrap();
805 let back: Widget = serde_json::from_str(&s).unwrap();
806 assert_eq!(s, serde_json::to_string(&back).unwrap());
807 }
808
809 #[test]
810 fn actions_and_input_values_round_trip() {
811 let actions = vec![
812 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
813 Action::Input { id: "n".into(), value: InputValue::Int(7) },
814 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
815 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
816 Action::Restore { data: "blob".into() },
817 Action::Start,
818 ];
819 for a in actions {
820 let s = serde_json::to_string(&a).unwrap();
821 let back: Action = serde_json::from_str(&s).unwrap();
822 assert_eq!(s, serde_json::to_string(&back).unwrap());
823 }
824 }
825
826 #[derive(Default)]
829 struct CounterModel {
830 count: i32,
831 restored: String,
832 started: bool,
833 last_input: String,
834 }
835
836 #[derive(serde::Serialize, serde::Deserialize)]
837 enum CounterEv {
838 Inc,
839 Add(i32),
840 }
841
842 #[derive(Default)]
843 struct CounterApp;
844
845 impl MobilerApp for CounterApp {
846 type Event = CounterEv;
847 type Model = CounterModel;
848 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
849 match ev {
850 CounterEv::Inc => model.count += 1,
851 CounterEv::Add(n) => model.count += n,
852 }
853 }
854 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
855 if let InputValue::Text(t) = value {
856 model.last_input = format!("{id}={t}");
857 }
858 }
859 fn restore(&self, data: &str, model: &mut CounterModel) {
860 model.restored = data.to_string();
861 }
862 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
863 model.started = true;
864 }
865 fn view(&self, model: &CounterModel) -> Widget {
866 text(format!("{}", model.count))
867 }
868 }
869
870 #[test]
871 fn shell_dispatches_fired_input_restore_and_start() {
872 use crux_core::App as _;
873 let shell = MobilerShell::<CounterApp>::default();
874 let mut m = CounterModel::default();
875
876 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
878 assert_eq!(m.count, 5);
879 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
881 assert_eq!(m.last_input, "name=bob");
882 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
884 assert_eq!(m.restored, "saved");
885 let _ = shell.update(Action::Start, &mut m);
887 assert!(m.started);
888 assert!(matches!(shell.view(&m), Widget::Text { .. }));
890 }
891
892 #[test]
893 fn shell_ignores_a_malformed_fired_token() {
894 use crux_core::App as _;
895 let shell = MobilerShell::<CounterApp>::default();
896 let mut m = CounterModel::default();
897 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
900 assert_eq!(m.count, 0);
901 }
902}