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 PluginStream(PluginStreamCall),
45}
46
47#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct PluginNotify {
49 pub plugin: String,
50 pub op: String,
51 pub input: String,
52}
53impl Operation for PluginNotify {
54 type Output = ();
55}
56
57#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
58pub struct PluginCall {
59 pub plugin: String,
60 pub op: String,
61 pub input: String,
62}
63impl Operation for PluginCall {
64 type Output = PluginResponse;
65}
66
67#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
71pub struct PluginStreamCall {
72 pub key: String,
73 pub plugin: String,
74 pub op: String,
75 pub input: String,
76}
77impl Operation for PluginStreamCall {
78 type Output = PluginResponse;
79}
80
81#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginResponse {
83 pub ok: bool,
84 pub output: String,
85}
86
87type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
88type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
90
91pub struct Cx<E> {
94 notifications: Vec<PluginNotify>,
95 requests: Vec<(PluginCall, Continuation<E>)>,
96 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
97}
98
99impl<E> Default for Cx<E> {
100 fn default() -> Self {
101 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
102 }
103}
104
105impl<E> Cx<E> {
106 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
108 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
109 }
110
111 pub fn plugin(
114 &mut self,
115 plugin: impl Into<String>,
116 op: impl Into<String>,
117 input: impl Into<String>,
118 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
119 ) {
120 self.requests
121 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
122 }
123
124 pub fn subscribe(
132 &mut self,
133 key: impl Into<String>,
134 plugin: impl Into<String>,
135 op: impl Into<String>,
136 input: impl Into<String>,
137 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
138 ) {
139 self.streams.push((
140 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
141 Box::new(on_event),
142 ));
143 }
144
145 pub fn unsubscribe(&mut self, key: impl Into<String>) {
149 self.notify("stream", "unsubscribe", key);
150 }
151
152 pub fn save(&mut self, data: impl Into<String>) {
154 self.notify("storage", "save", data);
155 }
156
157 pub fn copy(&mut self, text: impl Into<String>) {
159 self.notify("clipboard", "copy", text);
160 }
161
162 pub fn share(&mut self, text: impl Into<String>) {
164 self.notify("share", "text", text);
165 }
166
167 pub fn open_url(&mut self, url: impl Into<String>) {
170 self.notify("browser", "open", url);
171 }
172
173 pub fn toast(&mut self, text: impl Into<String>) {
175 self.notify("toast", "show", text);
176 }
177
178 pub fn haptic(&mut self, style: impl Into<String>) {
181 self.notify("haptics", style, "");
182 }
183
184 pub fn http(
189 &mut self,
190 method: impl Into<String>,
191 url: impl Into<String>,
192 body: Option<String>,
193 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
194 ) {
195 #[derive(Serialize)]
196 struct HttpReq {
197 url: String,
198 body: Option<String>,
199 }
200 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
201 .expect("serialize http request");
202 self.plugin("http", method, input, then);
203 }
204
205 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
207 self.http("GET", url, None, then);
208 }
209 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
211 self.http("POST", url, Some(body.into()), then);
212 }
213 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
215 self.http("PATCH", url, Some(body.into()), then);
216 }
217 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
219 self.http("DELETE", url, None, then);
220 }
221
222 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
226 self.plugin("device", "model", "", then);
227 }
228
229 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
234 self.plugin("device", "locale", "", then);
235 }
236
237 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
242 self.plugin("photo", "pick", "", then);
243 }
244
245 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
252 self.plugin("camera", "capture", "", then);
253 }
254
255 pub fn confirm(
259 &mut self,
260 title: impl Into<String>,
261 message: impl Into<String>,
262 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
263 ) {
264 #[derive(Serialize)]
265 struct Confirm {
266 title: String,
267 message: String,
268 }
269 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
270 .expect("serialize confirm");
271 self.plugin("dialog", "confirm", input, then);
272 }
273
274 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
279 self.plugin("datetime", "date", "", then);
280 }
281
282 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
287 self.plugin("datetime", "time", "", then);
288 }
289}
290
291pub trait MobilerApp: Default {
296 type Event: Serialize + DeserializeOwned + Send + 'static;
297 type Model: Default;
298
299 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
300
301 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
302 let _ = (id, value, model, cx);
303 }
304
305 fn restore(&self, data: &str, model: &mut Self::Model) {
308 let _ = (data, model);
309 }
310
311 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
314 let _ = (model, cx);
315 }
316
317 fn view(&self, model: &Self::Model) -> Widget;
318}
319
320pub struct MobilerShell<A>(PhantomData<fn() -> A>);
322
323impl<A> Default for MobilerShell<A> {
324 fn default() -> Self {
325 Self(PhantomData)
326 }
327}
328
329impl<A: MobilerApp> App for MobilerShell<A> {
330 type Event = Action;
331 type Model = A::Model;
332 type ViewModel = Widget;
333 type Effect = Effect;
334
335 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
336 let app = A::default();
337 let mut cx = Cx::<A::Event>::default();
338 match action {
339 Action::Fired { token } => {
340 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
341 app.update(event, model, &mut cx);
342 }
343 }
344 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
345 Action::Restore { data } => app.restore(&data, model),
346 Action::Start => app.init(model, &mut cx),
347 }
348 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
349 for op in cx.notifications {
350 commands.push(Command::notify_shell(op).build());
351 }
352 for (op, then) in cx.requests {
353 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
354 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
355 }));
356 }
357 for (op, then) in cx.streams {
358 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
361 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
362 }));
363 }
364 commands.push(render());
365 Command::all(commands)
366 }
367
368 fn view(&self, model: &Self::Model) -> Widget {
369 A::default().view(model)
370 }
371}
372
373#[derive(Clone, Debug)]
392pub struct Nav<R> {
393 stack: Vec<R>,
394}
395
396impl<R: Clone + Serialize> Nav<R> {
397 #[must_use]
399 pub fn new(root: R) -> Self {
400 Self { stack: vec![root] }
401 }
402 pub fn push(&mut self, route: R) {
404 self.stack.push(route);
405 }
406 pub fn pop(&mut self) {
408 if self.stack.len() > 1 {
409 self.stack.pop();
410 }
411 }
412 pub fn reset(&mut self, root: R) {
414 self.stack = vec![root];
415 }
416 #[must_use]
418 pub fn current(&self) -> &R {
419 self.stack.last().expect("nav stack is never empty")
420 }
421 #[must_use]
423 pub fn depth(&self) -> u32 {
424 self.stack.len() as u32
425 }
426 #[must_use]
428 pub fn can_go_back(&self) -> bool {
429 self.stack.len() > 1
430 }
431 fn route_key(&self) -> String {
434 serde_json::to_string(self.current()).expect("serialize route")
435 }
436}
437
438fn tok<E: Serialize>(event: E) -> String {
442 serde_json::to_string(&event).expect("serialize event")
443}
444
445#[must_use]
446pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
447 Widget::Text { content: content.into(), style }
448}
449#[must_use]
450pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
451#[must_use]
452pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
453#[must_use]
454pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
455#[must_use]
456pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
457#[must_use]
458pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
459
460#[must_use]
461pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
462 Widget::Image { source: source.into(), shape, ratio }
463}
464#[must_use]
465pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
466 Widget::Badge { label: label.into(), tone }
467}
468#[must_use]
470pub fn color_dot(color: ProjectColor) -> Widget {
471 Widget::ColorDot { color }
472}
473#[must_use]
474pub fn divider() -> Widget { Widget::Divider }
475#[must_use]
477pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
478#[must_use]
480pub fn skeleton() -> Widget { Widget::Skeleton }
481#[must_use]
485pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
486fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
488 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
489}
490
491#[must_use]
494pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
495 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
496}
497#[must_use]
500pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
501 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
502}
503#[must_use]
507pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
508 Widget::Chart { series, labels, style, axis, legend }
509}
510#[must_use]
512pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
513 chart(series, labels, ChartStyle::StackedBar, true, true)
514}
515#[must_use]
517pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
518 chart(series, labels, ChartStyle::StackedBar100, false, true)
519}
520#[must_use]
522pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
523 chart(series, vec![], ChartStyle::Pie, false, true)
524}
525#[must_use]
527pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
528 chart(series, vec![], ChartStyle::Donut, false, true)
529}
530#[must_use]
533pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
534 chart(series, vec![], ChartStyle::Rings, false, true)
535}
536#[must_use]
538pub fn gauge_chart(series: ChartSeries) -> Widget {
539 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
540}
541
542#[must_use]
547pub fn region_chart(
548 regions: Vec<ChartRegion>,
549 ticks: Vec<ChartTick>,
550 x_max: f32,
551 y_max: f32,
552 ref_lines: Vec<ChartRefLine>,
553 legend: Vec<ChartLegendItem>,
554) -> Widget {
555 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
556}
557
558#[must_use]
560pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
561 match widget {
562 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
563 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
564 }
565 other => other,
566 }
567}
568
569fn days_in_month(year: u32, month: u8) -> u8 {
571 match month {
572 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
573 4 | 6 | 9 | 11 => 30,
574 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
575 _ => 30,
576 }
577}
578
579fn weekday(year: u32, month: u8, day: u8) -> u8 {
581 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
582 let y = if month < 3 { year - 1 } else { year };
583 let m = month as usize - 1;
584 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
585}
586
587#[must_use]
591pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
592 let n = days_in_month(year, month);
593 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
594 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
595}
596
597#[must_use]
600pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
601 Widget::SwipeAction {
602 child: Box::new(child),
603 actions: actions
604 .into_iter()
605 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
606 .collect(),
607 }
608}
609#[must_use]
610pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
611
612#[must_use]
613pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
614#[must_use]
615pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
616#[must_use]
617pub fn card(child: Widget, style: CardStyle) -> Widget {
618 Widget::Card { child: Box::new(child), style, on_press: None }
619}
620#[must_use]
622pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
623 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
624}
625#[must_use]
628pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
629 Widget::Box { children, align, scrim }
630}
631#[must_use]
632pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
633#[must_use]
635pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
636#[must_use]
638pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
639#[must_use]
641pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
642 Widget::Avatar { source: source.into(), status: Some(status) }
643}
644#[must_use]
646pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
647#[must_use]
649pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
650 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
651}
652
653#[must_use]
654pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
655 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
656}
657#[must_use]
658pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
659 Widget::IconButton { icon, on_press: tok(on_press) }
660}
661#[must_use]
662pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
663 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
664}
665#[must_use]
666pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
667 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
668}
669#[must_use]
673pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
674 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
675}
676#[must_use]
678pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
679 field(id, placeholder, value, FieldKind::Secure, None)
680}
681#[must_use]
683pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
684 field(id, placeholder, value, FieldKind::Email, None)
685}
686#[must_use]
688pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
689 field(id, placeholder, value, FieldKind::Number, None)
690}
691#[must_use]
693pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
694 field(id, placeholder, value, FieldKind::Decimal, None)
695}
696#[must_use]
698pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
699 field(id, placeholder, value, FieldKind::Phone, None)
700}
701#[must_use]
703pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
704 field(id, placeholder, value, FieldKind::Url, None)
705}
706#[must_use]
708pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
709 field(id, placeholder, value, FieldKind::Multiline, None)
710}
711#[must_use]
714pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
715 match widget {
716 Widget::TextField { id, placeholder, value, kind, .. } =>
717 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
718 other => other,
719 }
720}
721#[must_use]
723pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
724 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
725}
726#[must_use]
728pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
729 Segment { label: label.into(), selected, on_select: tok(on_select) }
730}
731#[must_use]
733pub fn segmented(segments: Vec<Segment>) -> Widget {
734 Widget::Segmented { segments }
735}
736#[must_use]
737pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
738 Widget::Toggle { id: id.into(), label: label.into(), value }
739}
740#[must_use]
741pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
742 Widget::Checkbox { id: id.into(), label: label.into(), value }
743}
744#[must_use]
745pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
746 Widget::Slider { id: id.into(), value, max }
747}
748#[must_use]
749pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
750 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
751}
752
753#[must_use]
755pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
756 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
757}
758
759#[must_use]
761pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
762 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
763}
764
765#[must_use]
768pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
769 let title = title.into();
770 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 }
772}
773
774#[must_use]
778pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
779 let title = title.into();
780 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 }
781}
782
783#[must_use]
788pub fn nav_scaffold<R, E>(
789 title: impl Into<String>,
790 dark_mode: bool,
791 tabs: Vec<Tab>,
792 body: Widget,
793 nav: &Nav<R>,
794 on_back: E,
795) -> Widget
796where
797 R: Clone + Serialize,
798 E: Serialize,
799{
800 Widget::Scaffold {
801 title: title.into(),
802 body: Box::new(body),
803 tabs,
804 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
805 dark_mode,
806 theme: None,
807 fab: None,
808 sheet: None,
809 on_refresh: None,
810 refreshing: false,
811 route: nav.route_key(),
812 depth: nav.depth(),
813 }
814}
815
816pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
820 match widget {
821 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
822 title,
823 body,
824 tabs,
825 back,
826 dark_mode,
827 theme: Some(theme),
828 fab,
829 sheet,
830 on_refresh,
831 refreshing,
832 route,
833 depth,
834 },
835 other => other,
836 }
837}
838
839pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
842 match widget {
843 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
844 title,
845 body,
846 tabs,
847 back,
848 dark_mode,
849 theme,
850 fab: Some(Fab { icon, on_press: tok(on_press) }),
851 sheet,
852 on_refresh,
853 refreshing,
854 route,
855 depth,
856 },
857 other => other,
858 }
859}
860
861pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
864 match widget {
865 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
866 title: t,
867 body,
868 tabs,
869 back,
870 dark_mode,
871 theme,
872 fab,
873 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
874 on_refresh,
875 refreshing,
876 route,
877 depth,
878 },
879 other => other,
880 }
881}
882
883pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
887 match widget {
888 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
889 title,
890 body,
891 tabs,
892 back,
893 dark_mode,
894 theme,
895 fab,
896 sheet,
897 on_refresh: Some(tok(on_refresh)),
898 refreshing,
899 route,
900 depth,
901 },
902 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
905 children,
906 on_load_more,
907 loading,
908 has_more,
909 on_refresh: Some(tok(on_refresh)),
910 refreshing,
911 },
912 other => other,
913 }
914}
915
916#[must_use]
922pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
923 Widget::LazyList {
924 children,
925 on_load_more: Some(tok(on_load_more)),
926 loading,
927 has_more,
928 on_refresh: None,
929 refreshing: false,
930 }
931}
932
933#[must_use]
935pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
936 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
937}
938
939#[cfg(test)]
940mod tests {
941 use super::*;
942 use serde::Serialize;
943
944 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
945 enum Route {
946 Home,
947 Detail(u32),
948 }
949
950 #[derive(Serialize)]
951 enum Ev {
952 Tap,
953 Open(u32),
954 }
955
956 #[test]
959 fn nav_push_pop_depth() {
960 let mut nav = Nav::new(Route::Home);
961 assert_eq!(nav.depth(), 1);
962 assert!(!nav.can_go_back());
963
964 nav.push(Route::Detail(7));
965 assert_eq!(nav.depth(), 2);
966 assert!(nav.can_go_back());
967 assert!(matches!(nav.current(), Route::Detail(7)));
968
969 nav.pop();
970 assert_eq!(nav.depth(), 1);
971 assert!(matches!(nav.current(), Route::Home));
972
973 nav.pop(); assert_eq!(nav.depth(), 1);
975 }
976
977 #[test]
978 fn nav_reset_replaces_stack() {
979 let mut nav = Nav::new(Route::Home);
980 nav.push(Route::Detail(1));
981 nav.push(Route::Detail(2));
982 nav.reset(Route::Detail(9));
983 assert_eq!(nav.depth(), 1);
984 assert!(matches!(nav.current(), Route::Detail(9)));
985 }
986
987 #[test]
988 fn nav_route_key_is_serialization() {
989 let nav = Nav::new(Route::Detail(3));
990 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
991 }
992
993 #[test]
996 fn scaffold_sets_route_depth_and_no_back() {
997 match scaffold("Home", false, vec![], text("x")) {
998 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
999 assert_eq!(route, "Home");
1000 assert_eq!(depth, 1);
1001 assert!(back.is_none());
1002 assert!(!dark_mode);
1003 }
1004 other => panic!("expected Scaffold, got {other:?}"),
1005 }
1006 }
1007
1008 #[test]
1009 fn scaffold_back_is_depth_2_with_back() {
1010 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1011 Widget::Scaffold { depth, back, dark_mode, .. } => {
1012 assert_eq!(depth, 2);
1013 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1014 assert!(dark_mode);
1015 }
1016 other => panic!("expected Scaffold, got {other:?}"),
1017 }
1018 }
1019
1020 #[test]
1021 fn nav_scaffold_shows_back_only_when_poppable() {
1022 let mut nav = Nav::new(Route::Home);
1023 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1025 Widget::Scaffold { back, depth, route, .. } => {
1026 assert!(back.is_none());
1027 assert_eq!(depth, 1);
1028 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1029 }
1030 other => panic!("expected Scaffold, got {other:?}"),
1031 }
1032 nav.push(Route::Detail(2));
1034 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1035 Widget::Scaffold { back, depth, .. } => {
1036 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1037 assert_eq!(depth, 2);
1038 }
1039 other => panic!("expected Scaffold, got {other:?}"),
1040 }
1041 }
1042
1043 #[test]
1044 fn buttons_carry_serialized_event_tokens() {
1045 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1046 Widget::Button { label, on_press, .. } => {
1047 assert_eq!(label, "Go");
1048 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1049 }
1050 other => panic!("expected Button, got {other:?}"),
1051 }
1052 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1053 Widget::Card { on_press, .. } => {
1054 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1055 }
1056 other => panic!("expected Card, got {other:?}"),
1057 }
1058 match card(text("c"), CardStyle::Elevated) {
1060 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
1061 other => panic!("expected Card, got {other:?}"),
1062 }
1063 }
1064
1065 #[test]
1068 fn cx_notify_and_save_enqueue_notifications() {
1069 let mut cx = Cx::<Ev>::default();
1070 cx.notify("toast", "show", "hi");
1071 cx.save("blob");
1072 assert_eq!(cx.notifications.len(), 2);
1073 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1074 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1075 assert!(cx.requests.is_empty());
1076 }
1077
1078 #[test]
1079 fn cx_http_helpers_build_requests() {
1080 let mut cx = Cx::<Ev>::default();
1081 cx.get("http://h/x", |_| Ev::Tap);
1082 cx.post("http://h/y", "hello", |_| Ev::Tap);
1083 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1084 cx.delete("http://h/d", |_| Ev::Tap);
1085
1086 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1087 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1088 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1089
1090 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1091 assert_eq!(get_input["url"], "http://h/x");
1092 assert!(get_input["body"].is_null());
1093
1094 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1095 assert_eq!(post_input["url"], "http://h/y");
1096 assert_eq!(post_input["body"], "hello");
1097 }
1098
1099 #[test]
1100 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1101 let mut cx = Cx::<Ev>::default();
1102 cx.pick_photo(|_| Ev::Tap);
1103 cx.capture_photo(|_| Ev::Tap);
1104 assert_eq!(cx.requests.len(), 2);
1105 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", ""));
1108 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", ""));
1109 }
1110
1111 #[test]
1112 fn cx_capture_photo_routes_success_and_cancel() {
1113 let mut cx = Cx::<Ev>::default();
1115 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1116 let (_, then) = cx.requests.pop().unwrap();
1117 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1118
1119 let mut cx = Cx::<Ev>::default();
1121 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1122 let (_, then) = cx.requests.pop().unwrap();
1123 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1124 }
1125
1126 #[test]
1127 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1128 let mut cx = Cx::<Ev>::default();
1129 cx.copy("c");
1130 cx.share("s");
1131 cx.open_url("u");
1132 cx.toast("t");
1133 cx.haptic("heavy");
1134 let got: Vec<(&str, &str, &str)> = cx
1135 .notifications
1136 .iter()
1137 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1138 .collect();
1139 assert_eq!(
1140 got,
1141 vec![
1142 ("clipboard", "copy", "c"),
1143 ("share", "text", "s"),
1144 ("browser", "open", "u"),
1145 ("toast", "show", "t"),
1146 ("haptics", "heavy", ""), ]
1148 );
1149 assert!(cx.requests.is_empty());
1150 }
1151
1152 #[test]
1153 fn cx_device_model_is_a_request_not_a_notification() {
1154 let mut cx = Cx::<Ev>::default();
1155 cx.device_model(|_| Ev::Tap);
1156 assert!(cx.notifications.is_empty());
1157 assert_eq!(cx.requests.len(), 1);
1158 let (call, _) = &cx.requests[0];
1159 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1160 }
1161
1162 #[test]
1163 fn cx_device_locale_requests_the_device_locale_op() {
1164 let mut cx = Cx::<Ev>::default();
1165 cx.device_locale(|_| Ev::Tap);
1166 assert!(cx.notifications.is_empty());
1167 assert_eq!(cx.requests.len(), 1);
1168 let (call, _) = &cx.requests[0];
1169 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1170 }
1171
1172 #[test]
1173 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1174 let mut cx = Cx::<Ev>::default();
1175 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1176 assert!(cx.notifications.is_empty());
1178 assert!(cx.requests.is_empty());
1179 assert_eq!(cx.streams.len(), 1);
1180 let (call, on_event) = &cx.streams[0];
1181 assert_eq!(
1182 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1183 ("ws", "websocket", "stream", "wss://h/x")
1184 );
1185 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1187 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1188 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1189 }
1190
1191 #[test]
1192 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1193 let mut cx = Cx::<Ev>::default();
1194 cx.unsubscribe("ws");
1195 assert!(cx.streams.is_empty());
1196 assert_eq!(cx.notifications.len(), 1);
1197 assert_eq!(
1199 cx.notifications[0],
1200 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1201 );
1202 }
1203
1204 #[test]
1205 fn cx_confirm_serializes_title_message_and_routes_ok() {
1206 let mut cx = Cx::<Ev>::default();
1207 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1208 let (call, then) = cx.requests.pop().unwrap();
1209 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1210 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1211 assert_eq!(v["title"], "Delete?");
1212 assert_eq!(v["message"], "This cannot be undone.");
1213 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1215 }
1216
1217 #[test]
1220 fn text_builders_carry_their_style() {
1221 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1222 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1223 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1224 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1225 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1226 }
1227
1228 #[test]
1229 fn layout_and_content_builders_produce_their_variants() {
1230 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1231 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1232 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1233 assert!(matches!(divider(), Widget::Divider));
1234 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1235 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1236 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1237 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)));
1238 let rc = with_bracket(
1239 region_chart(
1240 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1241 vec![ChartTick::new(3.0, "3 Mt.")],
1242 65.0, 80.0,
1243 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1244 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1245 ),
1246 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1247 );
1248 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1249 assert!(matches!(
1251 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1252 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1253 ));
1254 assert!(matches!(
1255 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1256 Widget::SwipeAction { actions, .. } if actions.len() == 1
1257 ));
1258 assert!(matches!(
1260 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1261 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1262 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1263 ));
1264 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1265 assert!(matches!(
1267 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1268 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1269 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1270 ));
1271 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1272 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1273 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1274 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1275 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1276 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1278 }
1279
1280 #[test]
1281 fn input_builders_carry_ids_values_and_event_tokens() {
1282 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1283 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1284 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1285 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1286 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1287 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1288 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1289 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1290 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1291 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1292
1293 match chip("Latte", true, Ev::Open(2)) {
1294 Widget::Chip { selected, on_press, .. } => {
1295 assert!(selected);
1296 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1297 }
1298 other => panic!("expected Chip, got {other:?}"),
1299 }
1300 match stepper(5, Ev::Tap, Ev::Open(1)) {
1301 Widget::Stepper { value, on_decrement, on_increment } => {
1302 assert_eq!(value, 5);
1303 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1304 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1305 }
1306 other => panic!("expected Stepper, got {other:?}"),
1307 }
1308 let t = tab("Home", true, Ev::Tap);
1309 assert_eq!(t.label, "Home");
1310 assert!(t.selected);
1311 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1312 }
1313
1314 #[test]
1317 fn widget_tree_round_trips_through_serde() {
1318 let tree = scaffold(
1319 "Home",
1320 true,
1321 vec![tab("A", true, Ev::Tap)],
1322 column(vec![
1323 title("Hi"),
1324 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1325 image("u", ImageShape::Rounded, ImageRatio::Wide),
1326 slider("s", 2, 5),
1327 ]),
1328 );
1329 let s = serde_json::to_string(&tree).unwrap();
1330 let back: Widget = serde_json::from_str(&s).unwrap();
1331 assert_eq!(s, serde_json::to_string(&back).unwrap());
1332 }
1333
1334 #[test]
1335 fn actions_and_input_values_round_trip() {
1336 let actions = vec![
1337 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1338 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1339 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1340 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1341 Action::Restore { data: "blob".into() },
1342 Action::Start,
1343 ];
1344 for a in actions {
1345 let s = serde_json::to_string(&a).unwrap();
1346 let back: Action = serde_json::from_str(&s).unwrap();
1347 assert_eq!(s, serde_json::to_string(&back).unwrap());
1348 }
1349 }
1350
1351 #[derive(Default)]
1354 struct CounterModel {
1355 count: i32,
1356 restored: String,
1357 started: bool,
1358 last_input: String,
1359 }
1360
1361 #[derive(serde::Serialize, serde::Deserialize)]
1362 enum CounterEv {
1363 Inc,
1364 Add(i32),
1365 }
1366
1367 #[derive(Default)]
1368 struct CounterApp;
1369
1370 impl MobilerApp for CounterApp {
1371 type Event = CounterEv;
1372 type Model = CounterModel;
1373 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1374 match ev {
1375 CounterEv::Inc => model.count += 1,
1376 CounterEv::Add(n) => model.count += n,
1377 }
1378 }
1379 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1380 if let InputValue::Text(t) = value {
1381 model.last_input = format!("{id}={t}");
1382 }
1383 }
1384 fn restore(&self, data: &str, model: &mut CounterModel) {
1385 model.restored = data.to_string();
1386 }
1387 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1388 model.started = true;
1389 }
1390 fn view(&self, model: &CounterModel) -> Widget {
1391 text(format!("{}", model.count))
1392 }
1393 }
1394
1395 #[test]
1396 fn shell_dispatches_fired_input_restore_and_start() {
1397 use crux_core::App as _;
1398 let shell = MobilerShell::<CounterApp>::default();
1399 let mut m = CounterModel::default();
1400
1401 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1403 assert_eq!(m.count, 5);
1404 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1406 assert_eq!(m.last_input, "name=bob");
1407 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1409 assert_eq!(m.restored, "saved");
1410 let _ = shell.update(Action::Start, &mut m);
1412 assert!(m.started);
1413 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1415 }
1416
1417 #[test]
1418 fn shell_ignores_a_malformed_fired_token() {
1419 use crux_core::App as _;
1420 let shell = MobilerShell::<CounterApp>::default();
1421 let mut m = CounterModel::default();
1422 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1425 assert_eq!(m.count, 0);
1426 }
1427}