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, ChartStyle, Corner, Density, Fab, FontFamily, Icon,
21 ImageRatio, ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
22 TextStyle, Theme, Tone, 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]
408pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
409#[must_use]
411pub fn skeleton() -> Widget { Widget::Skeleton }
412#[must_use]
414pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
415 Widget::Chart { values, labels, style: ChartStyle::Bar }
416}
417#[must_use]
419pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
420 Widget::Chart { values, labels, style: ChartStyle::Line }
421}
422
423fn days_in_month(year: u32, month: u8) -> u8 {
425 match month {
426 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
427 4 | 6 | 9 | 11 => 30,
428 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
429 _ => 30,
430 }
431}
432
433fn weekday(year: u32, month: u8, day: u8) -> u8 {
435 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
436 let y = if month < 3 { year - 1 } else { year };
437 let m = month as usize - 1;
438 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
439}
440
441#[must_use]
445pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
446 let n = days_in_month(year, month);
447 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
448 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
449}
450
451#[must_use]
454pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
455 Widget::SwipeAction {
456 child: Box::new(child),
457 actions: actions
458 .into_iter()
459 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
460 .collect(),
461 }
462}
463#[must_use]
464pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
465
466#[must_use]
467pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
468#[must_use]
469pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
470#[must_use]
471pub fn card(child: Widget, style: CardStyle) -> Widget {
472 Widget::Card { child: Box::new(child), style, on_press: None }
473}
474#[must_use]
476pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
477 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
478}
479#[must_use]
482pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
483 Widget::Box { children, align, scrim }
484}
485#[must_use]
486pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
487#[must_use]
489pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
490#[must_use]
492pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
493#[must_use]
495pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
496 Widget::Avatar { source: source.into(), status: Some(status) }
497}
498#[must_use]
500pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
501#[must_use]
503pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
504 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
505}
506
507#[must_use]
508pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
509 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
510}
511#[must_use]
512pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
513 Widget::IconButton { icon, on_press: tok(on_press) }
514}
515#[must_use]
516pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
517 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
518}
519#[must_use]
520pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
521 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
522}
523#[must_use]
525pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
526 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
527}
528#[must_use]
530pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
531 Segment { label: label.into(), selected, on_select: tok(on_select) }
532}
533#[must_use]
535pub fn segmented(segments: Vec<Segment>) -> Widget {
536 Widget::Segmented { segments }
537}
538#[must_use]
539pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
540 Widget::Toggle { id: id.into(), label: label.into(), value }
541}
542#[must_use]
543pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
544 Widget::Checkbox { id: id.into(), label: label.into(), value }
545}
546#[must_use]
547pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
548 Widget::Slider { id: id.into(), value, max }
549}
550#[must_use]
551pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
552 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
553}
554
555#[must_use]
557pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
558 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
559}
560
561#[must_use]
563pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
564 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
565}
566
567#[must_use]
570pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
571 let title = title.into();
572 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, theme: None, fab: None, sheet: None, on_refresh: None, refreshing: false, depth: 1 }
574}
575
576#[must_use]
580pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
581 let title = title.into();
582 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, theme: None, fab: None, sheet: None, on_refresh: None, refreshing: false, depth: 2 }
583}
584
585#[must_use]
590pub fn nav_scaffold<R, E>(
591 title: impl Into<String>,
592 dark_mode: bool,
593 tabs: Vec<Tab>,
594 body: Widget,
595 nav: &Nav<R>,
596 on_back: E,
597) -> Widget
598where
599 R: Clone + Serialize,
600 E: Serialize,
601{
602 Widget::Scaffold {
603 title: title.into(),
604 body: Box::new(body),
605 tabs,
606 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
607 dark_mode,
608 theme: None,
609 fab: None,
610 sheet: None,
611 on_refresh: None,
612 refreshing: false,
613 route: nav.route_key(),
614 depth: nav.depth(),
615 }
616}
617
618pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
622 match widget {
623 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
624 title,
625 body,
626 tabs,
627 back,
628 dark_mode,
629 theme: Some(theme),
630 fab,
631 sheet,
632 on_refresh,
633 refreshing,
634 route,
635 depth,
636 },
637 other => other,
638 }
639}
640
641pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
644 match widget {
645 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
646 title,
647 body,
648 tabs,
649 back,
650 dark_mode,
651 theme,
652 fab: Some(Fab { icon, on_press: tok(on_press) }),
653 sheet,
654 on_refresh,
655 refreshing,
656 route,
657 depth,
658 },
659 other => other,
660 }
661}
662
663pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
666 match widget {
667 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
668 title: t,
669 body,
670 tabs,
671 back,
672 dark_mode,
673 theme,
674 fab,
675 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
676 on_refresh,
677 refreshing,
678 route,
679 depth,
680 },
681 other => other,
682 }
683}
684
685pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
689 match widget {
690 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
691 title,
692 body,
693 tabs,
694 back,
695 dark_mode,
696 theme,
697 fab,
698 sheet,
699 on_refresh: Some(tok(on_refresh)),
700 refreshing,
701 route,
702 depth,
703 },
704 other => other,
705 }
706}
707
708#[cfg(test)]
709mod tests {
710 use super::*;
711 use serde::Serialize;
712
713 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
714 enum Route {
715 Home,
716 Detail(u32),
717 }
718
719 #[derive(Serialize)]
720 enum Ev {
721 Tap,
722 Open(u32),
723 }
724
725 #[test]
728 fn nav_push_pop_depth() {
729 let mut nav = Nav::new(Route::Home);
730 assert_eq!(nav.depth(), 1);
731 assert!(!nav.can_go_back());
732
733 nav.push(Route::Detail(7));
734 assert_eq!(nav.depth(), 2);
735 assert!(nav.can_go_back());
736 assert!(matches!(nav.current(), Route::Detail(7)));
737
738 nav.pop();
739 assert_eq!(nav.depth(), 1);
740 assert!(matches!(nav.current(), Route::Home));
741
742 nav.pop(); assert_eq!(nav.depth(), 1);
744 }
745
746 #[test]
747 fn nav_reset_replaces_stack() {
748 let mut nav = Nav::new(Route::Home);
749 nav.push(Route::Detail(1));
750 nav.push(Route::Detail(2));
751 nav.reset(Route::Detail(9));
752 assert_eq!(nav.depth(), 1);
753 assert!(matches!(nav.current(), Route::Detail(9)));
754 }
755
756 #[test]
757 fn nav_route_key_is_serialization() {
758 let nav = Nav::new(Route::Detail(3));
759 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
760 }
761
762 #[test]
765 fn scaffold_sets_route_depth_and_no_back() {
766 match scaffold("Home", false, vec![], text("x")) {
767 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
768 assert_eq!(route, "Home");
769 assert_eq!(depth, 1);
770 assert!(back.is_none());
771 assert!(!dark_mode);
772 }
773 other => panic!("expected Scaffold, got {other:?}"),
774 }
775 }
776
777 #[test]
778 fn scaffold_back_is_depth_2_with_back() {
779 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
780 Widget::Scaffold { depth, back, dark_mode, .. } => {
781 assert_eq!(depth, 2);
782 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
783 assert!(dark_mode);
784 }
785 other => panic!("expected Scaffold, got {other:?}"),
786 }
787 }
788
789 #[test]
790 fn nav_scaffold_shows_back_only_when_poppable() {
791 let mut nav = Nav::new(Route::Home);
792 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
794 Widget::Scaffold { back, depth, route, .. } => {
795 assert!(back.is_none());
796 assert_eq!(depth, 1);
797 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
798 }
799 other => panic!("expected Scaffold, got {other:?}"),
800 }
801 nav.push(Route::Detail(2));
803 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
804 Widget::Scaffold { back, depth, .. } => {
805 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
806 assert_eq!(depth, 2);
807 }
808 other => panic!("expected Scaffold, got {other:?}"),
809 }
810 }
811
812 #[test]
813 fn buttons_carry_serialized_event_tokens() {
814 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
815 Widget::Button { label, on_press, .. } => {
816 assert_eq!(label, "Go");
817 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
818 }
819 other => panic!("expected Button, got {other:?}"),
820 }
821 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
822 Widget::Card { on_press, .. } => {
823 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
824 }
825 other => panic!("expected Card, got {other:?}"),
826 }
827 match card(text("c"), CardStyle::Elevated) {
829 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
830 other => panic!("expected Card, got {other:?}"),
831 }
832 }
833
834 #[test]
837 fn cx_notify_and_save_enqueue_notifications() {
838 let mut cx = Cx::<Ev>::default();
839 cx.notify("toast", "show", "hi");
840 cx.save("blob");
841 assert_eq!(cx.notifications.len(), 2);
842 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
843 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
844 assert!(cx.requests.is_empty());
845 }
846
847 #[test]
848 fn cx_http_helpers_build_requests() {
849 let mut cx = Cx::<Ev>::default();
850 cx.get("http://h/x", |_| Ev::Tap);
851 cx.post("http://h/y", "hello", |_| Ev::Tap);
852 cx.patch("http://h/z", "patch", |_| Ev::Tap);
853 cx.delete("http://h/d", |_| Ev::Tap);
854
855 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
856 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
857 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
858
859 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
860 assert_eq!(get_input["url"], "http://h/x");
861 assert!(get_input["body"].is_null());
862
863 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
864 assert_eq!(post_input["url"], "http://h/y");
865 assert_eq!(post_input["body"], "hello");
866 }
867
868 #[test]
869 fn cx_pick_and_capture_photo_request_the_right_plugin() {
870 let mut cx = Cx::<Ev>::default();
871 cx.pick_photo(|_| Ev::Tap);
872 cx.capture_photo(|_| Ev::Tap);
873 assert_eq!(cx.requests.len(), 2);
874 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", ""));
877 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", ""));
878 }
879
880 #[test]
881 fn cx_capture_photo_routes_success_and_cancel() {
882 let mut cx = Cx::<Ev>::default();
884 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
885 let (_, then) = cx.requests.pop().unwrap();
886 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
887
888 let mut cx = Cx::<Ev>::default();
890 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
891 let (_, then) = cx.requests.pop().unwrap();
892 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
893 }
894
895 #[test]
896 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
897 let mut cx = Cx::<Ev>::default();
898 cx.copy("c");
899 cx.share("s");
900 cx.open_url("u");
901 cx.toast("t");
902 cx.haptic("heavy");
903 let got: Vec<(&str, &str, &str)> = cx
904 .notifications
905 .iter()
906 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
907 .collect();
908 assert_eq!(
909 got,
910 vec![
911 ("clipboard", "copy", "c"),
912 ("share", "text", "s"),
913 ("browser", "open", "u"),
914 ("toast", "show", "t"),
915 ("haptics", "heavy", ""), ]
917 );
918 assert!(cx.requests.is_empty());
919 }
920
921 #[test]
922 fn cx_device_model_is_a_request_not_a_notification() {
923 let mut cx = Cx::<Ev>::default();
924 cx.device_model(|_| Ev::Tap);
925 assert!(cx.notifications.is_empty());
926 assert_eq!(cx.requests.len(), 1);
927 let (call, _) = &cx.requests[0];
928 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
929 }
930
931 #[test]
932 fn cx_confirm_serializes_title_message_and_routes_ok() {
933 let mut cx = Cx::<Ev>::default();
934 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
935 let (call, then) = cx.requests.pop().unwrap();
936 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
937 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
938 assert_eq!(v["title"], "Delete?");
939 assert_eq!(v["message"], "This cannot be undone.");
940 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
942 }
943
944 #[test]
947 fn text_builders_carry_their_style() {
948 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
949 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
950 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
951 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
952 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
953 }
954
955 #[test]
956 fn layout_and_content_builders_produce_their_variants() {
957 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
958 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
959 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
960 assert!(matches!(divider(), Widget::Divider));
961 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, values, .. } if values.len() == 2));
962 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
963 assert!(matches!(
965 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
966 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
967 ));
968 assert!(matches!(
969 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
970 Widget::SwipeAction { actions, .. } if actions.len() == 1
971 ));
972 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
973 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
974 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
975 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
976 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
977 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
979 }
980
981 #[test]
982 fn input_builders_carry_ids_values_and_event_tokens() {
983 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { .. }));
984 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
985 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
986 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
987
988 match chip("Latte", true, Ev::Open(2)) {
989 Widget::Chip { selected, on_press, .. } => {
990 assert!(selected);
991 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
992 }
993 other => panic!("expected Chip, got {other:?}"),
994 }
995 match stepper(5, Ev::Tap, Ev::Open(1)) {
996 Widget::Stepper { value, on_decrement, on_increment } => {
997 assert_eq!(value, 5);
998 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
999 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1000 }
1001 other => panic!("expected Stepper, got {other:?}"),
1002 }
1003 let t = tab("Home", true, Ev::Tap);
1004 assert_eq!(t.label, "Home");
1005 assert!(t.selected);
1006 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1007 }
1008
1009 #[test]
1012 fn widget_tree_round_trips_through_serde() {
1013 let tree = scaffold(
1014 "Home",
1015 true,
1016 vec![tab("A", true, Ev::Tap)],
1017 column(vec![
1018 title("Hi"),
1019 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1020 image("u", ImageShape::Rounded, ImageRatio::Wide),
1021 slider("s", 2, 5),
1022 ]),
1023 );
1024 let s = serde_json::to_string(&tree).unwrap();
1025 let back: Widget = serde_json::from_str(&s).unwrap();
1026 assert_eq!(s, serde_json::to_string(&back).unwrap());
1027 }
1028
1029 #[test]
1030 fn actions_and_input_values_round_trip() {
1031 let actions = vec![
1032 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1033 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1034 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1035 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1036 Action::Restore { data: "blob".into() },
1037 Action::Start,
1038 ];
1039 for a in actions {
1040 let s = serde_json::to_string(&a).unwrap();
1041 let back: Action = serde_json::from_str(&s).unwrap();
1042 assert_eq!(s, serde_json::to_string(&back).unwrap());
1043 }
1044 }
1045
1046 #[derive(Default)]
1049 struct CounterModel {
1050 count: i32,
1051 restored: String,
1052 started: bool,
1053 last_input: String,
1054 }
1055
1056 #[derive(serde::Serialize, serde::Deserialize)]
1057 enum CounterEv {
1058 Inc,
1059 Add(i32),
1060 }
1061
1062 #[derive(Default)]
1063 struct CounterApp;
1064
1065 impl MobilerApp for CounterApp {
1066 type Event = CounterEv;
1067 type Model = CounterModel;
1068 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1069 match ev {
1070 CounterEv::Inc => model.count += 1,
1071 CounterEv::Add(n) => model.count += n,
1072 }
1073 }
1074 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1075 if let InputValue::Text(t) = value {
1076 model.last_input = format!("{id}={t}");
1077 }
1078 }
1079 fn restore(&self, data: &str, model: &mut CounterModel) {
1080 model.restored = data.to_string();
1081 }
1082 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1083 model.started = true;
1084 }
1085 fn view(&self, model: &CounterModel) -> Widget {
1086 text(format!("{}", model.count))
1087 }
1088 }
1089
1090 #[test]
1091 fn shell_dispatches_fired_input_restore_and_start() {
1092 use crux_core::App as _;
1093 let shell = MobilerShell::<CounterApp>::default();
1094 let mut m = CounterModel::default();
1095
1096 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1098 assert_eq!(m.count, 5);
1099 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1101 assert_eq!(m.last_input, "name=bob");
1102 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1104 assert_eq!(m.restored, "saved");
1105 let _ = shell.update(Action::Start, &mut m);
1107 assert!(m.started);
1108 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1110 }
1111
1112 #[test]
1113 fn shell_ignores_a_malformed_fired_token() {
1114 use crux_core::App as _;
1115 let shell = MobilerShell::<CounterApp>::default();
1116 let mut m = CounterModel::default();
1117 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1120 assert_eq!(m.count, 0);
1121 }
1122}