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