1use std::marker::PhantomData;
9
10pub mod bunny;
11pub mod format;
12pub mod i18n;
13pub use format::{Currency, Locale};
14pub use i18n::{Catalog, negotiate};
15
16use crux_core::{
17 App, Command,
18 capability::Operation,
19 macros::effect,
20 render::{RenderOperation, render},
21};
22use facet::Facet;
23use serde::{Deserialize, Serialize, de::DeserializeOwned};
24
25pub use mobiler_ui::{
26 A11yRole, Action, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
27 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
28 ImageRatio, ImageShape, InputValue, MapMarker, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
29 TextStyle, Theme, Tone, Widget,
30};
31
32#[effect(facet_typegen)]
36#[derive(Debug)]
37pub enum Effect {
38 Render(RenderOperation),
39 PluginNotify(PluginNotify),
41 Plugin(PluginCall),
43 PluginStream(PluginStreamCall),
48}
49
50#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
51pub struct PluginNotify {
52 pub plugin: String,
53 pub op: String,
54 pub input: String,
55}
56impl Operation for PluginNotify {
57 type Output = ();
58}
59
60#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
61pub struct PluginCall {
62 pub plugin: String,
63 pub op: String,
64 pub input: String,
65}
66impl Operation for PluginCall {
67 type Output = PluginResponse;
68}
69
70#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
74pub struct PluginStreamCall {
75 pub key: String,
76 pub plugin: String,
77 pub op: String,
78 pub input: String,
79}
80impl Operation for PluginStreamCall {
81 type Output = PluginResponse;
82}
83
84#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
85pub struct PluginResponse {
86 pub ok: bool,
87 pub output: String,
88}
89
90type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
91type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
93
94pub struct Cx<E> {
97 notifications: Vec<PluginNotify>,
98 requests: Vec<(PluginCall, Continuation<E>)>,
99 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
100}
101
102impl<E> Default for Cx<E> {
103 fn default() -> Self {
104 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
105 }
106}
107
108impl<E> Cx<E> {
109 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
111 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
112 }
113
114 pub fn plugin(
117 &mut self,
118 plugin: impl Into<String>,
119 op: impl Into<String>,
120 input: impl Into<String>,
121 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
122 ) {
123 self.requests
124 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
125 }
126
127 pub fn subscribe(
135 &mut self,
136 key: impl Into<String>,
137 plugin: impl Into<String>,
138 op: impl Into<String>,
139 input: impl Into<String>,
140 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
141 ) {
142 self.streams.push((
143 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
144 Box::new(on_event),
145 ));
146 }
147
148 pub fn unsubscribe(&mut self, key: impl Into<String>) {
152 self.notify("stream", "unsubscribe", key);
153 }
154
155 pub fn save(&mut self, data: impl Into<String>) {
157 self.notify("storage", "save", data);
158 }
159
160 pub fn copy(&mut self, text: impl Into<String>) {
162 self.notify("clipboard", "copy", text);
163 }
164
165 pub fn share(&mut self, text: impl Into<String>) {
167 self.notify("share", "text", text);
168 }
169
170 pub fn open_url(&mut self, url: impl Into<String>) {
173 self.notify("browser", "open", url);
174 }
175
176 pub fn toast(&mut self, text: impl Into<String>) {
178 self.notify("toast", "show", text);
179 }
180
181 pub fn haptic(&mut self, style: impl Into<String>) {
184 self.notify("haptics", style, "");
185 }
186
187 pub fn http(
192 &mut self,
193 method: impl Into<String>,
194 url: impl Into<String>,
195 body: Option<String>,
196 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
197 ) {
198 #[derive(Serialize)]
199 struct HttpReq {
200 url: String,
201 body: Option<String>,
202 }
203 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
204 .expect("serialize http request");
205 self.plugin("http", method, input, then);
206 }
207
208 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
210 self.http("GET", url, None, then);
211 }
212 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
214 self.http("POST", url, Some(body.into()), then);
215 }
216 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
218 self.http("PATCH", url, Some(body.into()), then);
219 }
220 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
222 self.http("DELETE", url, None, then);
223 }
224
225 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
229 self.plugin("device", "model", "", then);
230 }
231
232 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
237 self.plugin("device", "locale", "", then);
238 }
239
240 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
245 self.plugin("photo", "pick", "", then);
246 }
247
248 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
255 self.plugin("camera", "capture", "", then);
256 }
257
258 pub fn confirm(
262 &mut self,
263 title: impl Into<String>,
264 message: impl Into<String>,
265 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
266 ) {
267 #[derive(Serialize)]
268 struct Confirm {
269 title: String,
270 message: String,
271 }
272 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
273 .expect("serialize confirm");
274 self.plugin("dialog", "confirm", input, then);
275 }
276
277 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
282 self.plugin("datetime", "date", "", then);
283 }
284
285 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
290 self.plugin("datetime", "time", "", then);
291 }
292
293 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
300 self.plugin("datetime", "now", "", then);
301 }
302}
303
304pub trait MobilerApp: Default {
309 type Event: Serialize + DeserializeOwned + Send + 'static;
310 type Model: Default;
311
312 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
313
314 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
315 let _ = (id, value, model, cx);
316 }
317
318 fn restore(&self, data: &str, model: &mut Self::Model) {
321 let _ = (data, model);
322 }
323
324 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
327 let _ = (model, cx);
328 }
329
330 fn view(&self, model: &Self::Model) -> Widget;
331}
332
333pub struct MobilerShell<A>(PhantomData<fn() -> A>);
335
336impl<A> Default for MobilerShell<A> {
337 fn default() -> Self {
338 Self(PhantomData)
339 }
340}
341
342impl<A: MobilerApp> App for MobilerShell<A> {
343 type Event = Action;
344 type Model = A::Model;
345 type ViewModel = Widget;
346 type Effect = Effect;
347
348 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
349 let app = A::default();
350 let mut cx = Cx::<A::Event>::default();
351 match action {
352 Action::Fired { token } => {
353 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
354 app.update(event, model, &mut cx);
355 }
356 }
357 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
358 Action::Restore { data } => app.restore(&data, model),
359 Action::Start => app.init(model, &mut cx),
360 }
361 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
362 for op in cx.notifications {
363 commands.push(Command::notify_shell(op).build());
364 }
365 for (op, then) in cx.requests {
366 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
367 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
368 }));
369 }
370 for (op, then) in cx.streams {
371 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
374 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
375 }));
376 }
377 commands.push(render());
378 Command::all(commands)
379 }
380
381 fn view(&self, model: &Self::Model) -> Widget {
382 A::default().view(model)
383 }
384}
385
386#[derive(Clone, Debug)]
405pub struct Nav<R> {
406 stack: Vec<R>,
407}
408
409impl<R: Clone + Serialize> Nav<R> {
410 #[must_use]
412 pub fn new(root: R) -> Self {
413 Self { stack: vec![root] }
414 }
415 pub fn push(&mut self, route: R) {
417 self.stack.push(route);
418 }
419 pub fn pop(&mut self) {
421 if self.stack.len() > 1 {
422 self.stack.pop();
423 }
424 }
425 pub fn reset(&mut self, root: R) {
427 self.stack = vec![root];
428 }
429 #[must_use]
431 pub fn current(&self) -> &R {
432 self.stack.last().expect("nav stack is never empty")
433 }
434 #[must_use]
436 pub fn depth(&self) -> u32 {
437 self.stack.len() as u32
438 }
439 #[must_use]
441 pub fn can_go_back(&self) -> bool {
442 self.stack.len() > 1
443 }
444 fn route_key(&self) -> String {
447 serde_json::to_string(self.current()).expect("serialize route")
448 }
449}
450
451fn tok<E: Serialize>(event: E) -> String {
455 serde_json::to_string(&event).expect("serialize event")
456}
457
458#[must_use]
459pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
460 Widget::Text { content: content.into(), style }
461}
462#[must_use]
463pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
464#[must_use]
465pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
466#[must_use]
467pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
468#[must_use]
469pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
470#[must_use]
471pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
472
473#[must_use]
474pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
475 Widget::Image { source: source.into(), shape, ratio }
476}
477#[must_use]
478pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
479 Widget::Badge { label: label.into(), tone }
480}
481#[must_use]
483pub fn color_dot(color: ProjectColor) -> Widget {
484 Widget::ColorDot { color }
485}
486#[must_use]
487pub fn divider() -> Widget { Widget::Divider }
488#[must_use]
490pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
491#[must_use]
493pub fn skeleton() -> Widget { Widget::Skeleton }
494#[must_use]
498pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
499#[must_use]
508pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
509 Widget::Video {
510 url: url.into(),
511 id: id.into(),
512 playing,
513 seek_to_ms,
514 controls: true,
515 looping: false,
516 muted: false,
517 on_ended: Some(tok(on_ended)),
518 poster: None,
519 start_at_ms: -1,
520 captions: Vec::new(),
521 rate: 1.0,
522 volume: 1.0,
523 urls: Vec::new(),
524 start_index: 0,
525 seek_index: -1,
526 allow_pip: false,
527 }
528}
529#[must_use]
535pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
536 Widget::Video {
537 url: urls.first().cloned().unwrap_or_default(),
538 id: id.into(),
539 playing,
540 seek_to_ms: -1,
541 controls: true,
542 looping: false,
543 muted: false,
544 on_ended: Some(tok(on_ended)),
545 poster: None,
546 start_at_ms: -1,
547 captions: Vec::new(),
548 rate: 1.0,
549 volume: 1.0,
550 urls,
551 start_index,
552 seek_index: -1,
553 allow_pip: false,
554 }
555}
556fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
559 match widget {
560 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
561 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
562 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
563 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
564 f(&mut v);
565 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
566 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
567 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
568 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
569 allow_pip: v.allow_pip }
570 }
571 other => other,
572 }
573}
574struct VideoFields {
575 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
576 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
577 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
578 seek_index: i64, allow_pip: bool,
579}
580#[must_use]
582pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
583#[must_use]
585pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
586#[must_use]
588pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
589#[must_use]
591pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
592 let poster = poster.into();
593 map_video(widget, move |v| v.poster = Some(poster))
594}
595#[must_use]
597pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
598 map_video(widget, move |v| v.start_at_ms = start_at_ms)
599}
600#[must_use]
602pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
603 map_video(widget, move |v| v.captions = captions)
604}
605#[must_use]
607pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
608#[must_use]
610pub fn with_volume(widget: Widget, volume: f32) -> Widget {
611 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
612}
613#[must_use]
615pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
616 map_video(widget, move |v| v.seek_index = index)
617}
618#[must_use]
620pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
621#[must_use]
626pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
627
628#[must_use]
634pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
635 Widget::Map {
636 id: id.into(),
637 center_lat,
638 center_lng,
639 zoom,
640 markers: Vec::new(),
641 style_url: None,
642 interactive: true,
643 }
644}
645#[must_use]
647pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
648 match widget {
649 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
650 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
651 other => other,
652 }
653}
654#[must_use]
656pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
657 match widget {
658 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
659 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
660 other => other,
661 }
662}
663#[must_use]
665pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
666 MapMarker { id: id.into(), lat, lng, title: None }
667}
668#[must_use]
670pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
671 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
672}
673fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
675 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
676}
677
678#[must_use]
681pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
682 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
683}
684#[must_use]
687pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
688 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
689}
690#[must_use]
694pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
695 Widget::Chart { series, labels, style, axis, legend }
696}
697#[must_use]
699pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
700 chart(series, labels, ChartStyle::StackedBar, true, true)
701}
702#[must_use]
704pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
705 chart(series, labels, ChartStyle::StackedBar100, false, true)
706}
707#[must_use]
709pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
710 chart(series, vec![], ChartStyle::Pie, false, true)
711}
712#[must_use]
714pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
715 chart(series, vec![], ChartStyle::Donut, false, true)
716}
717#[must_use]
720pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
721 chart(series, vec![], ChartStyle::Rings, false, true)
722}
723#[must_use]
725pub fn gauge_chart(series: ChartSeries) -> Widget {
726 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
727}
728
729#[must_use]
734pub fn region_chart(
735 regions: Vec<ChartRegion>,
736 ticks: Vec<ChartTick>,
737 x_max: f32,
738 y_max: f32,
739 ref_lines: Vec<ChartRefLine>,
740 legend: Vec<ChartLegendItem>,
741) -> Widget {
742 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
743}
744
745#[must_use]
747pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
748 match widget {
749 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
750 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
751 }
752 other => other,
753 }
754}
755
756fn days_in_month(year: u32, month: u8) -> u8 {
758 match month {
759 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
760 4 | 6 | 9 | 11 => 30,
761 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
762 _ => 30,
763 }
764}
765
766fn weekday(year: u32, month: u8, day: u8) -> u8 {
768 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
769 let y = if month < 3 { year - 1 } else { year };
770 let m = month as usize - 1;
771 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
772}
773
774#[must_use]
778pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
779 let n = days_in_month(year, month);
780 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
781 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
782}
783
784#[must_use]
787pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
788 Widget::SwipeAction {
789 child: Box::new(child),
790 actions: actions
791 .into_iter()
792 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
793 .collect(),
794 }
795}
796#[must_use]
797pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
798
799#[must_use]
800pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
801#[must_use]
802pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
803#[must_use]
804pub fn card(child: Widget, style: CardStyle) -> Widget {
805 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
806}
807#[must_use]
809pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
810 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
811}
812#[must_use]
815pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
816 match widget {
817 Widget::Card { child, style, on_press, .. } => Widget::Card {
818 child,
819 style,
820 on_press,
821 on_long_press: Some(tok(on_long_press)),
822 },
823 other => other,
824 }
825}
826#[must_use]
829pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
830 Widget::Box { children, align, scrim }
831}
832#[must_use]
833pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
834#[must_use]
839pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
840 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
841}
842#[must_use]
844pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
845#[must_use]
847pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
848#[must_use]
850pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
851 Widget::Avatar { source: source.into(), status: Some(status) }
852}
853#[must_use]
855pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
856#[must_use]
858pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
859 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
860}
861
862#[must_use]
863pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
864 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
865}
866#[must_use]
867pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
868 Widget::IconButton { icon, on_press: tok(on_press) }
869}
870#[must_use]
871pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
872 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
873}
874#[must_use]
875pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
876 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
877}
878#[must_use]
882pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
883 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
884}
885#[must_use]
887pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
888 field(id, placeholder, value, FieldKind::Secure, None)
889}
890#[must_use]
892pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
893 field(id, placeholder, value, FieldKind::Email, None)
894}
895#[must_use]
897pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
898 field(id, placeholder, value, FieldKind::Number, None)
899}
900#[must_use]
902pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
903 field(id, placeholder, value, FieldKind::Decimal, None)
904}
905#[must_use]
907pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
908 field(id, placeholder, value, FieldKind::Phone, None)
909}
910#[must_use]
912pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
913 field(id, placeholder, value, FieldKind::Url, None)
914}
915#[must_use]
917pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
918 field(id, placeholder, value, FieldKind::Multiline, None)
919}
920#[must_use]
923pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
924 match widget {
925 Widget::TextField { id, placeholder, value, kind, .. } =>
926 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
927 other => other,
928 }
929}
930
931#[must_use]
935pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
936 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
937}
938#[must_use]
941pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
942 match widget {
943 Widget::A11y { child, label, role, .. } =>
944 Widget::A11y { child, label, hint: Some(hint.into()), role },
945 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
946 }
947}
948#[must_use]
950pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
951 match widget {
952 Widget::A11y { child, label, hint, .. } =>
953 Widget::A11y { child, label, hint, role: Some(role) },
954 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
955 }
956}
957#[must_use]
959pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
960 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
961}
962#[must_use]
964pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
965 Segment { label: label.into(), selected, on_select: tok(on_select) }
966}
967#[must_use]
969pub fn segmented(segments: Vec<Segment>) -> Widget {
970 Widget::Segmented { segments }
971}
972#[must_use]
973pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
974 Widget::Toggle { id: id.into(), label: label.into(), value }
975}
976#[must_use]
977pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
978 Widget::Checkbox { id: id.into(), label: label.into(), value }
979}
980#[must_use]
981pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
982 Widget::Slider { id: id.into(), value, max }
983}
984#[must_use]
985pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
986 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
987}
988
989#[must_use]
991pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
992 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
993}
994
995#[must_use]
997pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
998 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
999}
1000
1001#[must_use]
1004pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1005 let title = title.into();
1006 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 }
1008}
1009
1010#[must_use]
1014pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1015 let title = title.into();
1016 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 }
1017}
1018
1019#[must_use]
1024pub fn nav_scaffold<R, E>(
1025 title: impl Into<String>,
1026 dark_mode: bool,
1027 tabs: Vec<Tab>,
1028 body: Widget,
1029 nav: &Nav<R>,
1030 on_back: E,
1031) -> Widget
1032where
1033 R: Clone + Serialize,
1034 E: Serialize,
1035{
1036 Widget::Scaffold {
1037 title: title.into(),
1038 body: Box::new(body),
1039 tabs,
1040 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1041 dark_mode,
1042 theme: None,
1043 fab: None,
1044 sheet: None,
1045 on_refresh: None,
1046 refreshing: false,
1047 route: nav.route_key(),
1048 depth: nav.depth(),
1049 }
1050}
1051
1052pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1056 match widget {
1057 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1058 title,
1059 body,
1060 tabs,
1061 back,
1062 dark_mode,
1063 theme: Some(theme),
1064 fab,
1065 sheet,
1066 on_refresh,
1067 refreshing,
1068 route,
1069 depth,
1070 },
1071 other => other,
1072 }
1073}
1074
1075pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1078 match widget {
1079 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1080 title,
1081 body,
1082 tabs,
1083 back,
1084 dark_mode,
1085 theme,
1086 fab: Some(Fab { icon, on_press: tok(on_press) }),
1087 sheet,
1088 on_refresh,
1089 refreshing,
1090 route,
1091 depth,
1092 },
1093 other => other,
1094 }
1095}
1096
1097pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1100 match widget {
1101 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1102 title: t,
1103 body,
1104 tabs,
1105 back,
1106 dark_mode,
1107 theme,
1108 fab,
1109 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1110 on_refresh,
1111 refreshing,
1112 route,
1113 depth,
1114 },
1115 other => other,
1116 }
1117}
1118
1119pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1123 match widget {
1124 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1125 title,
1126 body,
1127 tabs,
1128 back,
1129 dark_mode,
1130 theme,
1131 fab,
1132 sheet,
1133 on_refresh: Some(tok(on_refresh)),
1134 refreshing,
1135 route,
1136 depth,
1137 },
1138 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1141 children,
1142 on_load_more,
1143 loading,
1144 has_more,
1145 on_refresh: Some(tok(on_refresh)),
1146 refreshing,
1147 },
1148 other => other,
1149 }
1150}
1151
1152#[must_use]
1158pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1159 Widget::LazyList {
1160 children,
1161 on_load_more: Some(tok(on_load_more)),
1162 loading,
1163 has_more,
1164 on_refresh: None,
1165 refreshing: false,
1166 }
1167}
1168
1169#[must_use]
1171pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1172 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177 use super::*;
1178 use serde::Serialize;
1179
1180 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1181 enum Route {
1182 Home,
1183 Detail(u32),
1184 }
1185
1186 #[derive(Serialize)]
1187 enum Ev {
1188 Tap,
1189 Open(u32),
1190 }
1191
1192 #[test]
1195 fn nav_push_pop_depth() {
1196 let mut nav = Nav::new(Route::Home);
1197 assert_eq!(nav.depth(), 1);
1198 assert!(!nav.can_go_back());
1199
1200 nav.push(Route::Detail(7));
1201 assert_eq!(nav.depth(), 2);
1202 assert!(nav.can_go_back());
1203 assert!(matches!(nav.current(), Route::Detail(7)));
1204
1205 nav.pop();
1206 assert_eq!(nav.depth(), 1);
1207 assert!(matches!(nav.current(), Route::Home));
1208
1209 nav.pop(); assert_eq!(nav.depth(), 1);
1211 }
1212
1213 #[test]
1214 fn nav_reset_replaces_stack() {
1215 let mut nav = Nav::new(Route::Home);
1216 nav.push(Route::Detail(1));
1217 nav.push(Route::Detail(2));
1218 nav.reset(Route::Detail(9));
1219 assert_eq!(nav.depth(), 1);
1220 assert!(matches!(nav.current(), Route::Detail(9)));
1221 }
1222
1223 #[test]
1224 fn nav_route_key_is_serialization() {
1225 let nav = Nav::new(Route::Detail(3));
1226 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1227 }
1228
1229 #[test]
1232 fn scaffold_sets_route_depth_and_no_back() {
1233 match scaffold("Home", false, vec![], text("x")) {
1234 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1235 assert_eq!(route, "Home");
1236 assert_eq!(depth, 1);
1237 assert!(back.is_none());
1238 assert!(!dark_mode);
1239 }
1240 other => panic!("expected Scaffold, got {other:?}"),
1241 }
1242 }
1243
1244 #[test]
1245 fn scaffold_back_is_depth_2_with_back() {
1246 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1247 Widget::Scaffold { depth, back, dark_mode, .. } => {
1248 assert_eq!(depth, 2);
1249 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1250 assert!(dark_mode);
1251 }
1252 other => panic!("expected Scaffold, got {other:?}"),
1253 }
1254 }
1255
1256 #[test]
1257 fn nav_scaffold_shows_back_only_when_poppable() {
1258 let mut nav = Nav::new(Route::Home);
1259 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1261 Widget::Scaffold { back, depth, route, .. } => {
1262 assert!(back.is_none());
1263 assert_eq!(depth, 1);
1264 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1265 }
1266 other => panic!("expected Scaffold, got {other:?}"),
1267 }
1268 nav.push(Route::Detail(2));
1270 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1271 Widget::Scaffold { back, depth, .. } => {
1272 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1273 assert_eq!(depth, 2);
1274 }
1275 other => panic!("expected Scaffold, got {other:?}"),
1276 }
1277 }
1278
1279 #[test]
1280 fn buttons_carry_serialized_event_tokens() {
1281 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1282 Widget::Button { label, on_press, .. } => {
1283 assert_eq!(label, "Go");
1284 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1285 }
1286 other => panic!("expected Button, got {other:?}"),
1287 }
1288 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1289 Widget::Card { on_press, .. } => {
1290 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1291 }
1292 other => panic!("expected Card, got {other:?}"),
1293 }
1294 match card(text("c"), CardStyle::Elevated) {
1296 Widget::Card { on_press, on_long_press, .. } => {
1297 assert!(on_press.is_none());
1298 assert!(on_long_press.is_none());
1299 }
1300 other => panic!("expected Card, got {other:?}"),
1301 }
1302 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1304 Widget::Card { on_press, on_long_press, .. } => {
1305 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1306 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1307 }
1308 other => panic!("expected Card, got {other:?}"),
1309 }
1310 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1312 }
1313
1314 #[test]
1317 fn cx_notify_and_save_enqueue_notifications() {
1318 let mut cx = Cx::<Ev>::default();
1319 cx.notify("toast", "show", "hi");
1320 cx.save("blob");
1321 assert_eq!(cx.notifications.len(), 2);
1322 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1323 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1324 assert!(cx.requests.is_empty());
1325 }
1326
1327 #[test]
1328 fn cx_http_helpers_build_requests() {
1329 let mut cx = Cx::<Ev>::default();
1330 cx.get("http://h/x", |_| Ev::Tap);
1331 cx.post("http://h/y", "hello", |_| Ev::Tap);
1332 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1333 cx.delete("http://h/d", |_| Ev::Tap);
1334
1335 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1336 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1337 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1338
1339 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1340 assert_eq!(get_input["url"], "http://h/x");
1341 assert!(get_input["body"].is_null());
1342
1343 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1344 assert_eq!(post_input["url"], "http://h/y");
1345 assert_eq!(post_input["body"], "hello");
1346 }
1347
1348 #[test]
1349 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1350 let mut cx = Cx::<Ev>::default();
1351 cx.pick_photo(|_| Ev::Tap);
1352 cx.capture_photo(|_| Ev::Tap);
1353 assert_eq!(cx.requests.len(), 2);
1354 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", ""));
1357 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", ""));
1358 }
1359
1360 #[test]
1361 fn cx_capture_photo_routes_success_and_cancel() {
1362 let mut cx = Cx::<Ev>::default();
1364 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1365 let (_, then) = cx.requests.pop().unwrap();
1366 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1367
1368 let mut cx = Cx::<Ev>::default();
1370 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1371 let (_, then) = cx.requests.pop().unwrap();
1372 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1373 }
1374
1375 #[test]
1376 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1377 let mut cx = Cx::<Ev>::default();
1378 cx.copy("c");
1379 cx.share("s");
1380 cx.open_url("u");
1381 cx.toast("t");
1382 cx.haptic("heavy");
1383 let got: Vec<(&str, &str, &str)> = cx
1384 .notifications
1385 .iter()
1386 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1387 .collect();
1388 assert_eq!(
1389 got,
1390 vec![
1391 ("clipboard", "copy", "c"),
1392 ("share", "text", "s"),
1393 ("browser", "open", "u"),
1394 ("toast", "show", "t"),
1395 ("haptics", "heavy", ""), ]
1397 );
1398 assert!(cx.requests.is_empty());
1399 }
1400
1401 #[test]
1402 fn cx_device_model_is_a_request_not_a_notification() {
1403 let mut cx = Cx::<Ev>::default();
1404 cx.device_model(|_| Ev::Tap);
1405 assert!(cx.notifications.is_empty());
1406 assert_eq!(cx.requests.len(), 1);
1407 let (call, _) = &cx.requests[0];
1408 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1409 }
1410
1411 #[test]
1412 fn cx_device_locale_requests_the_device_locale_op() {
1413 let mut cx = Cx::<Ev>::default();
1414 cx.device_locale(|_| Ev::Tap);
1415 assert!(cx.notifications.is_empty());
1416 assert_eq!(cx.requests.len(), 1);
1417 let (call, _) = &cx.requests[0];
1418 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1419 }
1420
1421 #[test]
1422 fn cx_now_requests_the_datetime_now_op() {
1423 let mut cx = Cx::<Ev>::default();
1424 cx.now(|_| Ev::Tap);
1425 assert_eq!(cx.requests.len(), 1);
1426 let (call, _) = &cx.requests[0];
1427 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1428 }
1429
1430 #[test]
1431 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1432 let mut cx = Cx::<Ev>::default();
1433 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1434 assert!(cx.notifications.is_empty());
1436 assert!(cx.requests.is_empty());
1437 assert_eq!(cx.streams.len(), 1);
1438 let (call, on_event) = &cx.streams[0];
1439 assert_eq!(
1440 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1441 ("ws", "websocket", "stream", "wss://h/x")
1442 );
1443 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1445 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1446 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1447 }
1448
1449 #[test]
1450 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1451 let mut cx = Cx::<Ev>::default();
1452 cx.unsubscribe("ws");
1453 assert!(cx.streams.is_empty());
1454 assert_eq!(cx.notifications.len(), 1);
1455 assert_eq!(
1457 cx.notifications[0],
1458 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1459 );
1460 }
1461
1462 #[test]
1463 fn cx_confirm_serializes_title_message_and_routes_ok() {
1464 let mut cx = Cx::<Ev>::default();
1465 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1466 let (call, then) = cx.requests.pop().unwrap();
1467 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1468 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1469 assert_eq!(v["title"], "Delete?");
1470 assert_eq!(v["message"], "This cannot be undone.");
1471 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1473 }
1474
1475 #[test]
1478 fn text_builders_carry_their_style() {
1479 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1480 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1481 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1482 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1483 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1484 }
1485
1486 #[test]
1487 fn layout_and_content_builders_produce_their_variants() {
1488 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1489 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1490 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1491 assert!(matches!(divider(), Widget::Divider));
1492 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1493 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1494 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1495 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)));
1496 let rc = with_bracket(
1497 region_chart(
1498 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1499 vec![ChartTick::new(3.0, "3 Mt.")],
1500 65.0, 80.0,
1501 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1502 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1503 ),
1504 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1505 );
1506 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1507 assert!(matches!(
1509 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1510 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1511 ));
1512 assert!(matches!(
1513 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1514 Widget::SwipeAction { actions, .. } if actions.len() == 1
1515 ));
1516 assert!(matches!(
1518 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1519 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1520 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1521 ));
1522 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1523 assert!(matches!(
1525 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1526 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1527 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1528 ));
1529 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1530 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1531 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1532 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1533 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1534 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1536 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1538 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1539 }
1540
1541 #[test]
1542 fn input_builders_carry_ids_values_and_event_tokens() {
1543 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1544 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1545 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1546 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1548 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1549 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1550 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1551 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1553 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1554 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1555 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1556 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1557 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1558 "p.jpg"), 9000), 1.5), 0.5));
1559 assert!(matches!(tuned,
1560 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1561 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1562 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1564 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1565 assert!(matches!(with_pip(divider()), Widget::Divider));
1567 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1568 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1569 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1570 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1571 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1572 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1573 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1574 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1575
1576 match chip("Latte", true, Ev::Open(2)) {
1577 Widget::Chip { selected, on_press, .. } => {
1578 assert!(selected);
1579 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1580 }
1581 other => panic!("expected Chip, got {other:?}"),
1582 }
1583 match stepper(5, Ev::Tap, Ev::Open(1)) {
1584 Widget::Stepper { value, on_decrement, on_increment } => {
1585 assert_eq!(value, 5);
1586 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1587 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1588 }
1589 other => panic!("expected Stepper, got {other:?}"),
1590 }
1591 let t = tab("Home", true, Ev::Tap);
1592 assert_eq!(t.label, "Home");
1593 assert!(t.selected);
1594 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1595 }
1596
1597 #[test]
1600 fn widget_tree_round_trips_through_serde() {
1601 let tree = scaffold(
1602 "Home",
1603 true,
1604 vec![tab("A", true, Ev::Tap)],
1605 column(vec![
1606 title("Hi"),
1607 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1608 image("u", ImageShape::Rounded, ImageRatio::Wide),
1609 slider("s", 2, 5),
1610 ]),
1611 );
1612 let s = serde_json::to_string(&tree).unwrap();
1613 let back: Widget = serde_json::from_str(&s).unwrap();
1614 assert_eq!(s, serde_json::to_string(&back).unwrap());
1615 }
1616
1617 #[test]
1618 fn actions_and_input_values_round_trip() {
1619 let actions = vec![
1620 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1621 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1622 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1623 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1624 Action::Restore { data: "blob".into() },
1625 Action::Start,
1626 ];
1627 for a in actions {
1628 let s = serde_json::to_string(&a).unwrap();
1629 let back: Action = serde_json::from_str(&s).unwrap();
1630 assert_eq!(s, serde_json::to_string(&back).unwrap());
1631 }
1632 }
1633
1634 #[derive(Default)]
1637 struct CounterModel {
1638 count: i32,
1639 restored: String,
1640 started: bool,
1641 last_input: String,
1642 }
1643
1644 #[derive(serde::Serialize, serde::Deserialize)]
1645 enum CounterEv {
1646 Inc,
1647 Add(i32),
1648 }
1649
1650 #[derive(Default)]
1651 struct CounterApp;
1652
1653 impl MobilerApp for CounterApp {
1654 type Event = CounterEv;
1655 type Model = CounterModel;
1656 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1657 match ev {
1658 CounterEv::Inc => model.count += 1,
1659 CounterEv::Add(n) => model.count += n,
1660 }
1661 }
1662 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1663 if let InputValue::Text(t) = value {
1664 model.last_input = format!("{id}={t}");
1665 }
1666 }
1667 fn restore(&self, data: &str, model: &mut CounterModel) {
1668 model.restored = data.to_string();
1669 }
1670 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1671 model.started = true;
1672 }
1673 fn view(&self, model: &CounterModel) -> Widget {
1674 text(format!("{}", model.count))
1675 }
1676 }
1677
1678 #[test]
1679 fn shell_dispatches_fired_input_restore_and_start() {
1680 use crux_core::App as _;
1681 let shell = MobilerShell::<CounterApp>::default();
1682 let mut m = CounterModel::default();
1683
1684 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1686 assert_eq!(m.count, 5);
1687 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1689 assert_eq!(m.last_input, "name=bob");
1690 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1692 assert_eq!(m.restored, "saved");
1693 let _ = shell.update(Action::Start, &mut m);
1695 assert!(m.started);
1696 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1698 }
1699
1700 #[test]
1701 fn shell_ignores_a_malformed_fired_token() {
1702 use crux_core::App as _;
1703 let shell = MobilerShell::<CounterApp>::default();
1704 let mut m = CounterModel::default();
1705 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1708 assert_eq!(m.count, 0);
1709 }
1710}