1use std::marker::PhantomData;
9
10pub mod bunny;
11pub mod format;
12pub use format::{Currency, Locale};
13
14use crux_core::{
15 App, Command,
16 capability::Operation,
17 macros::effect,
18 render::{RenderOperation, render},
19};
20use facet::Facet;
21use serde::{Deserialize, Serialize, de::DeserializeOwned};
22
23pub use mobiler_ui::{
24 A11yRole, Action, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
25 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
26 ImageRatio, ImageShape, InputValue, MapMarker, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
27 TextStyle, Theme, Tone, Widget,
28};
29
30#[effect(facet_typegen)]
34#[derive(Debug)]
35pub enum Effect {
36 Render(RenderOperation),
37 PluginNotify(PluginNotify),
39 Plugin(PluginCall),
41 PluginStream(PluginStreamCall),
46}
47
48#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
49pub struct PluginNotify {
50 pub plugin: String,
51 pub op: String,
52 pub input: String,
53}
54impl Operation for PluginNotify {
55 type Output = ();
56}
57
58#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
59pub struct PluginCall {
60 pub plugin: String,
61 pub op: String,
62 pub input: String,
63}
64impl Operation for PluginCall {
65 type Output = PluginResponse;
66}
67
68#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
72pub struct PluginStreamCall {
73 pub key: String,
74 pub plugin: String,
75 pub op: String,
76 pub input: String,
77}
78impl Operation for PluginStreamCall {
79 type Output = PluginResponse;
80}
81
82#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
83pub struct PluginResponse {
84 pub ok: bool,
85 pub output: String,
86}
87
88type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
89type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
91
92pub struct Cx<E> {
95 notifications: Vec<PluginNotify>,
96 requests: Vec<(PluginCall, Continuation<E>)>,
97 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
98}
99
100impl<E> Default for Cx<E> {
101 fn default() -> Self {
102 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
103 }
104}
105
106impl<E> Cx<E> {
107 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
109 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
110 }
111
112 pub fn plugin(
115 &mut self,
116 plugin: impl Into<String>,
117 op: impl Into<String>,
118 input: impl Into<String>,
119 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
120 ) {
121 self.requests
122 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
123 }
124
125 pub fn subscribe(
133 &mut self,
134 key: impl Into<String>,
135 plugin: impl Into<String>,
136 op: impl Into<String>,
137 input: impl Into<String>,
138 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
139 ) {
140 self.streams.push((
141 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
142 Box::new(on_event),
143 ));
144 }
145
146 pub fn unsubscribe(&mut self, key: impl Into<String>) {
150 self.notify("stream", "unsubscribe", key);
151 }
152
153 pub fn save(&mut self, data: impl Into<String>) {
155 self.notify("storage", "save", data);
156 }
157
158 pub fn copy(&mut self, text: impl Into<String>) {
160 self.notify("clipboard", "copy", text);
161 }
162
163 pub fn share(&mut self, text: impl Into<String>) {
165 self.notify("share", "text", text);
166 }
167
168 pub fn open_url(&mut self, url: impl Into<String>) {
171 self.notify("browser", "open", url);
172 }
173
174 pub fn toast(&mut self, text: impl Into<String>) {
176 self.notify("toast", "show", text);
177 }
178
179 pub fn haptic(&mut self, style: impl Into<String>) {
182 self.notify("haptics", style, "");
183 }
184
185 pub fn http(
190 &mut self,
191 method: impl Into<String>,
192 url: impl Into<String>,
193 body: Option<String>,
194 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
195 ) {
196 #[derive(Serialize)]
197 struct HttpReq {
198 url: String,
199 body: Option<String>,
200 }
201 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
202 .expect("serialize http request");
203 self.plugin("http", method, input, then);
204 }
205
206 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
208 self.http("GET", url, None, then);
209 }
210 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
212 self.http("POST", url, Some(body.into()), then);
213 }
214 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
216 self.http("PATCH", url, Some(body.into()), then);
217 }
218 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
220 self.http("DELETE", url, None, then);
221 }
222
223 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
227 self.plugin("device", "model", "", then);
228 }
229
230 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
235 self.plugin("device", "locale", "", then);
236 }
237
238 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
243 self.plugin("photo", "pick", "", then);
244 }
245
246 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
253 self.plugin("camera", "capture", "", then);
254 }
255
256 pub fn confirm(
260 &mut self,
261 title: impl Into<String>,
262 message: impl Into<String>,
263 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
264 ) {
265 #[derive(Serialize)]
266 struct Confirm {
267 title: String,
268 message: String,
269 }
270 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
271 .expect("serialize confirm");
272 self.plugin("dialog", "confirm", input, then);
273 }
274
275 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
280 self.plugin("datetime", "date", "", then);
281 }
282
283 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
288 self.plugin("datetime", "time", "", then);
289 }
290}
291
292pub trait MobilerApp: Default {
297 type Event: Serialize + DeserializeOwned + Send + 'static;
298 type Model: Default;
299
300 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
301
302 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
303 let _ = (id, value, model, cx);
304 }
305
306 fn restore(&self, data: &str, model: &mut Self::Model) {
309 let _ = (data, model);
310 }
311
312 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
315 let _ = (model, cx);
316 }
317
318 fn view(&self, model: &Self::Model) -> Widget;
319}
320
321pub struct MobilerShell<A>(PhantomData<fn() -> A>);
323
324impl<A> Default for MobilerShell<A> {
325 fn default() -> Self {
326 Self(PhantomData)
327 }
328}
329
330impl<A: MobilerApp> App for MobilerShell<A> {
331 type Event = Action;
332 type Model = A::Model;
333 type ViewModel = Widget;
334 type Effect = Effect;
335
336 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
337 let app = A::default();
338 let mut cx = Cx::<A::Event>::default();
339 match action {
340 Action::Fired { token } => {
341 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
342 app.update(event, model, &mut cx);
343 }
344 }
345 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
346 Action::Restore { data } => app.restore(&data, model),
347 Action::Start => app.init(model, &mut cx),
348 }
349 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
350 for op in cx.notifications {
351 commands.push(Command::notify_shell(op).build());
352 }
353 for (op, then) in cx.requests {
354 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
355 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
356 }));
357 }
358 for (op, then) in cx.streams {
359 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
362 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
363 }));
364 }
365 commands.push(render());
366 Command::all(commands)
367 }
368
369 fn view(&self, model: &Self::Model) -> Widget {
370 A::default().view(model)
371 }
372}
373
374#[derive(Clone, Debug)]
393pub struct Nav<R> {
394 stack: Vec<R>,
395}
396
397impl<R: Clone + Serialize> Nav<R> {
398 #[must_use]
400 pub fn new(root: R) -> Self {
401 Self { stack: vec![root] }
402 }
403 pub fn push(&mut self, route: R) {
405 self.stack.push(route);
406 }
407 pub fn pop(&mut self) {
409 if self.stack.len() > 1 {
410 self.stack.pop();
411 }
412 }
413 pub fn reset(&mut self, root: R) {
415 self.stack = vec![root];
416 }
417 #[must_use]
419 pub fn current(&self) -> &R {
420 self.stack.last().expect("nav stack is never empty")
421 }
422 #[must_use]
424 pub fn depth(&self) -> u32 {
425 self.stack.len() as u32
426 }
427 #[must_use]
429 pub fn can_go_back(&self) -> bool {
430 self.stack.len() > 1
431 }
432 fn route_key(&self) -> String {
435 serde_json::to_string(self.current()).expect("serialize route")
436 }
437}
438
439fn tok<E: Serialize>(event: E) -> String {
443 serde_json::to_string(&event).expect("serialize event")
444}
445
446#[must_use]
447pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
448 Widget::Text { content: content.into(), style }
449}
450#[must_use]
451pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
452#[must_use]
453pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
454#[must_use]
455pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
456#[must_use]
457pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
458#[must_use]
459pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
460
461#[must_use]
462pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
463 Widget::Image { source: source.into(), shape, ratio }
464}
465#[must_use]
466pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
467 Widget::Badge { label: label.into(), tone }
468}
469#[must_use]
471pub fn color_dot(color: ProjectColor) -> Widget {
472 Widget::ColorDot { color }
473}
474#[must_use]
475pub fn divider() -> Widget { Widget::Divider }
476#[must_use]
478pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
479#[must_use]
481pub fn skeleton() -> Widget { Widget::Skeleton }
482#[must_use]
486pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
487#[must_use]
496pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
497 Widget::Video {
498 url: url.into(),
499 id: id.into(),
500 playing,
501 seek_to_ms,
502 controls: true,
503 looping: false,
504 muted: false,
505 on_ended: Some(tok(on_ended)),
506 poster: None,
507 start_at_ms: -1,
508 captions: Vec::new(),
509 rate: 1.0,
510 volume: 1.0,
511 urls: Vec::new(),
512 start_index: 0,
513 seek_index: -1,
514 allow_pip: false,
515 }
516}
517#[must_use]
523pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
524 Widget::Video {
525 url: urls.first().cloned().unwrap_or_default(),
526 id: id.into(),
527 playing,
528 seek_to_ms: -1,
529 controls: true,
530 looping: false,
531 muted: false,
532 on_ended: Some(tok(on_ended)),
533 poster: None,
534 start_at_ms: -1,
535 captions: Vec::new(),
536 rate: 1.0,
537 volume: 1.0,
538 urls,
539 start_index,
540 seek_index: -1,
541 allow_pip: false,
542 }
543}
544fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
547 match widget {
548 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
549 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
550 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
551 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
552 f(&mut v);
553 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
554 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
555 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
556 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
557 allow_pip: v.allow_pip }
558 }
559 other => other,
560 }
561}
562struct VideoFields {
563 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
564 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
565 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
566 seek_index: i64, allow_pip: bool,
567}
568#[must_use]
570pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
571#[must_use]
573pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
574#[must_use]
576pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
577#[must_use]
579pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
580 let poster = poster.into();
581 map_video(widget, move |v| v.poster = Some(poster))
582}
583#[must_use]
585pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
586 map_video(widget, move |v| v.start_at_ms = start_at_ms)
587}
588#[must_use]
590pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
591 map_video(widget, move |v| v.captions = captions)
592}
593#[must_use]
595pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
596#[must_use]
598pub fn with_volume(widget: Widget, volume: f32) -> Widget {
599 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
600}
601#[must_use]
603pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
604 map_video(widget, move |v| v.seek_index = index)
605}
606#[must_use]
608pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
609#[must_use]
614pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
615
616#[must_use]
622pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
623 Widget::Map {
624 id: id.into(),
625 center_lat,
626 center_lng,
627 zoom,
628 markers: Vec::new(),
629 style_url: None,
630 interactive: true,
631 }
632}
633#[must_use]
635pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
636 match widget {
637 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
638 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
639 other => other,
640 }
641}
642#[must_use]
644pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
645 match widget {
646 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
647 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
648 other => other,
649 }
650}
651#[must_use]
653pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
654 MapMarker { id: id.into(), lat, lng, title: None }
655}
656#[must_use]
658pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
659 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
660}
661fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
663 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
664}
665
666#[must_use]
669pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
670 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
671}
672#[must_use]
675pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
676 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
677}
678#[must_use]
682pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
683 Widget::Chart { series, labels, style, axis, legend }
684}
685#[must_use]
687pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
688 chart(series, labels, ChartStyle::StackedBar, true, true)
689}
690#[must_use]
692pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
693 chart(series, labels, ChartStyle::StackedBar100, false, true)
694}
695#[must_use]
697pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
698 chart(series, vec![], ChartStyle::Pie, false, true)
699}
700#[must_use]
702pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
703 chart(series, vec![], ChartStyle::Donut, false, true)
704}
705#[must_use]
708pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
709 chart(series, vec![], ChartStyle::Rings, false, true)
710}
711#[must_use]
713pub fn gauge_chart(series: ChartSeries) -> Widget {
714 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
715}
716
717#[must_use]
722pub fn region_chart(
723 regions: Vec<ChartRegion>,
724 ticks: Vec<ChartTick>,
725 x_max: f32,
726 y_max: f32,
727 ref_lines: Vec<ChartRefLine>,
728 legend: Vec<ChartLegendItem>,
729) -> Widget {
730 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
731}
732
733#[must_use]
735pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
736 match widget {
737 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
738 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
739 }
740 other => other,
741 }
742}
743
744fn days_in_month(year: u32, month: u8) -> u8 {
746 match month {
747 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
748 4 | 6 | 9 | 11 => 30,
749 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
750 _ => 30,
751 }
752}
753
754fn weekday(year: u32, month: u8, day: u8) -> u8 {
756 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
757 let y = if month < 3 { year - 1 } else { year };
758 let m = month as usize - 1;
759 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
760}
761
762#[must_use]
766pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
767 let n = days_in_month(year, month);
768 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
769 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
770}
771
772#[must_use]
775pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
776 Widget::SwipeAction {
777 child: Box::new(child),
778 actions: actions
779 .into_iter()
780 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
781 .collect(),
782 }
783}
784#[must_use]
785pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
786
787#[must_use]
788pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
789#[must_use]
790pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
791#[must_use]
792pub fn card(child: Widget, style: CardStyle) -> Widget {
793 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
794}
795#[must_use]
797pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
798 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
799}
800#[must_use]
803pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
804 match widget {
805 Widget::Card { child, style, on_press, .. } => Widget::Card {
806 child,
807 style,
808 on_press,
809 on_long_press: Some(tok(on_long_press)),
810 },
811 other => other,
812 }
813}
814#[must_use]
817pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
818 Widget::Box { children, align, scrim }
819}
820#[must_use]
821pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
822#[must_use]
827pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
828 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
829}
830#[must_use]
832pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
833#[must_use]
835pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
836#[must_use]
838pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
839 Widget::Avatar { source: source.into(), status: Some(status) }
840}
841#[must_use]
843pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
844#[must_use]
846pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
847 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
848}
849
850#[must_use]
851pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
852 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
853}
854#[must_use]
855pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
856 Widget::IconButton { icon, on_press: tok(on_press) }
857}
858#[must_use]
859pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
860 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
861}
862#[must_use]
863pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
864 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
865}
866#[must_use]
870pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
871 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
872}
873#[must_use]
875pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
876 field(id, placeholder, value, FieldKind::Secure, None)
877}
878#[must_use]
880pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
881 field(id, placeholder, value, FieldKind::Email, None)
882}
883#[must_use]
885pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
886 field(id, placeholder, value, FieldKind::Number, None)
887}
888#[must_use]
890pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
891 field(id, placeholder, value, FieldKind::Decimal, None)
892}
893#[must_use]
895pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
896 field(id, placeholder, value, FieldKind::Phone, None)
897}
898#[must_use]
900pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
901 field(id, placeholder, value, FieldKind::Url, None)
902}
903#[must_use]
905pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
906 field(id, placeholder, value, FieldKind::Multiline, None)
907}
908#[must_use]
911pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
912 match widget {
913 Widget::TextField { id, placeholder, value, kind, .. } =>
914 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
915 other => other,
916 }
917}
918
919#[must_use]
923pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
924 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
925}
926#[must_use]
929pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
930 match widget {
931 Widget::A11y { child, label, role, .. } =>
932 Widget::A11y { child, label, hint: Some(hint.into()), role },
933 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
934 }
935}
936#[must_use]
938pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
939 match widget {
940 Widget::A11y { child, label, hint, .. } =>
941 Widget::A11y { child, label, hint, role: Some(role) },
942 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
943 }
944}
945#[must_use]
947pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
948 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
949}
950#[must_use]
952pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
953 Segment { label: label.into(), selected, on_select: tok(on_select) }
954}
955#[must_use]
957pub fn segmented(segments: Vec<Segment>) -> Widget {
958 Widget::Segmented { segments }
959}
960#[must_use]
961pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
962 Widget::Toggle { id: id.into(), label: label.into(), value }
963}
964#[must_use]
965pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
966 Widget::Checkbox { id: id.into(), label: label.into(), value }
967}
968#[must_use]
969pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
970 Widget::Slider { id: id.into(), value, max }
971}
972#[must_use]
973pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
974 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
975}
976
977#[must_use]
979pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
980 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
981}
982
983#[must_use]
985pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
986 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
987}
988
989#[must_use]
992pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
993 let title = title.into();
994 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 }
996}
997
998#[must_use]
1002pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1003 let title = title.into();
1004 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 }
1005}
1006
1007#[must_use]
1012pub fn nav_scaffold<R, E>(
1013 title: impl Into<String>,
1014 dark_mode: bool,
1015 tabs: Vec<Tab>,
1016 body: Widget,
1017 nav: &Nav<R>,
1018 on_back: E,
1019) -> Widget
1020where
1021 R: Clone + Serialize,
1022 E: Serialize,
1023{
1024 Widget::Scaffold {
1025 title: title.into(),
1026 body: Box::new(body),
1027 tabs,
1028 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1029 dark_mode,
1030 theme: None,
1031 fab: None,
1032 sheet: None,
1033 on_refresh: None,
1034 refreshing: false,
1035 route: nav.route_key(),
1036 depth: nav.depth(),
1037 }
1038}
1039
1040pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1044 match widget {
1045 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1046 title,
1047 body,
1048 tabs,
1049 back,
1050 dark_mode,
1051 theme: Some(theme),
1052 fab,
1053 sheet,
1054 on_refresh,
1055 refreshing,
1056 route,
1057 depth,
1058 },
1059 other => other,
1060 }
1061}
1062
1063pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1066 match widget {
1067 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1068 title,
1069 body,
1070 tabs,
1071 back,
1072 dark_mode,
1073 theme,
1074 fab: Some(Fab { icon, on_press: tok(on_press) }),
1075 sheet,
1076 on_refresh,
1077 refreshing,
1078 route,
1079 depth,
1080 },
1081 other => other,
1082 }
1083}
1084
1085pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1088 match widget {
1089 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1090 title: t,
1091 body,
1092 tabs,
1093 back,
1094 dark_mode,
1095 theme,
1096 fab,
1097 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1098 on_refresh,
1099 refreshing,
1100 route,
1101 depth,
1102 },
1103 other => other,
1104 }
1105}
1106
1107pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1111 match widget {
1112 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1113 title,
1114 body,
1115 tabs,
1116 back,
1117 dark_mode,
1118 theme,
1119 fab,
1120 sheet,
1121 on_refresh: Some(tok(on_refresh)),
1122 refreshing,
1123 route,
1124 depth,
1125 },
1126 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1129 children,
1130 on_load_more,
1131 loading,
1132 has_more,
1133 on_refresh: Some(tok(on_refresh)),
1134 refreshing,
1135 },
1136 other => other,
1137 }
1138}
1139
1140#[must_use]
1146pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1147 Widget::LazyList {
1148 children,
1149 on_load_more: Some(tok(on_load_more)),
1150 loading,
1151 has_more,
1152 on_refresh: None,
1153 refreshing: false,
1154 }
1155}
1156
1157#[must_use]
1159pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1160 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165 use super::*;
1166 use serde::Serialize;
1167
1168 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1169 enum Route {
1170 Home,
1171 Detail(u32),
1172 }
1173
1174 #[derive(Serialize)]
1175 enum Ev {
1176 Tap,
1177 Open(u32),
1178 }
1179
1180 #[test]
1183 fn nav_push_pop_depth() {
1184 let mut nav = Nav::new(Route::Home);
1185 assert_eq!(nav.depth(), 1);
1186 assert!(!nav.can_go_back());
1187
1188 nav.push(Route::Detail(7));
1189 assert_eq!(nav.depth(), 2);
1190 assert!(nav.can_go_back());
1191 assert!(matches!(nav.current(), Route::Detail(7)));
1192
1193 nav.pop();
1194 assert_eq!(nav.depth(), 1);
1195 assert!(matches!(nav.current(), Route::Home));
1196
1197 nav.pop(); assert_eq!(nav.depth(), 1);
1199 }
1200
1201 #[test]
1202 fn nav_reset_replaces_stack() {
1203 let mut nav = Nav::new(Route::Home);
1204 nav.push(Route::Detail(1));
1205 nav.push(Route::Detail(2));
1206 nav.reset(Route::Detail(9));
1207 assert_eq!(nav.depth(), 1);
1208 assert!(matches!(nav.current(), Route::Detail(9)));
1209 }
1210
1211 #[test]
1212 fn nav_route_key_is_serialization() {
1213 let nav = Nav::new(Route::Detail(3));
1214 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1215 }
1216
1217 #[test]
1220 fn scaffold_sets_route_depth_and_no_back() {
1221 match scaffold("Home", false, vec![], text("x")) {
1222 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1223 assert_eq!(route, "Home");
1224 assert_eq!(depth, 1);
1225 assert!(back.is_none());
1226 assert!(!dark_mode);
1227 }
1228 other => panic!("expected Scaffold, got {other:?}"),
1229 }
1230 }
1231
1232 #[test]
1233 fn scaffold_back_is_depth_2_with_back() {
1234 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1235 Widget::Scaffold { depth, back, dark_mode, .. } => {
1236 assert_eq!(depth, 2);
1237 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1238 assert!(dark_mode);
1239 }
1240 other => panic!("expected Scaffold, got {other:?}"),
1241 }
1242 }
1243
1244 #[test]
1245 fn nav_scaffold_shows_back_only_when_poppable() {
1246 let mut nav = Nav::new(Route::Home);
1247 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1249 Widget::Scaffold { back, depth, route, .. } => {
1250 assert!(back.is_none());
1251 assert_eq!(depth, 1);
1252 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1253 }
1254 other => panic!("expected Scaffold, got {other:?}"),
1255 }
1256 nav.push(Route::Detail(2));
1258 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1259 Widget::Scaffold { back, depth, .. } => {
1260 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1261 assert_eq!(depth, 2);
1262 }
1263 other => panic!("expected Scaffold, got {other:?}"),
1264 }
1265 }
1266
1267 #[test]
1268 fn buttons_carry_serialized_event_tokens() {
1269 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1270 Widget::Button { label, on_press, .. } => {
1271 assert_eq!(label, "Go");
1272 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1273 }
1274 other => panic!("expected Button, got {other:?}"),
1275 }
1276 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1277 Widget::Card { on_press, .. } => {
1278 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1279 }
1280 other => panic!("expected Card, got {other:?}"),
1281 }
1282 match card(text("c"), CardStyle::Elevated) {
1284 Widget::Card { on_press, on_long_press, .. } => {
1285 assert!(on_press.is_none());
1286 assert!(on_long_press.is_none());
1287 }
1288 other => panic!("expected Card, got {other:?}"),
1289 }
1290 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1292 Widget::Card { on_press, on_long_press, .. } => {
1293 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1294 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1295 }
1296 other => panic!("expected Card, got {other:?}"),
1297 }
1298 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1300 }
1301
1302 #[test]
1305 fn cx_notify_and_save_enqueue_notifications() {
1306 let mut cx = Cx::<Ev>::default();
1307 cx.notify("toast", "show", "hi");
1308 cx.save("blob");
1309 assert_eq!(cx.notifications.len(), 2);
1310 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1311 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1312 assert!(cx.requests.is_empty());
1313 }
1314
1315 #[test]
1316 fn cx_http_helpers_build_requests() {
1317 let mut cx = Cx::<Ev>::default();
1318 cx.get("http://h/x", |_| Ev::Tap);
1319 cx.post("http://h/y", "hello", |_| Ev::Tap);
1320 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1321 cx.delete("http://h/d", |_| Ev::Tap);
1322
1323 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1324 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1325 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1326
1327 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1328 assert_eq!(get_input["url"], "http://h/x");
1329 assert!(get_input["body"].is_null());
1330
1331 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1332 assert_eq!(post_input["url"], "http://h/y");
1333 assert_eq!(post_input["body"], "hello");
1334 }
1335
1336 #[test]
1337 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1338 let mut cx = Cx::<Ev>::default();
1339 cx.pick_photo(|_| Ev::Tap);
1340 cx.capture_photo(|_| Ev::Tap);
1341 assert_eq!(cx.requests.len(), 2);
1342 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", ""));
1345 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", ""));
1346 }
1347
1348 #[test]
1349 fn cx_capture_photo_routes_success_and_cancel() {
1350 let mut cx = Cx::<Ev>::default();
1352 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1353 let (_, then) = cx.requests.pop().unwrap();
1354 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1355
1356 let mut cx = Cx::<Ev>::default();
1358 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1359 let (_, then) = cx.requests.pop().unwrap();
1360 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1361 }
1362
1363 #[test]
1364 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1365 let mut cx = Cx::<Ev>::default();
1366 cx.copy("c");
1367 cx.share("s");
1368 cx.open_url("u");
1369 cx.toast("t");
1370 cx.haptic("heavy");
1371 let got: Vec<(&str, &str, &str)> = cx
1372 .notifications
1373 .iter()
1374 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1375 .collect();
1376 assert_eq!(
1377 got,
1378 vec![
1379 ("clipboard", "copy", "c"),
1380 ("share", "text", "s"),
1381 ("browser", "open", "u"),
1382 ("toast", "show", "t"),
1383 ("haptics", "heavy", ""), ]
1385 );
1386 assert!(cx.requests.is_empty());
1387 }
1388
1389 #[test]
1390 fn cx_device_model_is_a_request_not_a_notification() {
1391 let mut cx = Cx::<Ev>::default();
1392 cx.device_model(|_| Ev::Tap);
1393 assert!(cx.notifications.is_empty());
1394 assert_eq!(cx.requests.len(), 1);
1395 let (call, _) = &cx.requests[0];
1396 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1397 }
1398
1399 #[test]
1400 fn cx_device_locale_requests_the_device_locale_op() {
1401 let mut cx = Cx::<Ev>::default();
1402 cx.device_locale(|_| Ev::Tap);
1403 assert!(cx.notifications.is_empty());
1404 assert_eq!(cx.requests.len(), 1);
1405 let (call, _) = &cx.requests[0];
1406 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1407 }
1408
1409 #[test]
1410 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1411 let mut cx = Cx::<Ev>::default();
1412 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1413 assert!(cx.notifications.is_empty());
1415 assert!(cx.requests.is_empty());
1416 assert_eq!(cx.streams.len(), 1);
1417 let (call, on_event) = &cx.streams[0];
1418 assert_eq!(
1419 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1420 ("ws", "websocket", "stream", "wss://h/x")
1421 );
1422 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1424 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1425 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1426 }
1427
1428 #[test]
1429 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1430 let mut cx = Cx::<Ev>::default();
1431 cx.unsubscribe("ws");
1432 assert!(cx.streams.is_empty());
1433 assert_eq!(cx.notifications.len(), 1);
1434 assert_eq!(
1436 cx.notifications[0],
1437 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1438 );
1439 }
1440
1441 #[test]
1442 fn cx_confirm_serializes_title_message_and_routes_ok() {
1443 let mut cx = Cx::<Ev>::default();
1444 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1445 let (call, then) = cx.requests.pop().unwrap();
1446 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1447 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1448 assert_eq!(v["title"], "Delete?");
1449 assert_eq!(v["message"], "This cannot be undone.");
1450 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1452 }
1453
1454 #[test]
1457 fn text_builders_carry_their_style() {
1458 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1459 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1460 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1461 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1462 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1463 }
1464
1465 #[test]
1466 fn layout_and_content_builders_produce_their_variants() {
1467 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1468 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1469 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1470 assert!(matches!(divider(), Widget::Divider));
1471 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1472 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1473 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1474 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)));
1475 let rc = with_bracket(
1476 region_chart(
1477 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1478 vec![ChartTick::new(3.0, "3 Mt.")],
1479 65.0, 80.0,
1480 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1481 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1482 ),
1483 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1484 );
1485 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1486 assert!(matches!(
1488 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1489 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1490 ));
1491 assert!(matches!(
1492 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1493 Widget::SwipeAction { actions, .. } if actions.len() == 1
1494 ));
1495 assert!(matches!(
1497 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1498 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1499 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1500 ));
1501 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1502 assert!(matches!(
1504 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1505 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1506 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1507 ));
1508 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1509 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1510 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1511 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1512 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1513 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1515 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1517 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1518 }
1519
1520 #[test]
1521 fn input_builders_carry_ids_values_and_event_tokens() {
1522 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1523 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1524 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1525 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1527 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1528 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1529 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1530 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1532 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1533 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1534 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1535 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1536 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1537 "p.jpg"), 9000), 1.5), 0.5));
1538 assert!(matches!(tuned,
1539 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1540 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1541 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1543 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1544 assert!(matches!(with_pip(divider()), Widget::Divider));
1546 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1547 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1548 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1549 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1550 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1551 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1552 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1553 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1554
1555 match chip("Latte", true, Ev::Open(2)) {
1556 Widget::Chip { selected, on_press, .. } => {
1557 assert!(selected);
1558 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1559 }
1560 other => panic!("expected Chip, got {other:?}"),
1561 }
1562 match stepper(5, Ev::Tap, Ev::Open(1)) {
1563 Widget::Stepper { value, on_decrement, on_increment } => {
1564 assert_eq!(value, 5);
1565 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1566 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1567 }
1568 other => panic!("expected Stepper, got {other:?}"),
1569 }
1570 let t = tab("Home", true, Ev::Tap);
1571 assert_eq!(t.label, "Home");
1572 assert!(t.selected);
1573 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1574 }
1575
1576 #[test]
1579 fn widget_tree_round_trips_through_serde() {
1580 let tree = scaffold(
1581 "Home",
1582 true,
1583 vec![tab("A", true, Ev::Tap)],
1584 column(vec![
1585 title("Hi"),
1586 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1587 image("u", ImageShape::Rounded, ImageRatio::Wide),
1588 slider("s", 2, 5),
1589 ]),
1590 );
1591 let s = serde_json::to_string(&tree).unwrap();
1592 let back: Widget = serde_json::from_str(&s).unwrap();
1593 assert_eq!(s, serde_json::to_string(&back).unwrap());
1594 }
1595
1596 #[test]
1597 fn actions_and_input_values_round_trip() {
1598 let actions = vec![
1599 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1600 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1601 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1602 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1603 Action::Restore { data: "blob".into() },
1604 Action::Start,
1605 ];
1606 for a in actions {
1607 let s = serde_json::to_string(&a).unwrap();
1608 let back: Action = serde_json::from_str(&s).unwrap();
1609 assert_eq!(s, serde_json::to_string(&back).unwrap());
1610 }
1611 }
1612
1613 #[derive(Default)]
1616 struct CounterModel {
1617 count: i32,
1618 restored: String,
1619 started: bool,
1620 last_input: String,
1621 }
1622
1623 #[derive(serde::Serialize, serde::Deserialize)]
1624 enum CounterEv {
1625 Inc,
1626 Add(i32),
1627 }
1628
1629 #[derive(Default)]
1630 struct CounterApp;
1631
1632 impl MobilerApp for CounterApp {
1633 type Event = CounterEv;
1634 type Model = CounterModel;
1635 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1636 match ev {
1637 CounterEv::Inc => model.count += 1,
1638 CounterEv::Add(n) => model.count += n,
1639 }
1640 }
1641 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1642 if let InputValue::Text(t) = value {
1643 model.last_input = format!("{id}={t}");
1644 }
1645 }
1646 fn restore(&self, data: &str, model: &mut CounterModel) {
1647 model.restored = data.to_string();
1648 }
1649 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1650 model.started = true;
1651 }
1652 fn view(&self, model: &CounterModel) -> Widget {
1653 text(format!("{}", model.count))
1654 }
1655 }
1656
1657 #[test]
1658 fn shell_dispatches_fired_input_restore_and_start() {
1659 use crux_core::App as _;
1660 let shell = MobilerShell::<CounterApp>::default();
1661 let mut m = CounterModel::default();
1662
1663 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1665 assert_eq!(m.count, 5);
1666 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1668 assert_eq!(m.last_input, "name=bob");
1669 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1671 assert_eq!(m.restored, "saved");
1672 let _ = shell.update(Action::Start, &mut m);
1674 assert!(m.started);
1675 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1677 }
1678
1679 #[test]
1680 fn shell_ignores_a_malformed_fired_token() {
1681 use crux_core::App as _;
1682 let shell = MobilerShell::<CounterApp>::default();
1683 let mut m = CounterModel::default();
1684 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1687 assert_eq!(m.count, 0);
1688 }
1689}