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 }
424#[must_use]
428pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
429fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
431 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
432}
433
434#[must_use]
437pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
438 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
439}
440#[must_use]
443pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
444 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
445}
446#[must_use]
450pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
451 Widget::Chart { series, labels, style, axis, legend }
452}
453#[must_use]
455pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
456 chart(series, labels, ChartStyle::StackedBar, true, true)
457}
458#[must_use]
460pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
461 chart(series, labels, ChartStyle::StackedBar100, false, true)
462}
463#[must_use]
465pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
466 chart(series, vec![], ChartStyle::Pie, false, true)
467}
468#[must_use]
470pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
471 chart(series, vec![], ChartStyle::Donut, false, true)
472}
473#[must_use]
476pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
477 chart(series, vec![], ChartStyle::Rings, false, true)
478}
479#[must_use]
481pub fn gauge_chart(series: ChartSeries) -> Widget {
482 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
483}
484
485#[must_use]
490pub fn region_chart(
491 regions: Vec<ChartRegion>,
492 ticks: Vec<ChartTick>,
493 x_max: f32,
494 y_max: f32,
495 ref_lines: Vec<ChartRefLine>,
496 legend: Vec<ChartLegendItem>,
497) -> Widget {
498 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
499}
500
501#[must_use]
503pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
504 match widget {
505 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
506 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
507 }
508 other => other,
509 }
510}
511
512fn days_in_month(year: u32, month: u8) -> u8 {
514 match month {
515 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
516 4 | 6 | 9 | 11 => 30,
517 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
518 _ => 30,
519 }
520}
521
522fn weekday(year: u32, month: u8, day: u8) -> u8 {
524 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
525 let y = if month < 3 { year - 1 } else { year };
526 let m = month as usize - 1;
527 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
528}
529
530#[must_use]
534pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
535 let n = days_in_month(year, month);
536 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
537 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
538}
539
540#[must_use]
543pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
544 Widget::SwipeAction {
545 child: Box::new(child),
546 actions: actions
547 .into_iter()
548 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
549 .collect(),
550 }
551}
552#[must_use]
553pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
554
555#[must_use]
556pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
557#[must_use]
558pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
559#[must_use]
560pub fn card(child: Widget, style: CardStyle) -> Widget {
561 Widget::Card { child: Box::new(child), style, on_press: None }
562}
563#[must_use]
565pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
566 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
567}
568#[must_use]
571pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
572 Widget::Box { children, align, scrim }
573}
574#[must_use]
575pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
576#[must_use]
578pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
579#[must_use]
581pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
582#[must_use]
584pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
585 Widget::Avatar { source: source.into(), status: Some(status) }
586}
587#[must_use]
589pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
590#[must_use]
592pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
593 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
594}
595
596#[must_use]
597pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
598 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
599}
600#[must_use]
601pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
602 Widget::IconButton { icon, on_press: tok(on_press) }
603}
604#[must_use]
605pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
606 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
607}
608#[must_use]
609pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
610 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
611}
612#[must_use]
616pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
617 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
618}
619#[must_use]
621pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
622 field(id, placeholder, value, FieldKind::Secure, None)
623}
624#[must_use]
626pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
627 field(id, placeholder, value, FieldKind::Email, None)
628}
629#[must_use]
631pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
632 field(id, placeholder, value, FieldKind::Number, None)
633}
634#[must_use]
636pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
637 field(id, placeholder, value, FieldKind::Decimal, None)
638}
639#[must_use]
641pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
642 field(id, placeholder, value, FieldKind::Phone, None)
643}
644#[must_use]
646pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
647 field(id, placeholder, value, FieldKind::Url, None)
648}
649#[must_use]
651pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
652 field(id, placeholder, value, FieldKind::Multiline, None)
653}
654#[must_use]
657pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
658 match widget {
659 Widget::TextField { id, placeholder, value, kind, .. } =>
660 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
661 other => other,
662 }
663}
664#[must_use]
666pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
667 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
668}
669#[must_use]
671pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
672 Segment { label: label.into(), selected, on_select: tok(on_select) }
673}
674#[must_use]
676pub fn segmented(segments: Vec<Segment>) -> Widget {
677 Widget::Segmented { segments }
678}
679#[must_use]
680pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
681 Widget::Toggle { id: id.into(), label: label.into(), value }
682}
683#[must_use]
684pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
685 Widget::Checkbox { id: id.into(), label: label.into(), value }
686}
687#[must_use]
688pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
689 Widget::Slider { id: id.into(), value, max }
690}
691#[must_use]
692pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
693 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
694}
695
696#[must_use]
698pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
699 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
700}
701
702#[must_use]
704pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
705 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
706}
707
708#[must_use]
711pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
712 let title = title.into();
713 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 }
715}
716
717#[must_use]
721pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
722 let title = title.into();
723 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 }
724}
725
726#[must_use]
731pub fn nav_scaffold<R, E>(
732 title: impl Into<String>,
733 dark_mode: bool,
734 tabs: Vec<Tab>,
735 body: Widget,
736 nav: &Nav<R>,
737 on_back: E,
738) -> Widget
739where
740 R: Clone + Serialize,
741 E: Serialize,
742{
743 Widget::Scaffold {
744 title: title.into(),
745 body: Box::new(body),
746 tabs,
747 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
748 dark_mode,
749 theme: None,
750 fab: None,
751 sheet: None,
752 on_refresh: None,
753 refreshing: false,
754 route: nav.route_key(),
755 depth: nav.depth(),
756 }
757}
758
759pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
763 match widget {
764 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
765 title,
766 body,
767 tabs,
768 back,
769 dark_mode,
770 theme: Some(theme),
771 fab,
772 sheet,
773 on_refresh,
774 refreshing,
775 route,
776 depth,
777 },
778 other => other,
779 }
780}
781
782pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
785 match widget {
786 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
787 title,
788 body,
789 tabs,
790 back,
791 dark_mode,
792 theme,
793 fab: Some(Fab { icon, on_press: tok(on_press) }),
794 sheet,
795 on_refresh,
796 refreshing,
797 route,
798 depth,
799 },
800 other => other,
801 }
802}
803
804pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
807 match widget {
808 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
809 title: t,
810 body,
811 tabs,
812 back,
813 dark_mode,
814 theme,
815 fab,
816 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
817 on_refresh,
818 refreshing,
819 route,
820 depth,
821 },
822 other => other,
823 }
824}
825
826pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
830 match widget {
831 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
832 title,
833 body,
834 tabs,
835 back,
836 dark_mode,
837 theme,
838 fab,
839 sheet,
840 on_refresh: Some(tok(on_refresh)),
841 refreshing,
842 route,
843 depth,
844 },
845 other => other,
846 }
847}
848
849#[cfg(test)]
850mod tests {
851 use super::*;
852 use serde::Serialize;
853
854 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
855 enum Route {
856 Home,
857 Detail(u32),
858 }
859
860 #[derive(Serialize)]
861 enum Ev {
862 Tap,
863 Open(u32),
864 }
865
866 #[test]
869 fn nav_push_pop_depth() {
870 let mut nav = Nav::new(Route::Home);
871 assert_eq!(nav.depth(), 1);
872 assert!(!nav.can_go_back());
873
874 nav.push(Route::Detail(7));
875 assert_eq!(nav.depth(), 2);
876 assert!(nav.can_go_back());
877 assert!(matches!(nav.current(), Route::Detail(7)));
878
879 nav.pop();
880 assert_eq!(nav.depth(), 1);
881 assert!(matches!(nav.current(), Route::Home));
882
883 nav.pop(); assert_eq!(nav.depth(), 1);
885 }
886
887 #[test]
888 fn nav_reset_replaces_stack() {
889 let mut nav = Nav::new(Route::Home);
890 nav.push(Route::Detail(1));
891 nav.push(Route::Detail(2));
892 nav.reset(Route::Detail(9));
893 assert_eq!(nav.depth(), 1);
894 assert!(matches!(nav.current(), Route::Detail(9)));
895 }
896
897 #[test]
898 fn nav_route_key_is_serialization() {
899 let nav = Nav::new(Route::Detail(3));
900 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
901 }
902
903 #[test]
906 fn scaffold_sets_route_depth_and_no_back() {
907 match scaffold("Home", false, vec![], text("x")) {
908 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
909 assert_eq!(route, "Home");
910 assert_eq!(depth, 1);
911 assert!(back.is_none());
912 assert!(!dark_mode);
913 }
914 other => panic!("expected Scaffold, got {other:?}"),
915 }
916 }
917
918 #[test]
919 fn scaffold_back_is_depth_2_with_back() {
920 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
921 Widget::Scaffold { depth, back, dark_mode, .. } => {
922 assert_eq!(depth, 2);
923 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
924 assert!(dark_mode);
925 }
926 other => panic!("expected Scaffold, got {other:?}"),
927 }
928 }
929
930 #[test]
931 fn nav_scaffold_shows_back_only_when_poppable() {
932 let mut nav = Nav::new(Route::Home);
933 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
935 Widget::Scaffold { back, depth, route, .. } => {
936 assert!(back.is_none());
937 assert_eq!(depth, 1);
938 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
939 }
940 other => panic!("expected Scaffold, got {other:?}"),
941 }
942 nav.push(Route::Detail(2));
944 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
945 Widget::Scaffold { back, depth, .. } => {
946 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
947 assert_eq!(depth, 2);
948 }
949 other => panic!("expected Scaffold, got {other:?}"),
950 }
951 }
952
953 #[test]
954 fn buttons_carry_serialized_event_tokens() {
955 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
956 Widget::Button { label, on_press, .. } => {
957 assert_eq!(label, "Go");
958 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
959 }
960 other => panic!("expected Button, got {other:?}"),
961 }
962 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
963 Widget::Card { on_press, .. } => {
964 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
965 }
966 other => panic!("expected Card, got {other:?}"),
967 }
968 match card(text("c"), CardStyle::Elevated) {
970 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
971 other => panic!("expected Card, got {other:?}"),
972 }
973 }
974
975 #[test]
978 fn cx_notify_and_save_enqueue_notifications() {
979 let mut cx = Cx::<Ev>::default();
980 cx.notify("toast", "show", "hi");
981 cx.save("blob");
982 assert_eq!(cx.notifications.len(), 2);
983 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
984 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
985 assert!(cx.requests.is_empty());
986 }
987
988 #[test]
989 fn cx_http_helpers_build_requests() {
990 let mut cx = Cx::<Ev>::default();
991 cx.get("http://h/x", |_| Ev::Tap);
992 cx.post("http://h/y", "hello", |_| Ev::Tap);
993 cx.patch("http://h/z", "patch", |_| Ev::Tap);
994 cx.delete("http://h/d", |_| Ev::Tap);
995
996 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
997 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
998 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
999
1000 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1001 assert_eq!(get_input["url"], "http://h/x");
1002 assert!(get_input["body"].is_null());
1003
1004 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1005 assert_eq!(post_input["url"], "http://h/y");
1006 assert_eq!(post_input["body"], "hello");
1007 }
1008
1009 #[test]
1010 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1011 let mut cx = Cx::<Ev>::default();
1012 cx.pick_photo(|_| Ev::Tap);
1013 cx.capture_photo(|_| Ev::Tap);
1014 assert_eq!(cx.requests.len(), 2);
1015 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", ""));
1018 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", ""));
1019 }
1020
1021 #[test]
1022 fn cx_capture_photo_routes_success_and_cancel() {
1023 let mut cx = Cx::<Ev>::default();
1025 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1026 let (_, then) = cx.requests.pop().unwrap();
1027 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1028
1029 let mut cx = Cx::<Ev>::default();
1031 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1032 let (_, then) = cx.requests.pop().unwrap();
1033 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1034 }
1035
1036 #[test]
1037 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1038 let mut cx = Cx::<Ev>::default();
1039 cx.copy("c");
1040 cx.share("s");
1041 cx.open_url("u");
1042 cx.toast("t");
1043 cx.haptic("heavy");
1044 let got: Vec<(&str, &str, &str)> = cx
1045 .notifications
1046 .iter()
1047 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1048 .collect();
1049 assert_eq!(
1050 got,
1051 vec![
1052 ("clipboard", "copy", "c"),
1053 ("share", "text", "s"),
1054 ("browser", "open", "u"),
1055 ("toast", "show", "t"),
1056 ("haptics", "heavy", ""), ]
1058 );
1059 assert!(cx.requests.is_empty());
1060 }
1061
1062 #[test]
1063 fn cx_device_model_is_a_request_not_a_notification() {
1064 let mut cx = Cx::<Ev>::default();
1065 cx.device_model(|_| Ev::Tap);
1066 assert!(cx.notifications.is_empty());
1067 assert_eq!(cx.requests.len(), 1);
1068 let (call, _) = &cx.requests[0];
1069 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1070 }
1071
1072 #[test]
1073 fn cx_device_locale_requests_the_device_locale_op() {
1074 let mut cx = Cx::<Ev>::default();
1075 cx.device_locale(|_| Ev::Tap);
1076 assert!(cx.notifications.is_empty());
1077 assert_eq!(cx.requests.len(), 1);
1078 let (call, _) = &cx.requests[0];
1079 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1080 }
1081
1082 #[test]
1083 fn cx_confirm_serializes_title_message_and_routes_ok() {
1084 let mut cx = Cx::<Ev>::default();
1085 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1086 let (call, then) = cx.requests.pop().unwrap();
1087 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1088 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1089 assert_eq!(v["title"], "Delete?");
1090 assert_eq!(v["message"], "This cannot be undone.");
1091 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1093 }
1094
1095 #[test]
1098 fn text_builders_carry_their_style() {
1099 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1100 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1101 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1102 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1103 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1104 }
1105
1106 #[test]
1107 fn layout_and_content_builders_produce_their_variants() {
1108 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1109 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1110 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1111 assert!(matches!(divider(), Widget::Divider));
1112 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1113 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1114 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1115 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)));
1116 let rc = with_bracket(
1117 region_chart(
1118 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1119 vec![ChartTick::new(3.0, "3 Mt.")],
1120 65.0, 80.0,
1121 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1122 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1123 ),
1124 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1125 );
1126 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1127 assert!(matches!(
1129 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1130 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1131 ));
1132 assert!(matches!(
1133 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1134 Widget::SwipeAction { actions, .. } if actions.len() == 1
1135 ));
1136 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1137 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1138 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1139 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1140 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1141 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1143 }
1144
1145 #[test]
1146 fn input_builders_carry_ids_values_and_event_tokens() {
1147 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1148 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1149 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1150 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1151 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1152 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1153 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1154 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1155 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1156 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1157
1158 match chip("Latte", true, Ev::Open(2)) {
1159 Widget::Chip { selected, on_press, .. } => {
1160 assert!(selected);
1161 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1162 }
1163 other => panic!("expected Chip, got {other:?}"),
1164 }
1165 match stepper(5, Ev::Tap, Ev::Open(1)) {
1166 Widget::Stepper { value, on_decrement, on_increment } => {
1167 assert_eq!(value, 5);
1168 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1169 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1170 }
1171 other => panic!("expected Stepper, got {other:?}"),
1172 }
1173 let t = tab("Home", true, Ev::Tap);
1174 assert_eq!(t.label, "Home");
1175 assert!(t.selected);
1176 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1177 }
1178
1179 #[test]
1182 fn widget_tree_round_trips_through_serde() {
1183 let tree = scaffold(
1184 "Home",
1185 true,
1186 vec![tab("A", true, Ev::Tap)],
1187 column(vec![
1188 title("Hi"),
1189 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1190 image("u", ImageShape::Rounded, ImageRatio::Wide),
1191 slider("s", 2, 5),
1192 ]),
1193 );
1194 let s = serde_json::to_string(&tree).unwrap();
1195 let back: Widget = serde_json::from_str(&s).unwrap();
1196 assert_eq!(s, serde_json::to_string(&back).unwrap());
1197 }
1198
1199 #[test]
1200 fn actions_and_input_values_round_trip() {
1201 let actions = vec![
1202 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1203 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1204 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1205 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1206 Action::Restore { data: "blob".into() },
1207 Action::Start,
1208 ];
1209 for a in actions {
1210 let s = serde_json::to_string(&a).unwrap();
1211 let back: Action = serde_json::from_str(&s).unwrap();
1212 assert_eq!(s, serde_json::to_string(&back).unwrap());
1213 }
1214 }
1215
1216 #[derive(Default)]
1219 struct CounterModel {
1220 count: i32,
1221 restored: String,
1222 started: bool,
1223 last_input: String,
1224 }
1225
1226 #[derive(serde::Serialize, serde::Deserialize)]
1227 enum CounterEv {
1228 Inc,
1229 Add(i32),
1230 }
1231
1232 #[derive(Default)]
1233 struct CounterApp;
1234
1235 impl MobilerApp for CounterApp {
1236 type Event = CounterEv;
1237 type Model = CounterModel;
1238 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1239 match ev {
1240 CounterEv::Inc => model.count += 1,
1241 CounterEv::Add(n) => model.count += n,
1242 }
1243 }
1244 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1245 if let InputValue::Text(t) = value {
1246 model.last_input = format!("{id}={t}");
1247 }
1248 }
1249 fn restore(&self, data: &str, model: &mut CounterModel) {
1250 model.restored = data.to_string();
1251 }
1252 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1253 model.started = true;
1254 }
1255 fn view(&self, model: &CounterModel) -> Widget {
1256 text(format!("{}", model.count))
1257 }
1258 }
1259
1260 #[test]
1261 fn shell_dispatches_fired_input_restore_and_start() {
1262 use crux_core::App as _;
1263 let shell = MobilerShell::<CounterApp>::default();
1264 let mut m = CounterModel::default();
1265
1266 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1268 assert_eq!(m.count, 5);
1269 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1271 assert_eq!(m.last_input, "name=bob");
1272 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1274 assert_eq!(m.restored, "saved");
1275 let _ = shell.update(Action::Start, &mut m);
1277 assert!(m.started);
1278 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1280 }
1281
1282 #[test]
1283 fn shell_ignores_a_malformed_fired_token() {
1284 use crux_core::App as _;
1285 let shell = MobilerShell::<CounterApp>::default();
1286 let mut m = CounterModel::default();
1287 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1290 assert_eq!(m.count, 0);
1291 }
1292}