1use std::marker::PhantomData;
9
10pub mod format;
11pub use format::{Currency, Locale};
12
13use crux_core::{
14 App, Command,
15 capability::Operation,
16 macros::effect,
17 render::{RenderOperation, render},
18};
19use facet::Facet;
20use serde::{Deserialize, Serialize, de::DeserializeOwned};
21
22pub use mobiler_ui::{
23 Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
24 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
25 ImageRatio, ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
26 TextStyle, Theme, Tone, Widget,
27};
28
29#[effect(facet_typegen)]
33#[derive(Debug)]
34pub enum Effect {
35 Render(RenderOperation),
36 PluginNotify(PluginNotify),
38 Plugin(PluginCall),
40}
41
42#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
43pub struct PluginNotify {
44 pub plugin: String,
45 pub op: String,
46 pub input: String,
47}
48impl Operation for PluginNotify {
49 type Output = ();
50}
51
52#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
53pub struct PluginCall {
54 pub plugin: String,
55 pub op: String,
56 pub input: String,
57}
58impl Operation for PluginCall {
59 type Output = PluginResponse;
60}
61
62#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
63pub struct PluginResponse {
64 pub ok: bool,
65 pub output: String,
66}
67
68type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
69
70pub struct Cx<E> {
73 notifications: Vec<PluginNotify>,
74 requests: Vec<(PluginCall, Continuation<E>)>,
75}
76
77impl<E> Default for Cx<E> {
78 fn default() -> Self {
79 Self { notifications: Vec::new(), requests: Vec::new() }
80 }
81}
82
83impl<E> Cx<E> {
84 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
86 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
87 }
88
89 pub fn plugin(
92 &mut self,
93 plugin: impl Into<String>,
94 op: impl Into<String>,
95 input: impl Into<String>,
96 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
97 ) {
98 self.requests
99 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
100 }
101
102 pub fn save(&mut self, data: impl Into<String>) {
104 self.notify("storage", "save", data);
105 }
106
107 pub fn copy(&mut self, text: impl Into<String>) {
109 self.notify("clipboard", "copy", text);
110 }
111
112 pub fn share(&mut self, text: impl Into<String>) {
114 self.notify("share", "text", text);
115 }
116
117 pub fn open_url(&mut self, url: impl Into<String>) {
120 self.notify("browser", "open", url);
121 }
122
123 pub fn toast(&mut self, text: impl Into<String>) {
125 self.notify("toast", "show", text);
126 }
127
128 pub fn haptic(&mut self, style: impl Into<String>) {
131 self.notify("haptics", style, "");
132 }
133
134 pub fn http(
139 &mut self,
140 method: impl Into<String>,
141 url: impl Into<String>,
142 body: Option<String>,
143 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
144 ) {
145 #[derive(Serialize)]
146 struct HttpReq {
147 url: String,
148 body: Option<String>,
149 }
150 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
151 .expect("serialize http request");
152 self.plugin("http", method, input, then);
153 }
154
155 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
157 self.http("GET", url, None, then);
158 }
159 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
161 self.http("POST", url, Some(body.into()), then);
162 }
163 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
165 self.http("PATCH", url, Some(body.into()), then);
166 }
167 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
169 self.http("DELETE", url, None, then);
170 }
171
172 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
176 self.plugin("device", "model", "", then);
177 }
178
179 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
184 self.plugin("device", "locale", "", then);
185 }
186
187 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
192 self.plugin("photo", "pick", "", then);
193 }
194
195 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
202 self.plugin("camera", "capture", "", then);
203 }
204
205 pub fn confirm(
209 &mut self,
210 title: impl Into<String>,
211 message: impl Into<String>,
212 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
213 ) {
214 #[derive(Serialize)]
215 struct Confirm {
216 title: String,
217 message: String,
218 }
219 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
220 .expect("serialize confirm");
221 self.plugin("dialog", "confirm", input, then);
222 }
223
224 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
229 self.plugin("datetime", "date", "", then);
230 }
231
232 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
237 self.plugin("datetime", "time", "", then);
238 }
239}
240
241pub trait MobilerApp: Default {
246 type Event: Serialize + DeserializeOwned + Send + 'static;
247 type Model: Default;
248
249 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
250
251 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
252 let _ = (id, value, model, cx);
253 }
254
255 fn restore(&self, data: &str, model: &mut Self::Model) {
258 let _ = (data, model);
259 }
260
261 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
264 let _ = (model, cx);
265 }
266
267 fn view(&self, model: &Self::Model) -> Widget;
268}
269
270pub struct MobilerShell<A>(PhantomData<fn() -> A>);
272
273impl<A> Default for MobilerShell<A> {
274 fn default() -> Self {
275 Self(PhantomData)
276 }
277}
278
279impl<A: MobilerApp> App for MobilerShell<A> {
280 type Event = Action;
281 type Model = A::Model;
282 type ViewModel = Widget;
283 type Effect = Effect;
284
285 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
286 let app = A::default();
287 let mut cx = Cx::<A::Event>::default();
288 match action {
289 Action::Fired { token } => {
290 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
291 app.update(event, model, &mut cx);
292 }
293 }
294 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
295 Action::Restore { data } => app.restore(&data, model),
296 Action::Start => app.init(model, &mut cx),
297 }
298 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
299 for op in cx.notifications {
300 commands.push(Command::notify_shell(op).build());
301 }
302 for (op, then) in cx.requests {
303 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
304 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
305 }));
306 }
307 commands.push(render());
308 Command::all(commands)
309 }
310
311 fn view(&self, model: &Self::Model) -> Widget {
312 A::default().view(model)
313 }
314}
315
316#[derive(Clone, Debug)]
335pub struct Nav<R> {
336 stack: Vec<R>,
337}
338
339impl<R: Clone + Serialize> Nav<R> {
340 #[must_use]
342 pub fn new(root: R) -> Self {
343 Self { stack: vec![root] }
344 }
345 pub fn push(&mut self, route: R) {
347 self.stack.push(route);
348 }
349 pub fn pop(&mut self) {
351 if self.stack.len() > 1 {
352 self.stack.pop();
353 }
354 }
355 pub fn reset(&mut self, root: R) {
357 self.stack = vec![root];
358 }
359 #[must_use]
361 pub fn current(&self) -> &R {
362 self.stack.last().expect("nav stack is never empty")
363 }
364 #[must_use]
366 pub fn depth(&self) -> u32 {
367 self.stack.len() as u32
368 }
369 #[must_use]
371 pub fn can_go_back(&self) -> bool {
372 self.stack.len() > 1
373 }
374 fn route_key(&self) -> String {
377 serde_json::to_string(self.current()).expect("serialize route")
378 }
379}
380
381fn tok<E: Serialize>(event: E) -> String {
385 serde_json::to_string(&event).expect("serialize event")
386}
387
388#[must_use]
389pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
390 Widget::Text { content: content.into(), style }
391}
392#[must_use]
393pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
394#[must_use]
395pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
396#[must_use]
397pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
398#[must_use]
399pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
400#[must_use]
401pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
402
403#[must_use]
404pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
405 Widget::Image { source: source.into(), shape, ratio }
406}
407#[must_use]
408pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
409 Widget::Badge { label: label.into(), tone }
410}
411#[must_use]
413pub fn color_dot(color: ProjectColor) -> Widget {
414 Widget::ColorDot { color }
415}
416#[must_use]
417pub fn divider() -> Widget { Widget::Divider }
418#[must_use]
420pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
421#[must_use]
423pub fn skeleton() -> Widget { Widget::Skeleton }
424fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
426 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
427}
428
429#[must_use]
432pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
433 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
434}
435#[must_use]
438pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
439 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
440}
441#[must_use]
445pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
446 Widget::Chart { series, labels, style, axis, legend }
447}
448#[must_use]
450pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
451 chart(series, labels, ChartStyle::StackedBar, true, true)
452}
453#[must_use]
455pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
456 chart(series, labels, ChartStyle::StackedBar100, false, true)
457}
458#[must_use]
460pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
461 chart(series, vec![], ChartStyle::Pie, false, true)
462}
463#[must_use]
465pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
466 chart(series, vec![], ChartStyle::Donut, false, true)
467}
468#[must_use]
471pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
472 chart(series, vec![], ChartStyle::Rings, false, true)
473}
474#[must_use]
476pub fn gauge_chart(series: ChartSeries) -> Widget {
477 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
478}
479
480#[must_use]
485pub fn region_chart(
486 regions: Vec<ChartRegion>,
487 ticks: Vec<ChartTick>,
488 x_max: f32,
489 y_max: f32,
490 ref_lines: Vec<ChartRefLine>,
491 legend: Vec<ChartLegendItem>,
492) -> Widget {
493 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
494}
495
496#[must_use]
498pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
499 match widget {
500 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
501 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
502 }
503 other => other,
504 }
505}
506
507fn days_in_month(year: u32, month: u8) -> u8 {
509 match month {
510 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
511 4 | 6 | 9 | 11 => 30,
512 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
513 _ => 30,
514 }
515}
516
517fn weekday(year: u32, month: u8, day: u8) -> u8 {
519 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
520 let y = if month < 3 { year - 1 } else { year };
521 let m = month as usize - 1;
522 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
523}
524
525#[must_use]
529pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
530 let n = days_in_month(year, month);
531 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
532 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
533}
534
535#[must_use]
538pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
539 Widget::SwipeAction {
540 child: Box::new(child),
541 actions: actions
542 .into_iter()
543 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
544 .collect(),
545 }
546}
547#[must_use]
548pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
549
550#[must_use]
551pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
552#[must_use]
553pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
554#[must_use]
555pub fn card(child: Widget, style: CardStyle) -> Widget {
556 Widget::Card { child: Box::new(child), style, on_press: None }
557}
558#[must_use]
560pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
561 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
562}
563#[must_use]
566pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
567 Widget::Box { children, align, scrim }
568}
569#[must_use]
570pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
571#[must_use]
573pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
574#[must_use]
576pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
577#[must_use]
579pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
580 Widget::Avatar { source: source.into(), status: Some(status) }
581}
582#[must_use]
584pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
585#[must_use]
587pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
588 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
589}
590
591#[must_use]
592pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
593 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
594}
595#[must_use]
596pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
597 Widget::IconButton { icon, on_press: tok(on_press) }
598}
599#[must_use]
600pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
601 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
602}
603#[must_use]
604pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
605 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
606}
607#[must_use]
611pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
612 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
613}
614#[must_use]
616pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
617 field(id, placeholder, value, FieldKind::Secure, None)
618}
619#[must_use]
621pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
622 field(id, placeholder, value, FieldKind::Email, None)
623}
624#[must_use]
626pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
627 field(id, placeholder, value, FieldKind::Number, None)
628}
629#[must_use]
631pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
632 field(id, placeholder, value, FieldKind::Decimal, None)
633}
634#[must_use]
636pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
637 field(id, placeholder, value, FieldKind::Phone, None)
638}
639#[must_use]
641pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
642 field(id, placeholder, value, FieldKind::Url, None)
643}
644#[must_use]
646pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
647 field(id, placeholder, value, FieldKind::Multiline, None)
648}
649#[must_use]
652pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
653 match widget {
654 Widget::TextField { id, placeholder, value, kind, .. } =>
655 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
656 other => other,
657 }
658}
659#[must_use]
661pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
662 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
663}
664#[must_use]
666pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
667 Segment { label: label.into(), selected, on_select: tok(on_select) }
668}
669#[must_use]
671pub fn segmented(segments: Vec<Segment>) -> Widget {
672 Widget::Segmented { segments }
673}
674#[must_use]
675pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
676 Widget::Toggle { id: id.into(), label: label.into(), value }
677}
678#[must_use]
679pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
680 Widget::Checkbox { id: id.into(), label: label.into(), value }
681}
682#[must_use]
683pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
684 Widget::Slider { id: id.into(), value, max }
685}
686#[must_use]
687pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
688 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
689}
690
691#[must_use]
693pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
694 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
695}
696
697#[must_use]
699pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
700 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
701}
702
703#[must_use]
706pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
707 let title = title.into();
708 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 }
710}
711
712#[must_use]
716pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
717 let title = title.into();
718 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 }
719}
720
721#[must_use]
726pub fn nav_scaffold<R, E>(
727 title: impl Into<String>,
728 dark_mode: bool,
729 tabs: Vec<Tab>,
730 body: Widget,
731 nav: &Nav<R>,
732 on_back: E,
733) -> Widget
734where
735 R: Clone + Serialize,
736 E: Serialize,
737{
738 Widget::Scaffold {
739 title: title.into(),
740 body: Box::new(body),
741 tabs,
742 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
743 dark_mode,
744 theme: None,
745 fab: None,
746 sheet: None,
747 on_refresh: None,
748 refreshing: false,
749 route: nav.route_key(),
750 depth: nav.depth(),
751 }
752}
753
754pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
758 match widget {
759 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
760 title,
761 body,
762 tabs,
763 back,
764 dark_mode,
765 theme: Some(theme),
766 fab,
767 sheet,
768 on_refresh,
769 refreshing,
770 route,
771 depth,
772 },
773 other => other,
774 }
775}
776
777pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
780 match widget {
781 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
782 title,
783 body,
784 tabs,
785 back,
786 dark_mode,
787 theme,
788 fab: Some(Fab { icon, on_press: tok(on_press) }),
789 sheet,
790 on_refresh,
791 refreshing,
792 route,
793 depth,
794 },
795 other => other,
796 }
797}
798
799pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
802 match widget {
803 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
804 title: t,
805 body,
806 tabs,
807 back,
808 dark_mode,
809 theme,
810 fab,
811 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
812 on_refresh,
813 refreshing,
814 route,
815 depth,
816 },
817 other => other,
818 }
819}
820
821pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
825 match widget {
826 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
827 title,
828 body,
829 tabs,
830 back,
831 dark_mode,
832 theme,
833 fab,
834 sheet,
835 on_refresh: Some(tok(on_refresh)),
836 refreshing,
837 route,
838 depth,
839 },
840 other => other,
841 }
842}
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847 use serde::Serialize;
848
849 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
850 enum Route {
851 Home,
852 Detail(u32),
853 }
854
855 #[derive(Serialize)]
856 enum Ev {
857 Tap,
858 Open(u32),
859 }
860
861 #[test]
864 fn nav_push_pop_depth() {
865 let mut nav = Nav::new(Route::Home);
866 assert_eq!(nav.depth(), 1);
867 assert!(!nav.can_go_back());
868
869 nav.push(Route::Detail(7));
870 assert_eq!(nav.depth(), 2);
871 assert!(nav.can_go_back());
872 assert!(matches!(nav.current(), Route::Detail(7)));
873
874 nav.pop();
875 assert_eq!(nav.depth(), 1);
876 assert!(matches!(nav.current(), Route::Home));
877
878 nav.pop(); assert_eq!(nav.depth(), 1);
880 }
881
882 #[test]
883 fn nav_reset_replaces_stack() {
884 let mut nav = Nav::new(Route::Home);
885 nav.push(Route::Detail(1));
886 nav.push(Route::Detail(2));
887 nav.reset(Route::Detail(9));
888 assert_eq!(nav.depth(), 1);
889 assert!(matches!(nav.current(), Route::Detail(9)));
890 }
891
892 #[test]
893 fn nav_route_key_is_serialization() {
894 let nav = Nav::new(Route::Detail(3));
895 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
896 }
897
898 #[test]
901 fn scaffold_sets_route_depth_and_no_back() {
902 match scaffold("Home", false, vec![], text("x")) {
903 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
904 assert_eq!(route, "Home");
905 assert_eq!(depth, 1);
906 assert!(back.is_none());
907 assert!(!dark_mode);
908 }
909 other => panic!("expected Scaffold, got {other:?}"),
910 }
911 }
912
913 #[test]
914 fn scaffold_back_is_depth_2_with_back() {
915 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
916 Widget::Scaffold { depth, back, dark_mode, .. } => {
917 assert_eq!(depth, 2);
918 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
919 assert!(dark_mode);
920 }
921 other => panic!("expected Scaffold, got {other:?}"),
922 }
923 }
924
925 #[test]
926 fn nav_scaffold_shows_back_only_when_poppable() {
927 let mut nav = Nav::new(Route::Home);
928 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
930 Widget::Scaffold { back, depth, route, .. } => {
931 assert!(back.is_none());
932 assert_eq!(depth, 1);
933 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
934 }
935 other => panic!("expected Scaffold, got {other:?}"),
936 }
937 nav.push(Route::Detail(2));
939 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
940 Widget::Scaffold { back, depth, .. } => {
941 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
942 assert_eq!(depth, 2);
943 }
944 other => panic!("expected Scaffold, got {other:?}"),
945 }
946 }
947
948 #[test]
949 fn buttons_carry_serialized_event_tokens() {
950 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
951 Widget::Button { label, on_press, .. } => {
952 assert_eq!(label, "Go");
953 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
954 }
955 other => panic!("expected Button, got {other:?}"),
956 }
957 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
958 Widget::Card { on_press, .. } => {
959 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
960 }
961 other => panic!("expected Card, got {other:?}"),
962 }
963 match card(text("c"), CardStyle::Elevated) {
965 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
966 other => panic!("expected Card, got {other:?}"),
967 }
968 }
969
970 #[test]
973 fn cx_notify_and_save_enqueue_notifications() {
974 let mut cx = Cx::<Ev>::default();
975 cx.notify("toast", "show", "hi");
976 cx.save("blob");
977 assert_eq!(cx.notifications.len(), 2);
978 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
979 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
980 assert!(cx.requests.is_empty());
981 }
982
983 #[test]
984 fn cx_http_helpers_build_requests() {
985 let mut cx = Cx::<Ev>::default();
986 cx.get("http://h/x", |_| Ev::Tap);
987 cx.post("http://h/y", "hello", |_| Ev::Tap);
988 cx.patch("http://h/z", "patch", |_| Ev::Tap);
989 cx.delete("http://h/d", |_| Ev::Tap);
990
991 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
992 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
993 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
994
995 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
996 assert_eq!(get_input["url"], "http://h/x");
997 assert!(get_input["body"].is_null());
998
999 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1000 assert_eq!(post_input["url"], "http://h/y");
1001 assert_eq!(post_input["body"], "hello");
1002 }
1003
1004 #[test]
1005 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1006 let mut cx = Cx::<Ev>::default();
1007 cx.pick_photo(|_| Ev::Tap);
1008 cx.capture_photo(|_| Ev::Tap);
1009 assert_eq!(cx.requests.len(), 2);
1010 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", ""));
1013 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", ""));
1014 }
1015
1016 #[test]
1017 fn cx_capture_photo_routes_success_and_cancel() {
1018 let mut cx = Cx::<Ev>::default();
1020 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1021 let (_, then) = cx.requests.pop().unwrap();
1022 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1023
1024 let mut cx = Cx::<Ev>::default();
1026 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1027 let (_, then) = cx.requests.pop().unwrap();
1028 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1029 }
1030
1031 #[test]
1032 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1033 let mut cx = Cx::<Ev>::default();
1034 cx.copy("c");
1035 cx.share("s");
1036 cx.open_url("u");
1037 cx.toast("t");
1038 cx.haptic("heavy");
1039 let got: Vec<(&str, &str, &str)> = cx
1040 .notifications
1041 .iter()
1042 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1043 .collect();
1044 assert_eq!(
1045 got,
1046 vec![
1047 ("clipboard", "copy", "c"),
1048 ("share", "text", "s"),
1049 ("browser", "open", "u"),
1050 ("toast", "show", "t"),
1051 ("haptics", "heavy", ""), ]
1053 );
1054 assert!(cx.requests.is_empty());
1055 }
1056
1057 #[test]
1058 fn cx_device_model_is_a_request_not_a_notification() {
1059 let mut cx = Cx::<Ev>::default();
1060 cx.device_model(|_| Ev::Tap);
1061 assert!(cx.notifications.is_empty());
1062 assert_eq!(cx.requests.len(), 1);
1063 let (call, _) = &cx.requests[0];
1064 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1065 }
1066
1067 #[test]
1068 fn cx_device_locale_requests_the_device_locale_op() {
1069 let mut cx = Cx::<Ev>::default();
1070 cx.device_locale(|_| Ev::Tap);
1071 assert!(cx.notifications.is_empty());
1072 assert_eq!(cx.requests.len(), 1);
1073 let (call, _) = &cx.requests[0];
1074 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1075 }
1076
1077 #[test]
1078 fn cx_confirm_serializes_title_message_and_routes_ok() {
1079 let mut cx = Cx::<Ev>::default();
1080 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1081 let (call, then) = cx.requests.pop().unwrap();
1082 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1083 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1084 assert_eq!(v["title"], "Delete?");
1085 assert_eq!(v["message"], "This cannot be undone.");
1086 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1088 }
1089
1090 #[test]
1093 fn text_builders_carry_their_style() {
1094 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1095 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1096 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1097 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1098 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1099 }
1100
1101 #[test]
1102 fn layout_and_content_builders_produce_their_variants() {
1103 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1104 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1105 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1106 assert!(matches!(divider(), Widget::Divider));
1107 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1108 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1109 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1110 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)));
1111 let rc = with_bracket(
1112 region_chart(
1113 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1114 vec![ChartTick::new(3.0, "3 Mt.")],
1115 65.0, 80.0,
1116 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1117 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1118 ),
1119 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1120 );
1121 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1122 assert!(matches!(
1124 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1125 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1126 ));
1127 assert!(matches!(
1128 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1129 Widget::SwipeAction { actions, .. } if actions.len() == 1
1130 ));
1131 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1132 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1133 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1134 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1135 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1136 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1138 }
1139
1140 #[test]
1141 fn input_builders_carry_ids_values_and_event_tokens() {
1142 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1143 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1144 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1145 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1146 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1147 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1148 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1149 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1150 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1151
1152 match chip("Latte", true, Ev::Open(2)) {
1153 Widget::Chip { selected, on_press, .. } => {
1154 assert!(selected);
1155 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1156 }
1157 other => panic!("expected Chip, got {other:?}"),
1158 }
1159 match stepper(5, Ev::Tap, Ev::Open(1)) {
1160 Widget::Stepper { value, on_decrement, on_increment } => {
1161 assert_eq!(value, 5);
1162 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1163 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1164 }
1165 other => panic!("expected Stepper, got {other:?}"),
1166 }
1167 let t = tab("Home", true, Ev::Tap);
1168 assert_eq!(t.label, "Home");
1169 assert!(t.selected);
1170 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1171 }
1172
1173 #[test]
1176 fn widget_tree_round_trips_through_serde() {
1177 let tree = scaffold(
1178 "Home",
1179 true,
1180 vec![tab("A", true, Ev::Tap)],
1181 column(vec![
1182 title("Hi"),
1183 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1184 image("u", ImageShape::Rounded, ImageRatio::Wide),
1185 slider("s", 2, 5),
1186 ]),
1187 );
1188 let s = serde_json::to_string(&tree).unwrap();
1189 let back: Widget = serde_json::from_str(&s).unwrap();
1190 assert_eq!(s, serde_json::to_string(&back).unwrap());
1191 }
1192
1193 #[test]
1194 fn actions_and_input_values_round_trip() {
1195 let actions = vec![
1196 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1197 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1198 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1199 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1200 Action::Restore { data: "blob".into() },
1201 Action::Start,
1202 ];
1203 for a in actions {
1204 let s = serde_json::to_string(&a).unwrap();
1205 let back: Action = serde_json::from_str(&s).unwrap();
1206 assert_eq!(s, serde_json::to_string(&back).unwrap());
1207 }
1208 }
1209
1210 #[derive(Default)]
1213 struct CounterModel {
1214 count: i32,
1215 restored: String,
1216 started: bool,
1217 last_input: String,
1218 }
1219
1220 #[derive(serde::Serialize, serde::Deserialize)]
1221 enum CounterEv {
1222 Inc,
1223 Add(i32),
1224 }
1225
1226 #[derive(Default)]
1227 struct CounterApp;
1228
1229 impl MobilerApp for CounterApp {
1230 type Event = CounterEv;
1231 type Model = CounterModel;
1232 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1233 match ev {
1234 CounterEv::Inc => model.count += 1,
1235 CounterEv::Add(n) => model.count += n,
1236 }
1237 }
1238 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1239 if let InputValue::Text(t) = value {
1240 model.last_input = format!("{id}={t}");
1241 }
1242 }
1243 fn restore(&self, data: &str, model: &mut CounterModel) {
1244 model.restored = data.to_string();
1245 }
1246 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1247 model.started = true;
1248 }
1249 fn view(&self, model: &CounterModel) -> Widget {
1250 text(format!("{}", model.count))
1251 }
1252 }
1253
1254 #[test]
1255 fn shell_dispatches_fired_input_restore_and_start() {
1256 use crux_core::App as _;
1257 let shell = MobilerShell::<CounterApp>::default();
1258 let mut m = CounterModel::default();
1259
1260 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1262 assert_eq!(m.count, 5);
1263 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1265 assert_eq!(m.last_input, "name=bob");
1266 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1268 assert_eq!(m.restored, "saved");
1269 let _ = shell.update(Action::Start, &mut m);
1271 assert!(m.started);
1272 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1274 }
1275
1276 #[test]
1277 fn shell_ignores_a_malformed_fired_token() {
1278 use crux_core::App as _;
1279 let shell = MobilerShell::<CounterApp>::default();
1280 let mut m = CounterModel::default();
1281 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1284 assert_eq!(m.count, 0);
1285 }
1286}