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