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() } }
486#[must_use]
493pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
494 Widget::Video {
495 url: url.into(),
496 id: id.into(),
497 playing,
498 seek_to_ms,
499 controls: true,
500 looping: false,
501 muted: false,
502 on_ended: Some(tok(on_ended)),
503 }
504}
505#[must_use]
507pub fn with_loop(widget: Widget) -> Widget {
508 match widget {
509 Widget::Video { url, id, playing, seek_to_ms, controls, muted, on_ended, .. } =>
510 Widget::Video { url, id, playing, seek_to_ms, controls, looping: true, muted, on_ended },
511 other => other,
512 }
513}
514#[must_use]
516pub fn with_muted(widget: Widget) -> Widget {
517 match widget {
518 Widget::Video { url, id, playing, seek_to_ms, controls, looping, on_ended, .. } =>
519 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted: true, on_ended },
520 other => other,
521 }
522}
523#[must_use]
525pub fn without_controls(widget: Widget) -> Widget {
526 match widget {
527 Widget::Video { url, id, playing, seek_to_ms, looping, muted, on_ended, .. } =>
528 Widget::Video { url, id, playing, seek_to_ms, controls: false, looping, muted, on_ended },
529 other => other,
530 }
531}
532fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
534 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
535}
536
537#[must_use]
540pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
541 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
542}
543#[must_use]
546pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
547 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
548}
549#[must_use]
553pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
554 Widget::Chart { series, labels, style, axis, legend }
555}
556#[must_use]
558pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
559 chart(series, labels, ChartStyle::StackedBar, true, true)
560}
561#[must_use]
563pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
564 chart(series, labels, ChartStyle::StackedBar100, false, true)
565}
566#[must_use]
568pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
569 chart(series, vec![], ChartStyle::Pie, false, true)
570}
571#[must_use]
573pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
574 chart(series, vec![], ChartStyle::Donut, false, true)
575}
576#[must_use]
579pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
580 chart(series, vec![], ChartStyle::Rings, false, true)
581}
582#[must_use]
584pub fn gauge_chart(series: ChartSeries) -> Widget {
585 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
586}
587
588#[must_use]
593pub fn region_chart(
594 regions: Vec<ChartRegion>,
595 ticks: Vec<ChartTick>,
596 x_max: f32,
597 y_max: f32,
598 ref_lines: Vec<ChartRefLine>,
599 legend: Vec<ChartLegendItem>,
600) -> Widget {
601 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
602}
603
604#[must_use]
606pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
607 match widget {
608 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
609 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
610 }
611 other => other,
612 }
613}
614
615fn days_in_month(year: u32, month: u8) -> u8 {
617 match month {
618 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
619 4 | 6 | 9 | 11 => 30,
620 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
621 _ => 30,
622 }
623}
624
625fn weekday(year: u32, month: u8, day: u8) -> u8 {
627 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
628 let y = if month < 3 { year - 1 } else { year };
629 let m = month as usize - 1;
630 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
631}
632
633#[must_use]
637pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
638 let n = days_in_month(year, month);
639 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
640 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
641}
642
643#[must_use]
646pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
647 Widget::SwipeAction {
648 child: Box::new(child),
649 actions: actions
650 .into_iter()
651 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
652 .collect(),
653 }
654}
655#[must_use]
656pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
657
658#[must_use]
659pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
660#[must_use]
661pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
662#[must_use]
663pub fn card(child: Widget, style: CardStyle) -> Widget {
664 Widget::Card { child: Box::new(child), style, on_press: None }
665}
666#[must_use]
668pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
669 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
670}
671#[must_use]
674pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
675 Widget::Box { children, align, scrim }
676}
677#[must_use]
678pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
679#[must_use]
681pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
682#[must_use]
684pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
685#[must_use]
687pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
688 Widget::Avatar { source: source.into(), status: Some(status) }
689}
690#[must_use]
692pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
693#[must_use]
695pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
696 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
697}
698
699#[must_use]
700pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
701 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
702}
703#[must_use]
704pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
705 Widget::IconButton { icon, on_press: tok(on_press) }
706}
707#[must_use]
708pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
709 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
710}
711#[must_use]
712pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
713 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
714}
715#[must_use]
719pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
720 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
721}
722#[must_use]
724pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
725 field(id, placeholder, value, FieldKind::Secure, None)
726}
727#[must_use]
729pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
730 field(id, placeholder, value, FieldKind::Email, None)
731}
732#[must_use]
734pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
735 field(id, placeholder, value, FieldKind::Number, None)
736}
737#[must_use]
739pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
740 field(id, placeholder, value, FieldKind::Decimal, None)
741}
742#[must_use]
744pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
745 field(id, placeholder, value, FieldKind::Phone, None)
746}
747#[must_use]
749pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
750 field(id, placeholder, value, FieldKind::Url, None)
751}
752#[must_use]
754pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
755 field(id, placeholder, value, FieldKind::Multiline, None)
756}
757#[must_use]
760pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
761 match widget {
762 Widget::TextField { id, placeholder, value, kind, .. } =>
763 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
764 other => other,
765 }
766}
767#[must_use]
769pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
770 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
771}
772#[must_use]
774pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
775 Segment { label: label.into(), selected, on_select: tok(on_select) }
776}
777#[must_use]
779pub fn segmented(segments: Vec<Segment>) -> Widget {
780 Widget::Segmented { segments }
781}
782#[must_use]
783pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
784 Widget::Toggle { id: id.into(), label: label.into(), value }
785}
786#[must_use]
787pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
788 Widget::Checkbox { id: id.into(), label: label.into(), value }
789}
790#[must_use]
791pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
792 Widget::Slider { id: id.into(), value, max }
793}
794#[must_use]
795pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
796 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
797}
798
799#[must_use]
801pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
802 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
803}
804
805#[must_use]
807pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
808 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
809}
810
811#[must_use]
814pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
815 let title = title.into();
816 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 }
818}
819
820#[must_use]
824pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
825 let title = title.into();
826 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 }
827}
828
829#[must_use]
834pub fn nav_scaffold<R, E>(
835 title: impl Into<String>,
836 dark_mode: bool,
837 tabs: Vec<Tab>,
838 body: Widget,
839 nav: &Nav<R>,
840 on_back: E,
841) -> Widget
842where
843 R: Clone + Serialize,
844 E: Serialize,
845{
846 Widget::Scaffold {
847 title: title.into(),
848 body: Box::new(body),
849 tabs,
850 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
851 dark_mode,
852 theme: None,
853 fab: None,
854 sheet: None,
855 on_refresh: None,
856 refreshing: false,
857 route: nav.route_key(),
858 depth: nav.depth(),
859 }
860}
861
862pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
866 match widget {
867 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
868 title,
869 body,
870 tabs,
871 back,
872 dark_mode,
873 theme: Some(theme),
874 fab,
875 sheet,
876 on_refresh,
877 refreshing,
878 route,
879 depth,
880 },
881 other => other,
882 }
883}
884
885pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
888 match widget {
889 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
890 title,
891 body,
892 tabs,
893 back,
894 dark_mode,
895 theme,
896 fab: Some(Fab { icon, on_press: tok(on_press) }),
897 sheet,
898 on_refresh,
899 refreshing,
900 route,
901 depth,
902 },
903 other => other,
904 }
905}
906
907pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
910 match widget {
911 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
912 title: t,
913 body,
914 tabs,
915 back,
916 dark_mode,
917 theme,
918 fab,
919 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
920 on_refresh,
921 refreshing,
922 route,
923 depth,
924 },
925 other => other,
926 }
927}
928
929pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
933 match widget {
934 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
935 title,
936 body,
937 tabs,
938 back,
939 dark_mode,
940 theme,
941 fab,
942 sheet,
943 on_refresh: Some(tok(on_refresh)),
944 refreshing,
945 route,
946 depth,
947 },
948 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
951 children,
952 on_load_more,
953 loading,
954 has_more,
955 on_refresh: Some(tok(on_refresh)),
956 refreshing,
957 },
958 other => other,
959 }
960}
961
962#[must_use]
968pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
969 Widget::LazyList {
970 children,
971 on_load_more: Some(tok(on_load_more)),
972 loading,
973 has_more,
974 on_refresh: None,
975 refreshing: false,
976 }
977}
978
979#[must_use]
981pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
982 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
983}
984
985#[cfg(test)]
986mod tests {
987 use super::*;
988 use serde::Serialize;
989
990 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
991 enum Route {
992 Home,
993 Detail(u32),
994 }
995
996 #[derive(Serialize)]
997 enum Ev {
998 Tap,
999 Open(u32),
1000 }
1001
1002 #[test]
1005 fn nav_push_pop_depth() {
1006 let mut nav = Nav::new(Route::Home);
1007 assert_eq!(nav.depth(), 1);
1008 assert!(!nav.can_go_back());
1009
1010 nav.push(Route::Detail(7));
1011 assert_eq!(nav.depth(), 2);
1012 assert!(nav.can_go_back());
1013 assert!(matches!(nav.current(), Route::Detail(7)));
1014
1015 nav.pop();
1016 assert_eq!(nav.depth(), 1);
1017 assert!(matches!(nav.current(), Route::Home));
1018
1019 nav.pop(); assert_eq!(nav.depth(), 1);
1021 }
1022
1023 #[test]
1024 fn nav_reset_replaces_stack() {
1025 let mut nav = Nav::new(Route::Home);
1026 nav.push(Route::Detail(1));
1027 nav.push(Route::Detail(2));
1028 nav.reset(Route::Detail(9));
1029 assert_eq!(nav.depth(), 1);
1030 assert!(matches!(nav.current(), Route::Detail(9)));
1031 }
1032
1033 #[test]
1034 fn nav_route_key_is_serialization() {
1035 let nav = Nav::new(Route::Detail(3));
1036 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1037 }
1038
1039 #[test]
1042 fn scaffold_sets_route_depth_and_no_back() {
1043 match scaffold("Home", false, vec![], text("x")) {
1044 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1045 assert_eq!(route, "Home");
1046 assert_eq!(depth, 1);
1047 assert!(back.is_none());
1048 assert!(!dark_mode);
1049 }
1050 other => panic!("expected Scaffold, got {other:?}"),
1051 }
1052 }
1053
1054 #[test]
1055 fn scaffold_back_is_depth_2_with_back() {
1056 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1057 Widget::Scaffold { depth, back, dark_mode, .. } => {
1058 assert_eq!(depth, 2);
1059 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1060 assert!(dark_mode);
1061 }
1062 other => panic!("expected Scaffold, got {other:?}"),
1063 }
1064 }
1065
1066 #[test]
1067 fn nav_scaffold_shows_back_only_when_poppable() {
1068 let mut nav = Nav::new(Route::Home);
1069 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1071 Widget::Scaffold { back, depth, route, .. } => {
1072 assert!(back.is_none());
1073 assert_eq!(depth, 1);
1074 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1075 }
1076 other => panic!("expected Scaffold, got {other:?}"),
1077 }
1078 nav.push(Route::Detail(2));
1080 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1081 Widget::Scaffold { back, depth, .. } => {
1082 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1083 assert_eq!(depth, 2);
1084 }
1085 other => panic!("expected Scaffold, got {other:?}"),
1086 }
1087 }
1088
1089 #[test]
1090 fn buttons_carry_serialized_event_tokens() {
1091 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1092 Widget::Button { label, on_press, .. } => {
1093 assert_eq!(label, "Go");
1094 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1095 }
1096 other => panic!("expected Button, got {other:?}"),
1097 }
1098 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1099 Widget::Card { on_press, .. } => {
1100 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1101 }
1102 other => panic!("expected Card, got {other:?}"),
1103 }
1104 match card(text("c"), CardStyle::Elevated) {
1106 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
1107 other => panic!("expected Card, got {other:?}"),
1108 }
1109 }
1110
1111 #[test]
1114 fn cx_notify_and_save_enqueue_notifications() {
1115 let mut cx = Cx::<Ev>::default();
1116 cx.notify("toast", "show", "hi");
1117 cx.save("blob");
1118 assert_eq!(cx.notifications.len(), 2);
1119 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1120 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1121 assert!(cx.requests.is_empty());
1122 }
1123
1124 #[test]
1125 fn cx_http_helpers_build_requests() {
1126 let mut cx = Cx::<Ev>::default();
1127 cx.get("http://h/x", |_| Ev::Tap);
1128 cx.post("http://h/y", "hello", |_| Ev::Tap);
1129 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1130 cx.delete("http://h/d", |_| Ev::Tap);
1131
1132 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1133 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1134 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1135
1136 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1137 assert_eq!(get_input["url"], "http://h/x");
1138 assert!(get_input["body"].is_null());
1139
1140 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1141 assert_eq!(post_input["url"], "http://h/y");
1142 assert_eq!(post_input["body"], "hello");
1143 }
1144
1145 #[test]
1146 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1147 let mut cx = Cx::<Ev>::default();
1148 cx.pick_photo(|_| Ev::Tap);
1149 cx.capture_photo(|_| Ev::Tap);
1150 assert_eq!(cx.requests.len(), 2);
1151 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", ""));
1154 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", ""));
1155 }
1156
1157 #[test]
1158 fn cx_capture_photo_routes_success_and_cancel() {
1159 let mut cx = Cx::<Ev>::default();
1161 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1162 let (_, then) = cx.requests.pop().unwrap();
1163 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1164
1165 let mut cx = Cx::<Ev>::default();
1167 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1168 let (_, then) = cx.requests.pop().unwrap();
1169 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1170 }
1171
1172 #[test]
1173 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1174 let mut cx = Cx::<Ev>::default();
1175 cx.copy("c");
1176 cx.share("s");
1177 cx.open_url("u");
1178 cx.toast("t");
1179 cx.haptic("heavy");
1180 let got: Vec<(&str, &str, &str)> = cx
1181 .notifications
1182 .iter()
1183 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1184 .collect();
1185 assert_eq!(
1186 got,
1187 vec![
1188 ("clipboard", "copy", "c"),
1189 ("share", "text", "s"),
1190 ("browser", "open", "u"),
1191 ("toast", "show", "t"),
1192 ("haptics", "heavy", ""), ]
1194 );
1195 assert!(cx.requests.is_empty());
1196 }
1197
1198 #[test]
1199 fn cx_device_model_is_a_request_not_a_notification() {
1200 let mut cx = Cx::<Ev>::default();
1201 cx.device_model(|_| Ev::Tap);
1202 assert!(cx.notifications.is_empty());
1203 assert_eq!(cx.requests.len(), 1);
1204 let (call, _) = &cx.requests[0];
1205 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1206 }
1207
1208 #[test]
1209 fn cx_device_locale_requests_the_device_locale_op() {
1210 let mut cx = Cx::<Ev>::default();
1211 cx.device_locale(|_| Ev::Tap);
1212 assert!(cx.notifications.is_empty());
1213 assert_eq!(cx.requests.len(), 1);
1214 let (call, _) = &cx.requests[0];
1215 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1216 }
1217
1218 #[test]
1219 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1220 let mut cx = Cx::<Ev>::default();
1221 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1222 assert!(cx.notifications.is_empty());
1224 assert!(cx.requests.is_empty());
1225 assert_eq!(cx.streams.len(), 1);
1226 let (call, on_event) = &cx.streams[0];
1227 assert_eq!(
1228 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1229 ("ws", "websocket", "stream", "wss://h/x")
1230 );
1231 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1233 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1234 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1235 }
1236
1237 #[test]
1238 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1239 let mut cx = Cx::<Ev>::default();
1240 cx.unsubscribe("ws");
1241 assert!(cx.streams.is_empty());
1242 assert_eq!(cx.notifications.len(), 1);
1243 assert_eq!(
1245 cx.notifications[0],
1246 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1247 );
1248 }
1249
1250 #[test]
1251 fn cx_confirm_serializes_title_message_and_routes_ok() {
1252 let mut cx = Cx::<Ev>::default();
1253 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1254 let (call, then) = cx.requests.pop().unwrap();
1255 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1256 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1257 assert_eq!(v["title"], "Delete?");
1258 assert_eq!(v["message"], "This cannot be undone.");
1259 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1261 }
1262
1263 #[test]
1266 fn text_builders_carry_their_style() {
1267 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1268 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1269 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1270 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1271 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1272 }
1273
1274 #[test]
1275 fn layout_and_content_builders_produce_their_variants() {
1276 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1277 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1278 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1279 assert!(matches!(divider(), Widget::Divider));
1280 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1281 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1282 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1283 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)));
1284 let rc = with_bracket(
1285 region_chart(
1286 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1287 vec![ChartTick::new(3.0, "3 Mt.")],
1288 65.0, 80.0,
1289 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1290 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1291 ),
1292 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1293 );
1294 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1295 assert!(matches!(
1297 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1298 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1299 ));
1300 assert!(matches!(
1301 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1302 Widget::SwipeAction { actions, .. } if actions.len() == 1
1303 ));
1304 assert!(matches!(
1306 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1307 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1308 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1309 ));
1310 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1311 assert!(matches!(
1313 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1314 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1315 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1316 ));
1317 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1318 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1319 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1320 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1321 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1322 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1324 }
1325
1326 #[test]
1327 fn input_builders_carry_ids_values_and_event_tokens() {
1328 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1329 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1330 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1332 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1333 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1334 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1335 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1336 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1337 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1338 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1339 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1340 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1341 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1342 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1343
1344 match chip("Latte", true, Ev::Open(2)) {
1345 Widget::Chip { selected, on_press, .. } => {
1346 assert!(selected);
1347 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1348 }
1349 other => panic!("expected Chip, got {other:?}"),
1350 }
1351 match stepper(5, Ev::Tap, Ev::Open(1)) {
1352 Widget::Stepper { value, on_decrement, on_increment } => {
1353 assert_eq!(value, 5);
1354 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1355 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1356 }
1357 other => panic!("expected Stepper, got {other:?}"),
1358 }
1359 let t = tab("Home", true, Ev::Tap);
1360 assert_eq!(t.label, "Home");
1361 assert!(t.selected);
1362 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1363 }
1364
1365 #[test]
1368 fn widget_tree_round_trips_through_serde() {
1369 let tree = scaffold(
1370 "Home",
1371 true,
1372 vec![tab("A", true, Ev::Tap)],
1373 column(vec![
1374 title("Hi"),
1375 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1376 image("u", ImageShape::Rounded, ImageRatio::Wide),
1377 slider("s", 2, 5),
1378 ]),
1379 );
1380 let s = serde_json::to_string(&tree).unwrap();
1381 let back: Widget = serde_json::from_str(&s).unwrap();
1382 assert_eq!(s, serde_json::to_string(&back).unwrap());
1383 }
1384
1385 #[test]
1386 fn actions_and_input_values_round_trip() {
1387 let actions = vec![
1388 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1389 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1390 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1391 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1392 Action::Restore { data: "blob".into() },
1393 Action::Start,
1394 ];
1395 for a in actions {
1396 let s = serde_json::to_string(&a).unwrap();
1397 let back: Action = serde_json::from_str(&s).unwrap();
1398 assert_eq!(s, serde_json::to_string(&back).unwrap());
1399 }
1400 }
1401
1402 #[derive(Default)]
1405 struct CounterModel {
1406 count: i32,
1407 restored: String,
1408 started: bool,
1409 last_input: String,
1410 }
1411
1412 #[derive(serde::Serialize, serde::Deserialize)]
1413 enum CounterEv {
1414 Inc,
1415 Add(i32),
1416 }
1417
1418 #[derive(Default)]
1419 struct CounterApp;
1420
1421 impl MobilerApp for CounterApp {
1422 type Event = CounterEv;
1423 type Model = CounterModel;
1424 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1425 match ev {
1426 CounterEv::Inc => model.count += 1,
1427 CounterEv::Add(n) => model.count += n,
1428 }
1429 }
1430 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1431 if let InputValue::Text(t) = value {
1432 model.last_input = format!("{id}={t}");
1433 }
1434 }
1435 fn restore(&self, data: &str, model: &mut CounterModel) {
1436 model.restored = data.to_string();
1437 }
1438 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1439 model.started = true;
1440 }
1441 fn view(&self, model: &CounterModel) -> Widget {
1442 text(format!("{}", model.count))
1443 }
1444 }
1445
1446 #[test]
1447 fn shell_dispatches_fired_input_restore_and_start() {
1448 use crux_core::App as _;
1449 let shell = MobilerShell::<CounterApp>::default();
1450 let mut m = CounterModel::default();
1451
1452 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1454 assert_eq!(m.count, 5);
1455 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1457 assert_eq!(m.last_input, "name=bob");
1458 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1460 assert_eq!(m.restored, "saved");
1461 let _ = shell.update(Action::Start, &mut m);
1463 assert!(m.started);
1464 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1466 }
1467
1468 #[test]
1469 fn shell_ignores_a_malformed_fired_token() {
1470 use crux_core::App as _;
1471 let shell = MobilerShell::<CounterApp>::default();
1472 let mut m = CounterModel::default();
1473 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1476 assert_eq!(m.count, 0);
1477 }
1478}