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 pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
184 self.plugin("photo", "pick", "", then);
185 }
186
187 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
194 self.plugin("camera", "capture", "", then);
195 }
196
197 pub fn confirm(
201 &mut self,
202 title: impl Into<String>,
203 message: impl Into<String>,
204 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
205 ) {
206 #[derive(Serialize)]
207 struct Confirm {
208 title: String,
209 message: String,
210 }
211 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
212 .expect("serialize confirm");
213 self.plugin("dialog", "confirm", input, then);
214 }
215
216 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
221 self.plugin("datetime", "date", "", then);
222 }
223
224 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
229 self.plugin("datetime", "time", "", then);
230 }
231}
232
233pub trait MobilerApp: Default {
238 type Event: Serialize + DeserializeOwned + Send + 'static;
239 type Model: Default;
240
241 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
242
243 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
244 let _ = (id, value, model, cx);
245 }
246
247 fn restore(&self, data: &str, model: &mut Self::Model) {
250 let _ = (data, model);
251 }
252
253 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
256 let _ = (model, cx);
257 }
258
259 fn view(&self, model: &Self::Model) -> Widget;
260}
261
262pub struct MobilerShell<A>(PhantomData<fn() -> A>);
264
265impl<A> Default for MobilerShell<A> {
266 fn default() -> Self {
267 Self(PhantomData)
268 }
269}
270
271impl<A: MobilerApp> App for MobilerShell<A> {
272 type Event = Action;
273 type Model = A::Model;
274 type ViewModel = Widget;
275 type Effect = Effect;
276
277 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
278 let app = A::default();
279 let mut cx = Cx::<A::Event>::default();
280 match action {
281 Action::Fired { token } => {
282 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
283 app.update(event, model, &mut cx);
284 }
285 }
286 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
287 Action::Restore { data } => app.restore(&data, model),
288 Action::Start => app.init(model, &mut cx),
289 }
290 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
291 for op in cx.notifications {
292 commands.push(Command::notify_shell(op).build());
293 }
294 for (op, then) in cx.requests {
295 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
296 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
297 }));
298 }
299 commands.push(render());
300 Command::all(commands)
301 }
302
303 fn view(&self, model: &Self::Model) -> Widget {
304 A::default().view(model)
305 }
306}
307
308#[derive(Clone, Debug)]
327pub struct Nav<R> {
328 stack: Vec<R>,
329}
330
331impl<R: Clone + Serialize> Nav<R> {
332 #[must_use]
334 pub fn new(root: R) -> Self {
335 Self { stack: vec![root] }
336 }
337 pub fn push(&mut self, route: R) {
339 self.stack.push(route);
340 }
341 pub fn pop(&mut self) {
343 if self.stack.len() > 1 {
344 self.stack.pop();
345 }
346 }
347 pub fn reset(&mut self, root: R) {
349 self.stack = vec![root];
350 }
351 #[must_use]
353 pub fn current(&self) -> &R {
354 self.stack.last().expect("nav stack is never empty")
355 }
356 #[must_use]
358 pub fn depth(&self) -> u32 {
359 self.stack.len() as u32
360 }
361 #[must_use]
363 pub fn can_go_back(&self) -> bool {
364 self.stack.len() > 1
365 }
366 fn route_key(&self) -> String {
369 serde_json::to_string(self.current()).expect("serialize route")
370 }
371}
372
373fn tok<E: Serialize>(event: E) -> String {
377 serde_json::to_string(&event).expect("serialize event")
378}
379
380#[must_use]
381pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
382 Widget::Text { content: content.into(), style }
383}
384#[must_use]
385pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
386#[must_use]
387pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
388#[must_use]
389pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
390#[must_use]
391pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
392#[must_use]
393pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
394
395#[must_use]
396pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
397 Widget::Image { source: source.into(), shape, ratio }
398}
399#[must_use]
400pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
401 Widget::Badge { label: label.into(), tone }
402}
403#[must_use]
405pub fn color_dot(color: ProjectColor) -> Widget {
406 Widget::ColorDot { color }
407}
408#[must_use]
409pub fn divider() -> Widget { Widget::Divider }
410#[must_use]
412pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
413#[must_use]
415pub fn skeleton() -> Widget { Widget::Skeleton }
416fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
418 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
419}
420
421#[must_use]
424pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
425 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
426}
427#[must_use]
430pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
431 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
432}
433#[must_use]
437pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
438 Widget::Chart { series, labels, style, axis, legend }
439}
440#[must_use]
442pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
443 chart(series, labels, ChartStyle::StackedBar, true, true)
444}
445#[must_use]
447pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
448 chart(series, labels, ChartStyle::StackedBar100, false, true)
449}
450#[must_use]
452pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
453 chart(series, vec![], ChartStyle::Pie, false, true)
454}
455#[must_use]
457pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
458 chart(series, vec![], ChartStyle::Donut, false, true)
459}
460#[must_use]
463pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
464 chart(series, vec![], ChartStyle::Rings, false, true)
465}
466#[must_use]
468pub fn gauge_chart(series: ChartSeries) -> Widget {
469 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
470}
471
472#[must_use]
477pub fn region_chart(
478 regions: Vec<ChartRegion>,
479 ticks: Vec<ChartTick>,
480 x_max: f32,
481 y_max: f32,
482 ref_lines: Vec<ChartRefLine>,
483 legend: Vec<ChartLegendItem>,
484) -> Widget {
485 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
486}
487
488#[must_use]
490pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
491 match widget {
492 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
493 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
494 }
495 other => other,
496 }
497}
498
499fn days_in_month(year: u32, month: u8) -> u8 {
501 match month {
502 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
503 4 | 6 | 9 | 11 => 30,
504 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
505 _ => 30,
506 }
507}
508
509fn weekday(year: u32, month: u8, day: u8) -> u8 {
511 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
512 let y = if month < 3 { year - 1 } else { year };
513 let m = month as usize - 1;
514 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
515}
516
517#[must_use]
521pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
522 let n = days_in_month(year, month);
523 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
524 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
525}
526
527#[must_use]
530pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
531 Widget::SwipeAction {
532 child: Box::new(child),
533 actions: actions
534 .into_iter()
535 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
536 .collect(),
537 }
538}
539#[must_use]
540pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
541
542#[must_use]
543pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
544#[must_use]
545pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
546#[must_use]
547pub fn card(child: Widget, style: CardStyle) -> Widget {
548 Widget::Card { child: Box::new(child), style, on_press: None }
549}
550#[must_use]
552pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
553 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
554}
555#[must_use]
558pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
559 Widget::Box { children, align, scrim }
560}
561#[must_use]
562pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
563#[must_use]
565pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
566#[must_use]
568pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
569#[must_use]
571pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
572 Widget::Avatar { source: source.into(), status: Some(status) }
573}
574#[must_use]
576pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
577#[must_use]
579pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
580 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
581}
582
583#[must_use]
584pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
585 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
586}
587#[must_use]
588pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
589 Widget::IconButton { icon, on_press: tok(on_press) }
590}
591#[must_use]
592pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
593 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
594}
595#[must_use]
596pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
597 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
598}
599#[must_use]
603pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
604 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
605}
606#[must_use]
608pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
609 field(id, placeholder, value, FieldKind::Secure, None)
610}
611#[must_use]
613pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
614 field(id, placeholder, value, FieldKind::Email, None)
615}
616#[must_use]
618pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
619 field(id, placeholder, value, FieldKind::Number, None)
620}
621#[must_use]
623pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
624 field(id, placeholder, value, FieldKind::Decimal, None)
625}
626#[must_use]
628pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
629 field(id, placeholder, value, FieldKind::Phone, None)
630}
631#[must_use]
633pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
634 field(id, placeholder, value, FieldKind::Url, None)
635}
636#[must_use]
638pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
639 field(id, placeholder, value, FieldKind::Multiline, None)
640}
641#[must_use]
644pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
645 match widget {
646 Widget::TextField { id, placeholder, value, kind, .. } =>
647 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
648 other => other,
649 }
650}
651#[must_use]
653pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
654 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
655}
656#[must_use]
658pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
659 Segment { label: label.into(), selected, on_select: tok(on_select) }
660}
661#[must_use]
663pub fn segmented(segments: Vec<Segment>) -> Widget {
664 Widget::Segmented { segments }
665}
666#[must_use]
667pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
668 Widget::Toggle { id: id.into(), label: label.into(), value }
669}
670#[must_use]
671pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
672 Widget::Checkbox { id: id.into(), label: label.into(), value }
673}
674#[must_use]
675pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
676 Widget::Slider { id: id.into(), value, max }
677}
678#[must_use]
679pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
680 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
681}
682
683#[must_use]
685pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
686 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
687}
688
689#[must_use]
691pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
692 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
693}
694
695#[must_use]
698pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
699 let title = title.into();
700 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 }
702}
703
704#[must_use]
708pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
709 let title = title.into();
710 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 }
711}
712
713#[must_use]
718pub fn nav_scaffold<R, E>(
719 title: impl Into<String>,
720 dark_mode: bool,
721 tabs: Vec<Tab>,
722 body: Widget,
723 nav: &Nav<R>,
724 on_back: E,
725) -> Widget
726where
727 R: Clone + Serialize,
728 E: Serialize,
729{
730 Widget::Scaffold {
731 title: title.into(),
732 body: Box::new(body),
733 tabs,
734 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
735 dark_mode,
736 theme: None,
737 fab: None,
738 sheet: None,
739 on_refresh: None,
740 refreshing: false,
741 route: nav.route_key(),
742 depth: nav.depth(),
743 }
744}
745
746pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
750 match widget {
751 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
752 title,
753 body,
754 tabs,
755 back,
756 dark_mode,
757 theme: Some(theme),
758 fab,
759 sheet,
760 on_refresh,
761 refreshing,
762 route,
763 depth,
764 },
765 other => other,
766 }
767}
768
769pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
772 match widget {
773 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
774 title,
775 body,
776 tabs,
777 back,
778 dark_mode,
779 theme,
780 fab: Some(Fab { icon, on_press: tok(on_press) }),
781 sheet,
782 on_refresh,
783 refreshing,
784 route,
785 depth,
786 },
787 other => other,
788 }
789}
790
791pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
794 match widget {
795 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
796 title: t,
797 body,
798 tabs,
799 back,
800 dark_mode,
801 theme,
802 fab,
803 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
804 on_refresh,
805 refreshing,
806 route,
807 depth,
808 },
809 other => other,
810 }
811}
812
813pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
817 match widget {
818 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
819 title,
820 body,
821 tabs,
822 back,
823 dark_mode,
824 theme,
825 fab,
826 sheet,
827 on_refresh: Some(tok(on_refresh)),
828 refreshing,
829 route,
830 depth,
831 },
832 other => other,
833 }
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839 use serde::Serialize;
840
841 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
842 enum Route {
843 Home,
844 Detail(u32),
845 }
846
847 #[derive(Serialize)]
848 enum Ev {
849 Tap,
850 Open(u32),
851 }
852
853 #[test]
856 fn nav_push_pop_depth() {
857 let mut nav = Nav::new(Route::Home);
858 assert_eq!(nav.depth(), 1);
859 assert!(!nav.can_go_back());
860
861 nav.push(Route::Detail(7));
862 assert_eq!(nav.depth(), 2);
863 assert!(nav.can_go_back());
864 assert!(matches!(nav.current(), Route::Detail(7)));
865
866 nav.pop();
867 assert_eq!(nav.depth(), 1);
868 assert!(matches!(nav.current(), Route::Home));
869
870 nav.pop(); assert_eq!(nav.depth(), 1);
872 }
873
874 #[test]
875 fn nav_reset_replaces_stack() {
876 let mut nav = Nav::new(Route::Home);
877 nav.push(Route::Detail(1));
878 nav.push(Route::Detail(2));
879 nav.reset(Route::Detail(9));
880 assert_eq!(nav.depth(), 1);
881 assert!(matches!(nav.current(), Route::Detail(9)));
882 }
883
884 #[test]
885 fn nav_route_key_is_serialization() {
886 let nav = Nav::new(Route::Detail(3));
887 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
888 }
889
890 #[test]
893 fn scaffold_sets_route_depth_and_no_back() {
894 match scaffold("Home", false, vec![], text("x")) {
895 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
896 assert_eq!(route, "Home");
897 assert_eq!(depth, 1);
898 assert!(back.is_none());
899 assert!(!dark_mode);
900 }
901 other => panic!("expected Scaffold, got {other:?}"),
902 }
903 }
904
905 #[test]
906 fn scaffold_back_is_depth_2_with_back() {
907 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
908 Widget::Scaffold { depth, back, dark_mode, .. } => {
909 assert_eq!(depth, 2);
910 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
911 assert!(dark_mode);
912 }
913 other => panic!("expected Scaffold, got {other:?}"),
914 }
915 }
916
917 #[test]
918 fn nav_scaffold_shows_back_only_when_poppable() {
919 let mut nav = Nav::new(Route::Home);
920 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
922 Widget::Scaffold { back, depth, route, .. } => {
923 assert!(back.is_none());
924 assert_eq!(depth, 1);
925 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
926 }
927 other => panic!("expected Scaffold, got {other:?}"),
928 }
929 nav.push(Route::Detail(2));
931 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
932 Widget::Scaffold { back, depth, .. } => {
933 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
934 assert_eq!(depth, 2);
935 }
936 other => panic!("expected Scaffold, got {other:?}"),
937 }
938 }
939
940 #[test]
941 fn buttons_carry_serialized_event_tokens() {
942 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
943 Widget::Button { label, on_press, .. } => {
944 assert_eq!(label, "Go");
945 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
946 }
947 other => panic!("expected Button, got {other:?}"),
948 }
949 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
950 Widget::Card { on_press, .. } => {
951 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
952 }
953 other => panic!("expected Card, got {other:?}"),
954 }
955 match card(text("c"), CardStyle::Elevated) {
957 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
958 other => panic!("expected Card, got {other:?}"),
959 }
960 }
961
962 #[test]
965 fn cx_notify_and_save_enqueue_notifications() {
966 let mut cx = Cx::<Ev>::default();
967 cx.notify("toast", "show", "hi");
968 cx.save("blob");
969 assert_eq!(cx.notifications.len(), 2);
970 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
971 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
972 assert!(cx.requests.is_empty());
973 }
974
975 #[test]
976 fn cx_http_helpers_build_requests() {
977 let mut cx = Cx::<Ev>::default();
978 cx.get("http://h/x", |_| Ev::Tap);
979 cx.post("http://h/y", "hello", |_| Ev::Tap);
980 cx.patch("http://h/z", "patch", |_| Ev::Tap);
981 cx.delete("http://h/d", |_| Ev::Tap);
982
983 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
984 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
985 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
986
987 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
988 assert_eq!(get_input["url"], "http://h/x");
989 assert!(get_input["body"].is_null());
990
991 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
992 assert_eq!(post_input["url"], "http://h/y");
993 assert_eq!(post_input["body"], "hello");
994 }
995
996 #[test]
997 fn cx_pick_and_capture_photo_request_the_right_plugin() {
998 let mut cx = Cx::<Ev>::default();
999 cx.pick_photo(|_| Ev::Tap);
1000 cx.capture_photo(|_| Ev::Tap);
1001 assert_eq!(cx.requests.len(), 2);
1002 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", ""));
1005 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", ""));
1006 }
1007
1008 #[test]
1009 fn cx_capture_photo_routes_success_and_cancel() {
1010 let mut cx = Cx::<Ev>::default();
1012 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1013 let (_, then) = cx.requests.pop().unwrap();
1014 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1015
1016 let mut cx = Cx::<Ev>::default();
1018 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1019 let (_, then) = cx.requests.pop().unwrap();
1020 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1021 }
1022
1023 #[test]
1024 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1025 let mut cx = Cx::<Ev>::default();
1026 cx.copy("c");
1027 cx.share("s");
1028 cx.open_url("u");
1029 cx.toast("t");
1030 cx.haptic("heavy");
1031 let got: Vec<(&str, &str, &str)> = cx
1032 .notifications
1033 .iter()
1034 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1035 .collect();
1036 assert_eq!(
1037 got,
1038 vec![
1039 ("clipboard", "copy", "c"),
1040 ("share", "text", "s"),
1041 ("browser", "open", "u"),
1042 ("toast", "show", "t"),
1043 ("haptics", "heavy", ""), ]
1045 );
1046 assert!(cx.requests.is_empty());
1047 }
1048
1049 #[test]
1050 fn cx_device_model_is_a_request_not_a_notification() {
1051 let mut cx = Cx::<Ev>::default();
1052 cx.device_model(|_| Ev::Tap);
1053 assert!(cx.notifications.is_empty());
1054 assert_eq!(cx.requests.len(), 1);
1055 let (call, _) = &cx.requests[0];
1056 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1057 }
1058
1059 #[test]
1060 fn cx_confirm_serializes_title_message_and_routes_ok() {
1061 let mut cx = Cx::<Ev>::default();
1062 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1063 let (call, then) = cx.requests.pop().unwrap();
1064 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1065 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1066 assert_eq!(v["title"], "Delete?");
1067 assert_eq!(v["message"], "This cannot be undone.");
1068 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1070 }
1071
1072 #[test]
1075 fn text_builders_carry_their_style() {
1076 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1077 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1078 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1079 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1080 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1081 }
1082
1083 #[test]
1084 fn layout_and_content_builders_produce_their_variants() {
1085 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1086 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1087 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1088 assert!(matches!(divider(), Widget::Divider));
1089 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1090 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1091 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1092 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)));
1093 let rc = with_bracket(
1094 region_chart(
1095 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1096 vec![ChartTick::new(3.0, "3 Mt.")],
1097 65.0, 80.0,
1098 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1099 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1100 ),
1101 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1102 );
1103 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1104 assert!(matches!(
1106 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1107 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1108 ));
1109 assert!(matches!(
1110 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1111 Widget::SwipeAction { actions, .. } if actions.len() == 1
1112 ));
1113 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1114 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1115 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1116 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1117 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1118 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1120 }
1121
1122 #[test]
1123 fn input_builders_carry_ids_values_and_event_tokens() {
1124 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1125 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1126 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1127 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1128 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1129 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1130 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1131 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1132 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1133
1134 match chip("Latte", true, Ev::Open(2)) {
1135 Widget::Chip { selected, on_press, .. } => {
1136 assert!(selected);
1137 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1138 }
1139 other => panic!("expected Chip, got {other:?}"),
1140 }
1141 match stepper(5, Ev::Tap, Ev::Open(1)) {
1142 Widget::Stepper { value, on_decrement, on_increment } => {
1143 assert_eq!(value, 5);
1144 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1145 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1146 }
1147 other => panic!("expected Stepper, got {other:?}"),
1148 }
1149 let t = tab("Home", true, Ev::Tap);
1150 assert_eq!(t.label, "Home");
1151 assert!(t.selected);
1152 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1153 }
1154
1155 #[test]
1158 fn widget_tree_round_trips_through_serde() {
1159 let tree = scaffold(
1160 "Home",
1161 true,
1162 vec![tab("A", true, Ev::Tap)],
1163 column(vec![
1164 title("Hi"),
1165 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1166 image("u", ImageShape::Rounded, ImageRatio::Wide),
1167 slider("s", 2, 5),
1168 ]),
1169 );
1170 let s = serde_json::to_string(&tree).unwrap();
1171 let back: Widget = serde_json::from_str(&s).unwrap();
1172 assert_eq!(s, serde_json::to_string(&back).unwrap());
1173 }
1174
1175 #[test]
1176 fn actions_and_input_values_round_trip() {
1177 let actions = vec![
1178 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1179 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1180 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1181 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1182 Action::Restore { data: "blob".into() },
1183 Action::Start,
1184 ];
1185 for a in actions {
1186 let s = serde_json::to_string(&a).unwrap();
1187 let back: Action = serde_json::from_str(&s).unwrap();
1188 assert_eq!(s, serde_json::to_string(&back).unwrap());
1189 }
1190 }
1191
1192 #[derive(Default)]
1195 struct CounterModel {
1196 count: i32,
1197 restored: String,
1198 started: bool,
1199 last_input: String,
1200 }
1201
1202 #[derive(serde::Serialize, serde::Deserialize)]
1203 enum CounterEv {
1204 Inc,
1205 Add(i32),
1206 }
1207
1208 #[derive(Default)]
1209 struct CounterApp;
1210
1211 impl MobilerApp for CounterApp {
1212 type Event = CounterEv;
1213 type Model = CounterModel;
1214 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1215 match ev {
1216 CounterEv::Inc => model.count += 1,
1217 CounterEv::Add(n) => model.count += n,
1218 }
1219 }
1220 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1221 if let InputValue::Text(t) = value {
1222 model.last_input = format!("{id}={t}");
1223 }
1224 }
1225 fn restore(&self, data: &str, model: &mut CounterModel) {
1226 model.restored = data.to_string();
1227 }
1228 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1229 model.started = true;
1230 }
1231 fn view(&self, model: &CounterModel) -> Widget {
1232 text(format!("{}", model.count))
1233 }
1234 }
1235
1236 #[test]
1237 fn shell_dispatches_fired_input_restore_and_start() {
1238 use crux_core::App as _;
1239 let shell = MobilerShell::<CounterApp>::default();
1240 let mut m = CounterModel::default();
1241
1242 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1244 assert_eq!(m.count, 5);
1245 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1247 assert_eq!(m.last_input, "name=bob");
1248 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1250 assert_eq!(m.restored, "saved");
1251 let _ = shell.update(Action::Start, &mut m);
1253 assert!(m.started);
1254 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1256 }
1257
1258 #[test]
1259 fn shell_ignores_a_malformed_fired_token() {
1260 use crux_core::App as _;
1261 let shell = MobilerShell::<CounterApp>::default();
1262 let mut m = CounterModel::default();
1263 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1266 assert_eq!(m.count, 0);
1267 }
1268}