1use std::marker::PhantomData;
9
10pub mod bunny;
11pub mod dialog;
12pub mod format;
13pub mod http;
14pub mod i18n;
15pub mod transfer;
16pub use dialog::{Confirm, Picker};
17pub use format::{Currency, Locale, Weekday};
18pub use http::{HttpHeader, HttpOutcome};
19pub use i18n::{Catalog, negotiate};
20pub use transfer::TransferEvent;
21
22use crux_core::{
23 App, Command,
24 capability::Operation,
25 macros::effect,
26 render::{RenderOperation, render},
27};
28use facet::Facet;
29use serde::{Deserialize, Serialize, de::DeserializeOwned};
30
31pub use mobiler_ui::{
32 A11yRole, Action, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
33 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
34 ImageRatio, ImageShape, InputValue, MapMarker, ProjectColor, Rgb, Segment, Sheet, ShellLabels, Spacing, SwipeButton, Tab,
35 TextStyle, Theme, Tone, Widget,
36};
37
38#[effect(facet_typegen)]
42#[derive(Debug)]
43pub enum Effect {
44 Render(RenderOperation),
45 PluginNotify(PluginNotify),
47 Plugin(PluginCall),
49 PluginStream(PluginStreamCall),
54}
55
56#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
57pub struct PluginNotify {
58 pub plugin: String,
59 pub op: String,
60 pub input: String,
61}
62impl Operation for PluginNotify {
63 type Output = ();
64}
65
66#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
67pub struct PluginCall {
68 pub plugin: String,
69 pub op: String,
70 pub input: String,
71}
72impl Operation for PluginCall {
73 type Output = PluginResponse;
74}
75
76#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
80pub struct PluginStreamCall {
81 pub key: String,
82 pub plugin: String,
83 pub op: String,
84 pub input: String,
85}
86impl Operation for PluginStreamCall {
87 type Output = PluginResponse;
88}
89
90#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
99pub struct PluginResponse {
100 pub ok: bool,
101 pub output: Vec<u8>,
102}
103
104impl PluginResponse {
105 pub fn text(ok: bool, s: impl Into<String>) -> Self {
107 Self { ok, output: s.into().into_bytes() }
108 }
109
110 pub fn as_text(&self) -> Option<&str> {
112 std::str::from_utf8(&self.output).ok()
113 }
114}
115
116type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
117type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
119
120pub struct Cx<E> {
123 notifications: Vec<PluginNotify>,
124 requests: Vec<(PluginCall, Continuation<E>)>,
125 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
126}
127
128impl<E> Default for Cx<E> {
129 fn default() -> Self {
130 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
131 }
132}
133
134impl<E> Cx<E> {
135 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
137 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
138 }
139
140 pub fn plugin(
143 &mut self,
144 plugin: impl Into<String>,
145 op: impl Into<String>,
146 input: impl Into<String>,
147 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
148 ) {
149 self.requests
150 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
151 }
152
153 pub fn subscribe(
161 &mut self,
162 key: impl Into<String>,
163 plugin: impl Into<String>,
164 op: impl Into<String>,
165 input: impl Into<String>,
166 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
167 ) {
168 self.streams.push((
169 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
170 Box::new(on_event),
171 ));
172 }
173
174 pub fn unsubscribe(&mut self, key: impl Into<String>) {
178 self.notify("stream", "unsubscribe", key);
179 }
180
181 pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
184 crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
185 }
186
187 pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
190 crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
191 }
192
193 pub fn save(&mut self, data: impl Into<String>) {
195 self.notify("storage", "save", data);
196 }
197
198 pub fn copy(&mut self, text: impl Into<String>) {
200 self.notify("clipboard", "copy", text);
201 }
202
203 pub fn share(&mut self, text: impl Into<String>) {
205 self.notify("share", "text", text);
206 }
207
208 pub fn open_url(&mut self, url: impl Into<String>) {
211 self.notify("browser", "open", url);
212 }
213
214 pub fn toast(&mut self, text: impl Into<String>) {
216 self.notify("toast", "show", text);
217 }
218
219 pub fn haptic(&mut self, style: impl Into<String>) {
222 self.notify("haptics", style, "");
223 }
224
225 pub fn request(
240 &mut self,
241 method: impl Into<String>,
242 url: impl Into<String>,
243 ) -> crate::http::RequestBuilder<'_, E> {
244 crate::http::RequestBuilder::new(self, method.into(), url.into())
245 }
246
247 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
249 self.request("GET", url).send(then);
250 }
251 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
253 self.request("POST", url).body(body).send(then);
254 }
255 pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
257 self.request("PUT", url).body(body).send(then);
258 }
259 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
261 self.request("PATCH", url).body(body).send(then);
262 }
263 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
265 self.request("DELETE", url).send(then);
266 }
267
268 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
272 self.plugin("device", "model", "", then);
273 }
274
275 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
280 self.plugin("device", "locale", "", then);
281 }
282
283 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
288 self.plugin("photo", "pick", "", then);
289 }
290
291 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
298 self.plugin("camera", "capture", "", then);
299 }
300
301 pub fn confirm(
305 &mut self,
306 title: impl Into<String>,
307 message: impl Into<String>,
308 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
309 ) {
310 self.confirm_with(Confirm::new(title, message), then);
311 }
312
313 pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
317 self.plugin("dialog", "confirm", dialog.to_input(), then);
318 }
319
320 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
325 self.plugin("datetime", "date", "", then);
326 }
327
328 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
333 self.plugin("datetime", "time", "", then);
334 }
335
336 pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
338 self.plugin("datetime", "date", picker.to_input(), then);
339 }
340
341 pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
343 self.plugin("datetime", "time", picker.to_input(), then);
344 }
345
346 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
353 self.plugin("datetime", "now", "", then);
354 }
355}
356
357pub trait MobilerApp: Default {
362 type Event: Serialize + DeserializeOwned + Send + 'static;
363 type Model: Default;
364
365 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
366
367 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
368 let _ = (id, value, model, cx);
369 }
370
371 fn restore(&self, data: &str, model: &mut Self::Model) {
374 let _ = (data, model);
375 }
376
377 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
380 let _ = (model, cx);
381 }
382
383 fn view(&self, model: &Self::Model) -> Widget;
384}
385
386pub struct MobilerShell<A>(PhantomData<fn() -> A>);
388
389impl<A> Default for MobilerShell<A> {
390 fn default() -> Self {
391 Self(PhantomData)
392 }
393}
394
395impl<A: MobilerApp> App for MobilerShell<A> {
396 type Event = Action;
397 type Model = A::Model;
398 type ViewModel = Widget;
399 type Effect = Effect;
400
401 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
402 let app = A::default();
403 let mut cx = Cx::<A::Event>::default();
404 match action {
405 Action::Fired { token } => {
406 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
407 app.update(event, model, &mut cx);
408 }
409 }
410 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
411 Action::Restore { data } => app.restore(&data, model),
412 Action::Start => app.init(model, &mut cx),
413 }
414 let mut commands: Vec<Command<Effect, Action>> = vec![render()];
420 for op in cx.notifications {
421 commands.push(Command::notify_shell(op).build());
422 }
423 for (op, then) in cx.requests {
424 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
425 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
426 }));
427 }
428 for (op, then) in cx.streams {
429 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
432 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
433 }));
434 }
435 Command::all(commands)
436 }
437
438 fn view(&self, model: &Self::Model) -> Widget {
439 A::default().view(model)
440 }
441}
442
443#[derive(Clone, Debug)]
462pub struct Nav<R> {
463 stack: Vec<R>,
464}
465
466impl<R: Clone + Serialize> Nav<R> {
467 #[must_use]
469 pub fn new(root: R) -> Self {
470 Self { stack: vec![root] }
471 }
472 pub fn push(&mut self, route: R) {
474 self.stack.push(route);
475 }
476 pub fn pop(&mut self) {
478 if self.stack.len() > 1 {
479 self.stack.pop();
480 }
481 }
482 pub fn reset(&mut self, root: R) {
484 self.stack = vec![root];
485 }
486 #[must_use]
488 pub fn current(&self) -> &R {
489 self.stack.last().expect("nav stack is never empty")
490 }
491 #[must_use]
493 pub fn depth(&self) -> u32 {
494 self.stack.len() as u32
495 }
496 #[must_use]
498 pub fn can_go_back(&self) -> bool {
499 self.stack.len() > 1
500 }
501 fn route_key(&self) -> String {
504 serde_json::to_string(self.current()).expect("serialize route")
505 }
506}
507
508fn tok<E: Serialize>(event: E) -> String {
512 serde_json::to_string(&event).expect("serialize event")
513}
514
515#[must_use]
516pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
517 Widget::Text { content: content.into(), style }
518}
519#[must_use]
520pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
521#[must_use]
522pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
523#[must_use]
524pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
525#[must_use]
526pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
527#[must_use]
528pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
529
530#[must_use]
531pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
532 Widget::Image { source: source.into(), shape, ratio }
533}
534#[must_use]
535pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
536 Widget::Badge { label: label.into(), tone }
537}
538#[must_use]
540pub fn color_dot(color: ProjectColor) -> Widget {
541 Widget::ColorDot { color }
542}
543#[must_use]
544pub fn divider() -> Widget { Widget::Divider }
545#[must_use]
547pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
548#[must_use]
550pub fn skeleton() -> Widget { Widget::Skeleton }
551#[must_use]
555pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
556#[must_use]
565pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
566 Widget::Video {
567 url: url.into(),
568 id: id.into(),
569 playing,
570 seek_to_ms,
571 controls: true,
572 looping: false,
573 muted: false,
574 on_ended: Some(tok(on_ended)),
575 poster: None,
576 start_at_ms: -1,
577 captions: Vec::new(),
578 rate: 1.0,
579 volume: 1.0,
580 urls: Vec::new(),
581 start_index: 0,
582 seek_index: -1,
583 allow_pip: false,
584 }
585}
586#[must_use]
592pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
593 Widget::Video {
594 url: urls.first().cloned().unwrap_or_default(),
595 id: id.into(),
596 playing,
597 seek_to_ms: -1,
598 controls: true,
599 looping: false,
600 muted: false,
601 on_ended: Some(tok(on_ended)),
602 poster: None,
603 start_at_ms: -1,
604 captions: Vec::new(),
605 rate: 1.0,
606 volume: 1.0,
607 urls,
608 start_index,
609 seek_index: -1,
610 allow_pip: false,
611 }
612}
613fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
616 match widget {
617 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
618 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
619 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
620 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
621 f(&mut v);
622 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
623 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
624 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
625 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
626 allow_pip: v.allow_pip }
627 }
628 other => other,
629 }
630}
631struct VideoFields {
632 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
633 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
634 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
635 seek_index: i64, allow_pip: bool,
636}
637#[must_use]
639pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
640#[must_use]
642pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
643#[must_use]
645pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
646#[must_use]
648pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
649 let poster = poster.into();
650 map_video(widget, move |v| v.poster = Some(poster))
651}
652#[must_use]
654pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
655 map_video(widget, move |v| v.start_at_ms = start_at_ms)
656}
657#[must_use]
659pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
660 map_video(widget, move |v| v.captions = captions)
661}
662#[must_use]
664pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
665#[must_use]
667pub fn with_volume(widget: Widget, volume: f32) -> Widget {
668 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
669}
670#[must_use]
672pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
673 map_video(widget, move |v| v.seek_index = index)
674}
675#[must_use]
677pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
678#[must_use]
683pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
684
685#[must_use]
691pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
692 Widget::Map {
693 id: id.into(),
694 center_lat,
695 center_lng,
696 zoom,
697 markers: Vec::new(),
698 style_url: None,
699 interactive: true,
700 }
701}
702#[must_use]
704pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
705 match widget {
706 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
707 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
708 other => other,
709 }
710}
711#[must_use]
713pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
714 match widget {
715 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
716 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
717 other => other,
718 }
719}
720#[must_use]
722pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
723 MapMarker { id: id.into(), lat, lng, title: None }
724}
725#[must_use]
727pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
728 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
729}
730fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
732 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
733}
734
735#[must_use]
738pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
739 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
740}
741#[must_use]
744pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
745 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
746}
747#[must_use]
751pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
752 Widget::Chart { series, labels, style, axis, legend }
753}
754#[must_use]
756pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
757 chart(series, labels, ChartStyle::StackedBar, true, true)
758}
759#[must_use]
761pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
762 chart(series, labels, ChartStyle::StackedBar100, false, true)
763}
764#[must_use]
766pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
767 chart(series, vec![], ChartStyle::Pie, false, true)
768}
769#[must_use]
771pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
772 chart(series, vec![], ChartStyle::Donut, false, true)
773}
774#[must_use]
777pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
778 chart(series, vec![], ChartStyle::Rings, false, true)
779}
780#[must_use]
782pub fn gauge_chart(series: ChartSeries) -> Widget {
783 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
784}
785
786#[must_use]
791pub fn region_chart(
792 regions: Vec<ChartRegion>,
793 ticks: Vec<ChartTick>,
794 x_max: f32,
795 y_max: f32,
796 ref_lines: Vec<ChartRefLine>,
797 legend: Vec<ChartLegendItem>,
798) -> Widget {
799 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
800}
801
802#[must_use]
804pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
805 match widget {
806 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
807 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
808 }
809 other => other,
810 }
811}
812
813fn days_in_month(year: u32, month: u8) -> u8 {
815 match month {
816 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
817 4 | 6 | 9 | 11 => 30,
818 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
819 _ => 30,
820 }
821}
822
823fn weekday(year: u32, month: u8, day: u8) -> u8 {
825 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
826 let y = if month < 3 { year - 1 } else { year };
827 let m = month as usize - 1;
828 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
829}
830
831#[must_use]
835pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
836 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
837}
838
839#[must_use]
844pub fn calendar_in<E: Serialize>(
845 locale: Locale,
846 year: u32,
847 month: u8,
848 selected: Option<u8>,
849 markers: &[u8],
850 on_day: impl Fn(u8) -> E,
851) -> Widget {
852 let n = days_in_month(year, month);
853 let start = locale.week_start().sun0();
854 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
855 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
856 let markers = if markers.is_empty() {
857 Vec::new()
858 } else {
859 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
860 };
861 Widget::Calendar {
862 year,
863 month,
864 title: format::month_year(year, u32::from(month), locale),
865 weekday_labels,
866 leading_blanks,
867 selected,
868 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
869 markers,
870 }
871}
872
873#[must_use]
876pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
877 Widget::SwipeAction {
878 child: Box::new(child),
879 actions: actions
880 .into_iter()
881 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
882 .collect(),
883 }
884}
885#[must_use]
886pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
887
888#[must_use]
889pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
890#[must_use]
891pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
892#[must_use]
893pub fn card(child: Widget, style: CardStyle) -> Widget {
894 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
895}
896#[must_use]
898pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
899 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
900}
901#[must_use]
904pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
905 match widget {
906 Widget::Card { child, style, on_press, .. } => Widget::Card {
907 child,
908 style,
909 on_press,
910 on_long_press: Some(tok(on_long_press)),
911 },
912 other => other,
913 }
914}
915#[must_use]
918pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
919 Widget::Box { children, align, scrim }
920}
921#[must_use]
922pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
923#[must_use]
928pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
929 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
930}
931#[must_use]
933pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
934#[must_use]
936pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
937#[must_use]
939pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
940#[must_use]
942pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
943 Widget::Avatar { source: source.into(), status: Some(status) }
944}
945#[must_use]
947pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
948#[must_use]
950pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
951 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
952}
953
954#[derive(Clone, Copy, Debug, PartialEq, Eq)]
962pub struct ButtonOpts {
963 pub tone: Tone,
964 pub icon: Option<Icon>,
965 pub wide: bool,
966}
967
968impl Default for ButtonOpts {
969 fn default() -> Self {
970 Self { tone: Tone::Neutral, icon: None, wide: false }
971 }
972}
973
974impl ButtonOpts {
975 #[must_use]
977 pub const fn tone(mut self, tone: Tone) -> Self {
978 self.tone = tone;
979 self
980 }
981 #[must_use]
983 pub const fn icon(mut self, icon: Icon) -> Self {
984 self.icon = Some(icon);
985 self
986 }
987 #[must_use]
989 pub const fn wide(mut self) -> Self {
990 self.wide = true;
991 self
992 }
993}
994
995#[must_use]
996pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
997 button_with(label, style, on_press, ButtonOpts::default())
998}
999
1000#[must_use]
1002pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1003 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1004}
1005#[must_use]
1006pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1007 Widget::IconButton { icon, on_press: tok(on_press) }
1008}
1009#[must_use]
1010pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1011 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1012}
1013#[must_use]
1014pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1015 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1016}
1017#[must_use]
1021pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1022 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1023}
1024#[must_use]
1026pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1027 field(id, placeholder, value, FieldKind::Secure, None)
1028}
1029#[must_use]
1031pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1032 field(id, placeholder, value, FieldKind::Email, None)
1033}
1034#[must_use]
1036pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1037 field(id, placeholder, value, FieldKind::Number, None)
1038}
1039#[must_use]
1041pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1042 field(id, placeholder, value, FieldKind::Decimal, None)
1043}
1044#[must_use]
1046pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1047 field(id, placeholder, value, FieldKind::Phone, None)
1048}
1049#[must_use]
1051pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1052 field(id, placeholder, value, FieldKind::Url, None)
1053}
1054#[must_use]
1056pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1057 field(id, placeholder, value, FieldKind::Multiline, None)
1058}
1059#[must_use]
1062pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1063 match widget {
1064 Widget::TextField { id, placeholder, value, kind, .. } =>
1065 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1066 other => other,
1067 }
1068}
1069
1070#[must_use]
1074pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1075 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1076}
1077#[must_use]
1080pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1081 match widget {
1082 Widget::A11y { child, label, role, .. } =>
1083 Widget::A11y { child, label, hint: Some(hint.into()), role },
1084 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1085 }
1086}
1087#[must_use]
1089pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1090 match widget {
1091 Widget::A11y { child, label, hint, .. } =>
1092 Widget::A11y { child, label, hint, role: Some(role) },
1093 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1094 }
1095}
1096#[must_use]
1098pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1099 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1100}
1101#[must_use]
1103pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1104 Segment { label: label.into(), selected, on_select: tok(on_select) }
1105}
1106#[must_use]
1108pub fn segmented(segments: Vec<Segment>) -> Widget {
1109 Widget::Segmented { segments }
1110}
1111#[must_use]
1112pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1113 Widget::Toggle { id: id.into(), label: label.into(), value }
1114}
1115#[must_use]
1116pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1117 Widget::Checkbox { id: id.into(), label: label.into(), value }
1118}
1119#[must_use]
1120pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1121 Widget::Slider { id: id.into(), value, max }
1122}
1123#[must_use]
1124pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1125 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1126}
1127
1128#[must_use]
1130pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1131 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1132}
1133
1134#[must_use]
1136pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1137 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1138}
1139
1140#[must_use]
1143pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1144 let title = title.into();
1145 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, labels: None }
1147}
1148
1149#[must_use]
1153pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1154 let title = title.into();
1155 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, labels: None }
1156}
1157
1158#[must_use]
1163pub fn nav_scaffold<R, E>(
1164 title: impl Into<String>,
1165 dark_mode: bool,
1166 tabs: Vec<Tab>,
1167 body: Widget,
1168 nav: &Nav<R>,
1169 on_back: E,
1170) -> Widget
1171where
1172 R: Clone + Serialize,
1173 E: Serialize,
1174{
1175 Widget::Scaffold {
1176 title: title.into(),
1177 body: Box::new(body),
1178 tabs,
1179 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1180 dark_mode,
1181 theme: None,
1182 fab: None,
1183 sheet: None,
1184 on_refresh: None,
1185 refreshing: false,
1186 route: nav.route_key(),
1187 depth: nav.depth(),
1188 labels: None,
1189 }
1190}
1191
1192pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1196 match widget {
1197 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, .. } => Widget::Scaffold {
1198 title,
1199 body,
1200 tabs,
1201 back,
1202 dark_mode,
1203 theme: Some(theme),
1204 fab,
1205 sheet,
1206 on_refresh,
1207 refreshing,
1208 route,
1209 depth,
1210 labels,
1211 },
1212 other => other,
1213 }
1214}
1215
1216pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1219 match widget {
1220 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, .. } => Widget::Scaffold {
1221 title,
1222 body,
1223 tabs,
1224 back,
1225 dark_mode,
1226 theme,
1227 fab: Some(Fab { icon, on_press: tok(on_press) }),
1228 sheet,
1229 on_refresh,
1230 refreshing,
1231 route,
1232 depth,
1233 labels,
1234 },
1235 other => other,
1236 }
1237}
1238
1239pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1242 match widget {
1243 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, .. } => Widget::Scaffold {
1244 title: t,
1245 body,
1246 tabs,
1247 back,
1248 dark_mode,
1249 theme,
1250 fab,
1251 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1252 on_refresh,
1253 refreshing,
1254 route,
1255 depth,
1256 labels,
1257 },
1258 other => other,
1259 }
1260}
1261
1262pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1266 match widget {
1267 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, .. } => Widget::Scaffold {
1268 title,
1269 body,
1270 tabs,
1271 back,
1272 dark_mode,
1273 theme,
1274 fab,
1275 sheet,
1276 on_refresh: Some(tok(on_refresh)),
1277 refreshing,
1278 route,
1279 depth,
1280 labels,
1281 },
1282 Widget::LazyList { children, on_load_more, loading, has_more, end_label, .. } => Widget::LazyList {
1285 children,
1286 on_load_more,
1287 loading,
1288 has_more,
1289 on_refresh: Some(tok(on_refresh)),
1290 refreshing,
1291 end_label,
1292 },
1293 other => other,
1294 }
1295}
1296
1297#[must_use]
1302pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1303 match widget {
1304 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, .. } => {
1305 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels) }
1306 }
1307 other => other,
1308 }
1309}
1310
1311#[must_use]
1317pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1318 Widget::LazyList {
1319 children,
1320 on_load_more: Some(tok(on_load_more)),
1321 loading,
1322 has_more,
1323 on_refresh: None,
1324 refreshing: false,
1325 end_label: None,
1326 }
1327}
1328
1329#[must_use]
1331pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1332 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None }
1333}
1334
1335#[must_use]
1339pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1340 match widget {
1341 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, .. } => {
1342 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()) }
1343 }
1344 other => other,
1345 }
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350 use super::*;
1351 use serde::Serialize;
1352
1353 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1354 enum Route {
1355 Home,
1356 Detail(u32),
1357 }
1358
1359 #[derive(Serialize)]
1360 enum Ev {
1361 Tap,
1362 Open(u32),
1363 }
1364
1365 #[test]
1368 fn plugin_response_carries_bytes_and_converts_text() {
1369 let r = PluginResponse::text(true, "hello");
1370 assert!(r.ok);
1371 assert_eq!(r.output, b"hello".to_vec());
1372 assert_eq!(r.as_text(), Some("hello"));
1373
1374 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1375 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1376 }
1377
1378 #[test]
1381 fn nav_push_pop_depth() {
1382 let mut nav = Nav::new(Route::Home);
1383 assert_eq!(nav.depth(), 1);
1384 assert!(!nav.can_go_back());
1385
1386 nav.push(Route::Detail(7));
1387 assert_eq!(nav.depth(), 2);
1388 assert!(nav.can_go_back());
1389 assert!(matches!(nav.current(), Route::Detail(7)));
1390
1391 nav.pop();
1392 assert_eq!(nav.depth(), 1);
1393 assert!(matches!(nav.current(), Route::Home));
1394
1395 nav.pop(); assert_eq!(nav.depth(), 1);
1397 }
1398
1399 #[test]
1400 fn nav_reset_replaces_stack() {
1401 let mut nav = Nav::new(Route::Home);
1402 nav.push(Route::Detail(1));
1403 nav.push(Route::Detail(2));
1404 nav.reset(Route::Detail(9));
1405 assert_eq!(nav.depth(), 1);
1406 assert!(matches!(nav.current(), Route::Detail(9)));
1407 }
1408
1409 #[test]
1410 fn nav_route_key_is_serialization() {
1411 let nav = Nav::new(Route::Detail(3));
1412 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1413 }
1414
1415 #[test]
1418 fn scaffold_sets_route_depth_and_no_back() {
1419 match scaffold("Home", false, vec![], text("x")) {
1420 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1421 assert_eq!(route, "Home");
1422 assert_eq!(depth, 1);
1423 assert!(back.is_none());
1424 assert!(!dark_mode);
1425 }
1426 other => panic!("expected Scaffold, got {other:?}"),
1427 }
1428 }
1429
1430 #[test]
1431 fn scaffold_back_is_depth_2_with_back() {
1432 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1433 Widget::Scaffold { depth, back, dark_mode, .. } => {
1434 assert_eq!(depth, 2);
1435 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1436 assert!(dark_mode);
1437 }
1438 other => panic!("expected Scaffold, got {other:?}"),
1439 }
1440 }
1441
1442 #[test]
1443 fn nav_scaffold_shows_back_only_when_poppable() {
1444 let mut nav = Nav::new(Route::Home);
1445 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1447 Widget::Scaffold { back, depth, route, .. } => {
1448 assert!(back.is_none());
1449 assert_eq!(depth, 1);
1450 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1451 }
1452 other => panic!("expected Scaffold, got {other:?}"),
1453 }
1454 nav.push(Route::Detail(2));
1456 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1457 Widget::Scaffold { back, depth, .. } => {
1458 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1459 assert_eq!(depth, 2);
1460 }
1461 other => panic!("expected Scaffold, got {other:?}"),
1462 }
1463 }
1464
1465 #[test]
1466 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1467 let l = ShellLabels::new().back("Nazad").ok("U redu");
1468 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1469 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1470 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1471 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1473 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1474 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1475 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1476 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1477 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1478 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1479 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1480 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1482 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1484 let nav = Nav::new(Route::Home);
1486 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1487 }
1488
1489 #[test]
1490 fn button_with_carries_tone_icon_and_width() {
1491 assert!(matches!(
1492 button("Go", ButtonStyle::Filled, Ev::Tap),
1493 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1494 ));
1495 assert!(matches!(
1496 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1497 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1498 ));
1499 }
1500
1501 #[test]
1502 fn buttons_carry_serialized_event_tokens() {
1503 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1504 Widget::Button { label, on_press, .. } => {
1505 assert_eq!(label, "Go");
1506 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1507 }
1508 other => panic!("expected Button, got {other:?}"),
1509 }
1510 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1511 Widget::Card { on_press, .. } => {
1512 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1513 }
1514 other => panic!("expected Card, got {other:?}"),
1515 }
1516 match card(text("c"), CardStyle::Elevated) {
1518 Widget::Card { on_press, on_long_press, .. } => {
1519 assert!(on_press.is_none());
1520 assert!(on_long_press.is_none());
1521 }
1522 other => panic!("expected Card, got {other:?}"),
1523 }
1524 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1526 Widget::Card { on_press, on_long_press, .. } => {
1527 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1528 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1529 }
1530 other => panic!("expected Card, got {other:?}"),
1531 }
1532 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1534 }
1535
1536 #[test]
1539 fn cx_notify_and_save_enqueue_notifications() {
1540 let mut cx = Cx::<Ev>::default();
1541 cx.notify("toast", "show", "hi");
1542 cx.save("blob");
1543 assert_eq!(cx.notifications.len(), 2);
1544 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1545 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1546 assert!(cx.requests.is_empty());
1547 }
1548
1549 #[test]
1550 fn cx_http_helpers_build_requests() {
1551 let mut cx = Cx::<Ev>::default();
1552 cx.get("http://h/x", |_| Ev::Tap);
1553 cx.post("http://h/y", "hello", |_| Ev::Tap);
1554 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1555 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1556 cx.delete("http://h/d", |_| Ev::Tap);
1557
1558 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1559 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1560 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1561
1562 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1563 assert_eq!(get_input["url"], "http://h/x");
1564 assert!(get_input["body"].is_null());
1565
1566 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1567 assert_eq!(put_input["url"], "http://h/p");
1568 assert_eq!(put_input["body"], "putbody");
1569 }
1570
1571 #[test]
1572 fn request_builder_emits_headers_in_order() {
1573 let mut cx = Cx::<Ev>::default();
1574 cx.request("PUT", "http://h/access-key")
1575 .bearer("tok123")
1576 .header("X-Trace-Id", "abc")
1577 .body("{}")
1578 .send(|_| Ev::Tap);
1579
1580 assert_eq!(cx.requests.len(), 1);
1581 let (call, _) = &cx.requests[0];
1582 assert_eq!(call.plugin, "http");
1583 assert_eq!(call.op, "PUT");
1584
1585 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1586 assert_eq!(input["url"], "http://h/access-key");
1587 assert_eq!(input["body"], "{}");
1588 assert_eq!(input["headers"][0]["name"], "Authorization");
1589 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1590 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1591 assert_eq!(input["headers"][1]["value"], "abc");
1592 }
1593
1594 #[test]
1595 fn helpers_emit_no_headers_field_content() {
1596 let mut cx = Cx::<Ev>::default();
1597 cx.get("http://h/x", |_| Ev::Tap);
1598 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1599 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1600 }
1601
1602 #[test]
1603 fn continuation_receives_decoded_outcome() {
1604 #[derive(Debug, PartialEq)]
1605 enum Got { Conflict, Offline, Other }
1606
1607 let classify = |r: PluginResponse| -> Got {
1608 match HttpOutcome::decode(&r.output).unwrap() {
1609 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1610 HttpOutcome::TransportError { .. } => Got::Offline,
1611 _ => Got::Other,
1612 }
1613 };
1614
1615 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1616 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1617
1618 let offline = HttpOutcome::TransportError { message: "refused".into() };
1619 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1620 }
1621
1622 #[test]
1623 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1624 let mut cx = Cx::<Ev>::default();
1629
1630 cx.request("GET", "http://h/x").send(|outcome| {
1631 match outcome {
1632 HttpOutcome::TransportError { message } => {
1633 assert!(
1634 message.contains("malformed http response"),
1635 "unexpected message: {message}"
1636 );
1637 }
1638 HttpOutcome::Response { .. } => {
1639 panic!("garbage bytes must not decode as a Response")
1640 }
1641 }
1642 Ev::Tap
1643 });
1644
1645 assert_eq!(cx.requests.len(), 1);
1646 let (_, continuation) = cx.requests.remove(0);
1647 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1650 }
1651
1652 #[test]
1653 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1654 let mut cx = Cx::<Ev>::default();
1655 cx.pick_photo(|_| Ev::Tap);
1656 cx.capture_photo(|_| Ev::Tap);
1657 assert_eq!(cx.requests.len(), 2);
1658 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", ""));
1661 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", ""));
1662 }
1663
1664 #[test]
1665 fn cx_capture_photo_routes_success_and_cancel() {
1666 let mut cx = Cx::<Ev>::default();
1668 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1669 let (_, then) = cx.requests.pop().unwrap();
1670 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1671
1672 let mut cx = Cx::<Ev>::default();
1674 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1675 let (_, then) = cx.requests.pop().unwrap();
1676 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1677 }
1678
1679 #[test]
1680 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1681 let mut cx = Cx::<Ev>::default();
1682 cx.copy("c");
1683 cx.share("s");
1684 cx.open_url("u");
1685 cx.toast("t");
1686 cx.haptic("heavy");
1687 let got: Vec<(&str, &str, &str)> = cx
1688 .notifications
1689 .iter()
1690 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1691 .collect();
1692 assert_eq!(
1693 got,
1694 vec![
1695 ("clipboard", "copy", "c"),
1696 ("share", "text", "s"),
1697 ("browser", "open", "u"),
1698 ("toast", "show", "t"),
1699 ("haptics", "heavy", ""), ]
1701 );
1702 assert!(cx.requests.is_empty());
1703 }
1704
1705 #[test]
1706 fn cx_device_model_is_a_request_not_a_notification() {
1707 let mut cx = Cx::<Ev>::default();
1708 cx.device_model(|_| Ev::Tap);
1709 assert!(cx.notifications.is_empty());
1710 assert_eq!(cx.requests.len(), 1);
1711 let (call, _) = &cx.requests[0];
1712 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1713 }
1714
1715 #[test]
1716 fn cx_device_locale_requests_the_device_locale_op() {
1717 let mut cx = Cx::<Ev>::default();
1718 cx.device_locale(|_| Ev::Tap);
1719 assert!(cx.notifications.is_empty());
1720 assert_eq!(cx.requests.len(), 1);
1721 let (call, _) = &cx.requests[0];
1722 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1723 }
1724
1725 #[test]
1726 fn cx_now_requests_the_datetime_now_op() {
1727 let mut cx = Cx::<Ev>::default();
1728 cx.now(|_| Ev::Tap);
1729 assert_eq!(cx.requests.len(), 1);
1730 let (call, _) = &cx.requests[0];
1731 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1732 }
1733
1734 #[test]
1735 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1736 let mut cx = Cx::<Ev>::default();
1737 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1738 assert!(cx.notifications.is_empty());
1740 assert!(cx.requests.is_empty());
1741 assert_eq!(cx.streams.len(), 1);
1742 let (call, on_event) = &cx.streams[0];
1743 assert_eq!(
1744 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1745 ("ws", "websocket", "stream", "wss://h/x")
1746 );
1747 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1749 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1750 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1751 }
1752
1753 #[test]
1754 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1755 let mut cx = Cx::<Ev>::default();
1756 cx.unsubscribe("ws");
1757 assert!(cx.streams.is_empty());
1758 assert_eq!(cx.notifications.len(), 1);
1759 assert_eq!(
1761 cx.notifications[0],
1762 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1763 );
1764 }
1765
1766 #[test]
1767 fn cx_confirm_serializes_title_message_and_routes_ok() {
1768 let mut cx = Cx::<Ev>::default();
1769 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1770 let (call, then) = cx.requests.pop().unwrap();
1771 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1772 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1773 assert_eq!(v["title"], "Delete?");
1774 assert_eq!(v["message"], "This cannot be undone.");
1775 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1777 }
1778
1779 #[test]
1780 fn cx_confirm_stays_byte_identical_on_the_wire() {
1781 let mut cx = Cx::<Ev>::default();
1782 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
1783 let (call, _) = cx.requests.pop().unwrap();
1784 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
1785 }
1786
1787 #[test]
1788 fn cx_confirm_with_sends_labels_and_destructive() {
1789 let mut cx = Cx::<Ev>::default();
1790 cx.confirm_with(
1791 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
1792 .confirm_label("Otkaži termin")
1793 .cancel_label("Ne, vrati se")
1794 .destructive(),
1795 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
1796 );
1797 let (call, then) = cx.requests.pop().unwrap();
1798 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1799 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1800 assert_eq!(v["title"], "Otkazati termin?");
1801 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
1802 assert_eq!(v["confirm_label"], "Otkaži termin");
1803 assert_eq!(v["cancel_label"], "Ne, vrati se");
1804 assert_eq!(v["destructive"], true);
1805 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
1806 let mut cx = Cx::<Ev>::default();
1808 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
1809 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
1810 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
1811 }
1812
1813 #[test]
1814 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
1815 let mut cx = Cx::<Ev>::default();
1816 cx.pick_date(|_| Ev::Tap);
1817 cx.pick_time(|_| Ev::Tap);
1818 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
1819
1820 let mut cx = Cx::<Ev>::default();
1821 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
1822 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
1823 let (date, _) = &cx.requests[0];
1824 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
1825 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
1826 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
1827 let (time, _) = &cx.requests[1];
1828 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
1829 }
1830
1831 #[test]
1834 fn text_builders_carry_their_style() {
1835 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1836 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1837 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1838 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1839 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1840 }
1841
1842 #[test]
1843 fn layout_and_content_builders_produce_their_variants() {
1844 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1845 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1846 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1847 assert!(matches!(divider(), Widget::Divider));
1848 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1849 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1850 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1851 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)));
1852 let rc = with_bracket(
1853 region_chart(
1854 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1855 vec![ChartTick::new(3.0, "3 Mt.")],
1856 65.0, 80.0,
1857 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1858 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1859 ),
1860 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1861 );
1862 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1863 assert!(matches!(
1865 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1866 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
1867 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
1868 ));
1869 assert!(matches!(
1870 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1871 Widget::SwipeAction { actions, .. } if actions.len() == 1
1872 ));
1873 assert!(matches!(
1875 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1876 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None }
1877 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1878 ));
1879 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1880 assert!(matches!(
1882 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1883 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1884 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1885 ));
1886 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
1888 assert!(matches!(
1889 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
1890 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
1891 ));
1892 assert!(matches!(
1894 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
1895 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
1896 ));
1897 assert!(matches!(
1898 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
1899 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
1900 ));
1901 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
1903 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1904 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1905 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1906 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1907 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1908 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1910 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1912 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1913 }
1914
1915 #[test]
1916 fn input_builders_carry_ids_values_and_event_tokens() {
1917 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1918 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1919 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1920 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1922 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1923 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1924 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1925 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1927 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1928 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1929 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1930 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1931 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1932 "p.jpg"), 9000), 1.5), 0.5));
1933 assert!(matches!(tuned,
1934 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1935 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1936 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1938 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1939 assert!(matches!(with_pip(divider()), Widget::Divider));
1941 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1942 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1943 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1944 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1945 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1946 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1947 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1948 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1949
1950 match chip("Latte", true, Ev::Open(2)) {
1951 Widget::Chip { selected, on_press, .. } => {
1952 assert!(selected);
1953 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1954 }
1955 other => panic!("expected Chip, got {other:?}"),
1956 }
1957 match stepper(5, Ev::Tap, Ev::Open(1)) {
1958 Widget::Stepper { value, on_decrement, on_increment } => {
1959 assert_eq!(value, 5);
1960 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1961 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1962 }
1963 other => panic!("expected Stepper, got {other:?}"),
1964 }
1965 let t = tab("Home", true, Ev::Tap);
1966 assert_eq!(t.label, "Home");
1967 assert!(t.selected);
1968 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1969 }
1970
1971 #[test]
1974 fn widget_tree_round_trips_through_serde() {
1975 let tree = scaffold(
1976 "Home",
1977 true,
1978 vec![tab("A", true, Ev::Tap)],
1979 column(vec![
1980 title("Hi"),
1981 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1982 image("u", ImageShape::Rounded, ImageRatio::Wide),
1983 slider("s", 2, 5),
1984 ]),
1985 );
1986 let s = serde_json::to_string(&tree).unwrap();
1987 let back: Widget = serde_json::from_str(&s).unwrap();
1988 assert_eq!(s, serde_json::to_string(&back).unwrap());
1989 }
1990
1991 #[test]
1992 fn actions_and_input_values_round_trip() {
1993 let actions = vec![
1994 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1995 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1996 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1997 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1998 Action::Restore { data: "blob".into() },
1999 Action::Start,
2000 ];
2001 for a in actions {
2002 let s = serde_json::to_string(&a).unwrap();
2003 let back: Action = serde_json::from_str(&s).unwrap();
2004 assert_eq!(s, serde_json::to_string(&back).unwrap());
2005 }
2006 }
2007
2008 #[derive(Default)]
2011 struct CounterModel {
2012 count: i32,
2013 restored: String,
2014 started: bool,
2015 last_input: String,
2016 }
2017
2018 #[derive(serde::Serialize, serde::Deserialize)]
2019 enum CounterEv {
2020 Inc,
2021 Add(i32),
2022 }
2023
2024 #[derive(Default)]
2025 struct CounterApp;
2026
2027 impl MobilerApp for CounterApp {
2028 type Event = CounterEv;
2029 type Model = CounterModel;
2030 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2031 match ev {
2032 CounterEv::Inc => model.count += 1,
2033 CounterEv::Add(n) => model.count += n,
2034 }
2035 }
2036 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2037 if let InputValue::Text(t) = value {
2038 model.last_input = format!("{id}={t}");
2039 }
2040 }
2041 fn restore(&self, data: &str, model: &mut CounterModel) {
2042 model.restored = data.to_string();
2043 }
2044 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2045 model.started = true;
2046 }
2047 fn view(&self, model: &CounterModel) -> Widget {
2048 text(format!("{}", model.count))
2049 }
2050 }
2051
2052 #[test]
2053 fn shell_dispatches_fired_input_restore_and_start() {
2054 use crux_core::App as _;
2055 let shell = MobilerShell::<CounterApp>::default();
2056 let mut m = CounterModel::default();
2057
2058 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2060 assert_eq!(m.count, 5);
2061 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2063 assert_eq!(m.last_input, "name=bob");
2064 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2066 assert_eq!(m.restored, "saved");
2067 let _ = shell.update(Action::Start, &mut m);
2069 assert!(m.started);
2070 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2072 }
2073
2074 #[test]
2075 fn shell_ignores_a_malformed_fired_token() {
2076 use crux_core::App as _;
2077 let shell = MobilerShell::<CounterApp>::default();
2078 let mut m = CounterModel::default();
2079 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2082 assert_eq!(m.count, 0);
2083 }
2084
2085 #[derive(Default)]
2088 struct EffectsApp;
2089
2090 impl MobilerApp for EffectsApp {
2091 type Event = CounterEv;
2092 type Model = CounterModel;
2093 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2094 model.count += 1;
2095 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2096 cx.notify("toast", "show", "hi");
2097 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2098 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2099 }
2100 fn view(&self, model: &CounterModel) -> Widget {
2101 text(format!("{}", model.count))
2102 }
2103 }
2104
2105 #[test]
2106 fn shell_renders_before_requests_notifications_and_streams() {
2107 use crux_core::App as _;
2108 let shell = MobilerShell::<EffectsApp>::default();
2109 let mut m = CounterModel::default();
2110 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2111 let kinds: Vec<String> = cmd
2112 .effects()
2113 .map(|e| match e {
2114 Effect::Render(_) => "render".to_string(),
2115 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2116 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2117 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2118 })
2119 .collect();
2120 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2123 }
2124
2125 #[test]
2128 fn upload_builder_emits_transfer_stream_call() {
2129 let mut cx = Cx::<Ev>::default();
2130 let key = cx
2131 .upload("https://h/put", "file:///tmp/a.enc")
2132 .bearer("tok")
2133 .header("Content-Type", "application/octet-stream")
2134 .start("up-1", |_ev| Ev::Tap);
2135
2136 assert_eq!(key, "up-1");
2137 assert_eq!(cx.streams.len(), 1);
2138 let (call, _) = &cx.streams[0];
2139 assert_eq!(call.key, "up-1");
2140 assert_eq!(call.plugin, "transfer");
2141 assert_eq!(call.op, "upload");
2142
2143 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2144 assert_eq!(v["url"], "https://h/put");
2145 assert_eq!(v["source"], "file:///tmp/a.enc");
2146 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2148 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2149 assert_eq!(v["headers"][1]["name"], "Content-Type");
2150 }
2151
2152 #[test]
2153 fn download_builder_uses_dest_and_no_default_method() {
2154 let mut cx = Cx::<Ev>::default();
2155 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2156 let (call, _) = &cx.streams[0];
2157 assert_eq!(call.op, "download");
2158 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2159 assert_eq!(v["dest"], "/data/att-9.enc");
2160 assert!(v.get("source").is_none());
2161 }
2162
2163 #[test]
2164 fn start_continuation_decodes_progress_and_done() {
2165 use crate::http::HttpOutcome;
2166
2167 #[derive(Debug, PartialEq)]
2170 enum Got {
2171 Prog(u64),
2172 Done(u16),
2173 Bad,
2174 }
2175 #[derive(Debug, PartialEq)]
2176 struct GotEv(Got);
2177
2178 let mut cx = Cx::<GotEv>::default();
2179 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2180 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2181 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2182 Some(s) => Got::Done(s),
2183 None => Got::Bad,
2184 }),
2185 });
2186 let (_, cont) = &cx.streams[0];
2187
2188 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2189 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2190
2191 let done = TransferEvent::Done {
2192 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2193 handle: Some("/d".into()),
2194 };
2195 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2196 }
2197
2198 #[test]
2199 fn calendar_in_localizes_layout_and_clamps_markers() {
2200 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2202 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2203 assert_eq!(title, "Septembar 2026");
2204 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2205 assert_eq!(leading_blanks, 1);
2206 assert_eq!(on_day.len(), 30);
2207 assert_eq!(markers.len(), 30, "padded to one level per day");
2208 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2209 assert!(matches!(
2211 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2212 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2213 ));
2214 }
2215
2216 #[test]
2217 fn scroller_hint_is_opt_in() {
2218 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2219 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2220 }
2221}