1use std::marker::PhantomData;
9
10pub mod app_info;
11pub mod bunny;
12pub mod device;
13pub mod photo;
14pub mod dialog;
15pub mod format;
16pub mod http;
17pub mod i18n;
18pub mod transfer;
19pub use app_info::AppInfo;
20pub use device::DeviceInfo;
21pub use photo::{Photo, PhotoError, PhotoFormat, PhotoOptions};
22pub use dialog::{Confirm, Picker, Snackbar, SnackbarDuration};
23pub use format::{Currency, Locale, Weekday};
24pub use http::{HttpHeader, HttpOutcome};
25pub use i18n::{Catalog, negotiate};
26pub use transfer::TransferEvent;
27
28use crux_core::{
29 App, Command,
30 capability::Operation,
31 macros::effect,
32 render::{RenderOperation, render},
33};
34use facet::Facet;
35use serde::{Deserialize, Serialize, de::DeserializeOwned};
36
37pub use mobiler_ui::{
38 A11yRole, Action, Appearance, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
39 ChartSeries, ChartStyle, ChartTick, ColorRoles, Corner, FamilyRole, Density, Fab, FieldKind, FontFamily, Icon,
40 ImageRatio, ImageShape, InputValue, MapMarker, Palette, ProjectColor, Radius, Rgb, Rgba, Segment, Shapes, Sheet, ShellLabels, Spacing, SwipeButton, Tab, TabBadge,
41 TextStyle, Theme, Tone, TonePair, TypeScale, TypeSpec, Widget,
42};
43
44#[effect(facet_typegen)]
48#[derive(Debug)]
49pub enum Effect {
50 Render(RenderOperation),
51 PluginNotify(PluginNotify),
53 Plugin(PluginCall),
55 PluginStream(PluginStreamCall),
60}
61
62#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
63pub struct PluginNotify {
64 pub plugin: String,
65 pub op: String,
66 pub input: String,
67}
68impl Operation for PluginNotify {
69 type Output = ();
70}
71
72#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
73pub struct PluginCall {
74 pub plugin: String,
75 pub op: String,
76 pub input: String,
77}
78impl Operation for PluginCall {
79 type Output = PluginResponse;
80}
81
82#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
86pub struct PluginStreamCall {
87 pub key: String,
88 pub plugin: String,
89 pub op: String,
90 pub input: String,
91}
92impl Operation for PluginStreamCall {
93 type Output = PluginResponse;
94}
95
96#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
105pub struct PluginResponse {
106 pub ok: bool,
107 pub output: Vec<u8>,
108}
109
110impl PluginResponse {
111 pub fn text(ok: bool, s: impl Into<String>) -> Self {
113 Self { ok, output: s.into().into_bytes() }
114 }
115
116 pub fn as_text(&self) -> Option<&str> {
118 std::str::from_utf8(&self.output).ok()
119 }
120}
121
122type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
123type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
125
126pub struct Cx<E> {
129 notifications: Vec<PluginNotify>,
130 requests: Vec<(PluginCall, Continuation<E>)>,
131 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
132 app_info: AppInfo,
133}
134
135impl<E> Default for Cx<E> {
136 fn default() -> Self {
137 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new(), app_info: AppInfo::default() }
138 }
139}
140
141impl<E> Cx<E> {
142 #[must_use]
144 pub fn with_app_info(info: AppInfo) -> Self {
145 Self { app_info: info, ..Self::default() }
146 }
147
148 #[must_use]
153 pub fn app_info(&self) -> &AppInfo {
154 &self.app_info
155 }
156
157 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
159 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
160 }
161
162 pub fn plugin(
165 &mut self,
166 plugin: impl Into<String>,
167 op: impl Into<String>,
168 input: impl Into<String>,
169 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
170 ) {
171 self.requests
172 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
173 }
174
175 pub fn subscribe(
183 &mut self,
184 key: impl Into<String>,
185 plugin: impl Into<String>,
186 op: impl Into<String>,
187 input: impl Into<String>,
188 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
189 ) {
190 self.streams.push((
191 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
192 Box::new(on_event),
193 ));
194 }
195
196 pub fn unsubscribe(&mut self, key: impl Into<String>) {
200 self.notify("stream", "unsubscribe", key);
201 }
202
203 pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
208 crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
209 }
210
211 pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
214 crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
215 }
216
217 pub fn save(&mut self, data: impl Into<String>) {
223 self.notify("storage", "save", data);
224 }
225
226 pub fn copy(&mut self, text: impl Into<String>) {
228 self.notify("clipboard", "copy", text);
229 }
230
231 pub fn share(&mut self, text: impl Into<String>) {
233 self.notify("share", "text", text);
234 }
235
236 pub fn open_url(&mut self, url: impl Into<String>) {
239 self.notify("browser", "open", url);
240 }
241
242 pub fn open_url_then(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
249 self.plugin("browser", "open", url, then);
250 }
251
252 pub fn toast(&mut self, text: impl Into<String>) {
254 self.notify("toast", "show", text);
255 }
256
257 pub fn haptic(&mut self, style: impl Into<String>) {
260 self.notify("haptics", style, "");
261 }
262
263 pub fn request(
278 &mut self,
279 method: impl Into<String>,
280 url: impl Into<String>,
281 ) -> crate::http::RequestBuilder<'_, E> {
282 crate::http::RequestBuilder::new(self, method.into(), url.into())
283 }
284
285 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
287 self.request("GET", url).send(then);
288 }
289 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
291 self.request("POST", url).body(body).send(then);
292 }
293 pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
295 self.request("PUT", url).body(body).send(then);
296 }
297 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
299 self.request("PATCH", url).body(body).send(then);
300 }
301 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
303 self.request("DELETE", url).send(then);
304 }
305
306 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
310 self.plugin("device", "model", "", then);
311 }
312
313 pub fn device_info(&mut self, then: impl FnOnce(Option<DeviceInfo>) -> E + Send + 'static) {
317 self.plugin("device", "info", "", move |r| then(device::from_response(&r)));
318 }
319
320 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
325 self.plugin("device", "locale", "", then);
326 }
327
328 pub fn system_appearance(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
331 self.plugin("device", "appearance", "", then);
332 }
333
334 pub fn subscribe_appearance(&mut self, key: impl Into<String>, on_event: impl Fn(PluginResponse) -> E + Send + 'static) {
337 self.subscribe(key, "appearance", "changes", "", on_event);
338 }
339
340 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
345 self.plugin("photo", "pick", "", then);
346 }
347
348 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
355 self.plugin("camera", "capture", "", then);
356 }
357
358 pub fn pick_photo_with(&mut self, options: PhotoOptions, then: impl FnOnce(Result<Photo, PhotoError>) -> E + Send + 'static) {
364 self.plugin("photo", "pick", options.to_input(), move |r| then(photo::from_response(&r)));
365 }
366
367 pub fn capture_photo_with(&mut self, options: PhotoOptions, then: impl FnOnce(Result<Photo, PhotoError>) -> E + Send + 'static) {
370 self.plugin("camera", "capture", options.to_input(), move |r| then(photo::from_response(&r)));
371 }
372
373 pub fn confirm(
377 &mut self,
378 title: impl Into<String>,
379 message: impl Into<String>,
380 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
381 ) {
382 self.confirm_with(Confirm::new(title, message), then);
383 }
384
385 pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
389 self.plugin("dialog", "confirm", dialog.to_input(), then);
390 }
391
392 pub fn snackbar(&mut self, snackbar: Snackbar, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
398 self.plugin("snackbar", "show", snackbar.to_input(), then);
399 }
400
401 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
406 self.plugin("datetime", "date", "", then);
407 }
408
409 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
414 self.plugin("datetime", "time", "", then);
415 }
416
417 pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
419 self.plugin("datetime", "date", picker.to_input(), then);
420 }
421
422 pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
424 self.plugin("datetime", "time", picker.to_input(), then);
425 }
426
427 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
434 self.plugin("datetime", "now", "", then);
435 }
436}
437
438pub trait MobilerApp: Default {
443 type Event: Serialize + DeserializeOwned + Send + 'static;
444 type Model: Default;
445
446 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
447
448 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
449 let _ = (id, value, model, cx);
450 }
451
452 fn restore(&self, data: &str, model: &mut Self::Model) {
455 let _ = (data, model);
456 }
457
458 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
461 let _ = (model, cx);
462 }
463
464 fn view(&self, model: &Self::Model) -> Widget;
465}
466
467pub struct MobilerShell<A>(PhantomData<fn() -> A>);
469
470impl<A> Default for MobilerShell<A> {
471 fn default() -> Self {
472 Self(PhantomData)
473 }
474}
475
476impl<A: MobilerApp> App for MobilerShell<A> {
477 type Event = Action;
478 type Model = A::Model;
479 type ViewModel = Widget;
480 type Effect = Effect;
481
482 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
483 let app = A::default();
484 let mut cx = Cx::<A::Event>::with_app_info(app_info::get());
485 match action {
486 Action::Fired { token } => {
487 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
488 app.update(event, model, &mut cx);
489 }
490 }
491 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
492 Action::Restore { data } => app.restore(&data, model),
493 Action::Start => app.init(model, &mut cx),
494 Action::AppInfo { version, build, platform, bundle_id } => {
495 app_info::set(AppInfo { version, build, platform, bundle_id });
496 }
497 }
498 let mut commands: Vec<Command<Effect, Action>> = vec![render()];
504 for op in cx.notifications {
505 commands.push(Command::notify_shell(op).build());
506 }
507 for (op, then) in cx.requests {
508 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
509 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
510 }));
511 }
512 for (op, then) in cx.streams {
513 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
516 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
517 }));
518 }
519 Command::all(commands)
520 }
521
522 fn view(&self, model: &Self::Model) -> Widget {
523 A::default().view(model)
524 }
525}
526
527#[derive(Clone, Debug)]
546pub struct Nav<R> {
547 stack: Vec<R>,
548}
549
550impl<R: Clone + Serialize> Nav<R> {
551 #[must_use]
553 pub fn new(root: R) -> Self {
554 Self { stack: vec![root] }
555 }
556 pub fn push(&mut self, route: R) {
558 self.stack.push(route);
559 }
560 pub fn pop(&mut self) {
562 if self.stack.len() > 1 {
563 self.stack.pop();
564 }
565 }
566 pub fn reset(&mut self, root: R) {
568 self.stack = vec![root];
569 }
570 #[must_use]
572 pub fn current(&self) -> &R {
573 self.stack.last().expect("nav stack is never empty")
574 }
575 #[must_use]
577 pub fn depth(&self) -> u32 {
578 self.stack.len() as u32
579 }
580 #[must_use]
582 pub fn can_go_back(&self) -> bool {
583 self.stack.len() > 1
584 }
585 fn route_key(&self) -> String {
588 serde_json::to_string(self.current()).expect("serialize route")
589 }
590}
591
592fn tok<E: Serialize>(event: E) -> String {
596 serde_json::to_string(&event).expect("serialize event")
597}
598
599#[must_use]
600pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
601 Widget::Text { content: content.into(), style }
602}
603#[must_use]
604pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
605#[must_use]
606pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
607#[must_use]
608pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
609#[must_use]
610pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
611#[must_use]
612pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
613#[must_use]
616pub fn display(content: impl Into<String>) -> Widget { styled(content, TextStyle::Display) }
617#[must_use]
619pub fn headline(content: impl Into<String>) -> Widget { styled(content, TextStyle::Headline) }
620
621#[must_use]
622pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
623 Widget::Image { source: source.into(), shape, ratio }
624}
625#[must_use]
626pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
627 Widget::Badge { label: label.into(), tone, icon: None }
628}
629#[must_use]
631pub fn color_dot(color: ProjectColor) -> Widget {
632 Widget::ColorDot { color }
633}
634#[must_use]
635pub fn divider() -> Widget { Widget::Divider }
636#[must_use]
638pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
639#[must_use]
641pub fn skeleton() -> Widget { Widget::Skeleton }
642#[must_use]
646pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
647#[must_use]
656pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
657 Widget::Video {
658 url: url.into(),
659 id: id.into(),
660 playing,
661 seek_to_ms,
662 controls: true,
663 looping: false,
664 muted: false,
665 on_ended: Some(tok(on_ended)),
666 poster: None,
667 start_at_ms: -1,
668 captions: Vec::new(),
669 rate: 1.0,
670 volume: 1.0,
671 urls: Vec::new(),
672 start_index: 0,
673 seek_index: -1,
674 allow_pip: false,
675 }
676}
677#[must_use]
683pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
684 Widget::Video {
685 url: urls.first().cloned().unwrap_or_default(),
686 id: id.into(),
687 playing,
688 seek_to_ms: -1,
689 controls: true,
690 looping: false,
691 muted: false,
692 on_ended: Some(tok(on_ended)),
693 poster: None,
694 start_at_ms: -1,
695 captions: Vec::new(),
696 rate: 1.0,
697 volume: 1.0,
698 urls,
699 start_index,
700 seek_index: -1,
701 allow_pip: false,
702 }
703}
704fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
707 match widget {
708 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
709 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
710 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
711 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
712 f(&mut v);
713 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
714 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
715 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
716 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
717 allow_pip: v.allow_pip }
718 }
719 other => other,
720 }
721}
722struct VideoFields {
723 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
724 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
725 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
726 seek_index: i64, allow_pip: bool,
727}
728#[must_use]
730pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
731#[must_use]
733pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
734#[must_use]
736pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
737#[must_use]
739pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
740 let poster = poster.into();
741 map_video(widget, move |v| v.poster = Some(poster))
742}
743#[must_use]
745pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
746 map_video(widget, move |v| v.start_at_ms = start_at_ms)
747}
748#[must_use]
750pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
751 map_video(widget, move |v| v.captions = captions)
752}
753#[must_use]
755pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
756#[must_use]
758pub fn with_volume(widget: Widget, volume: f32) -> Widget {
759 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
760}
761#[must_use]
763pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
764 map_video(widget, move |v| v.seek_index = index)
765}
766#[must_use]
768pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
769#[must_use]
774pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
775
776#[must_use]
782pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
783 Widget::Map {
784 id: id.into(),
785 center_lat,
786 center_lng,
787 zoom,
788 markers: Vec::new(),
789 style_url: None,
790 interactive: true,
791 }
792}
793#[must_use]
795pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
796 match widget {
797 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
798 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
799 other => other,
800 }
801}
802#[must_use]
804pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
805 match widget {
806 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
807 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
808 other => other,
809 }
810}
811#[must_use]
813pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
814 MapMarker { id: id.into(), lat, lng, title: None }
815}
816#[must_use]
818pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
819 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
820}
821fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
823 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
824}
825
826#[must_use]
829pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
830 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
831}
832#[must_use]
835pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
836 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
837}
838#[must_use]
842pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
843 Widget::Chart { series, labels, style, axis, legend }
844}
845#[must_use]
847pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
848 chart(series, labels, ChartStyle::StackedBar, true, true)
849}
850#[must_use]
852pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
853 chart(series, labels, ChartStyle::StackedBar100, false, true)
854}
855#[must_use]
857pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
858 chart(series, vec![], ChartStyle::Pie, false, true)
859}
860#[must_use]
862pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
863 chart(series, vec![], ChartStyle::Donut, false, true)
864}
865#[must_use]
868pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
869 chart(series, vec![], ChartStyle::Rings, false, true)
870}
871#[must_use]
873pub fn gauge_chart(series: ChartSeries) -> Widget {
874 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
875}
876
877#[must_use]
882pub fn region_chart(
883 regions: Vec<ChartRegion>,
884 ticks: Vec<ChartTick>,
885 x_max: f32,
886 y_max: f32,
887 ref_lines: Vec<ChartRefLine>,
888 legend: Vec<ChartLegendItem>,
889) -> Widget {
890 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
891}
892
893#[must_use]
895pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
896 match widget {
897 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
898 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
899 }
900 other => other,
901 }
902}
903
904fn days_in_month(year: u32, month: u8) -> u8 {
906 match month {
907 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
908 4 | 6 | 9 | 11 => 30,
909 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
910 _ => 30,
911 }
912}
913
914fn weekday(year: u32, month: u8, day: u8) -> u8 {
916 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
917 let y = if month < 3 { year - 1 } else { year };
918 let m = month as usize - 1;
919 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
920}
921
922#[must_use]
926pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
927 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
928}
929
930#[must_use]
935pub fn calendar_in<E: Serialize>(
936 locale: Locale,
937 year: u32,
938 month: u8,
939 selected: Option<u8>,
940 markers: &[u8],
941 on_day: impl Fn(u8) -> E,
942) -> Widget {
943 let n = days_in_month(year, month);
944 let start = locale.week_start().sun0();
945 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
946 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
947 let markers = if markers.is_empty() {
948 Vec::new()
949 } else {
950 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
951 };
952 Widget::Calendar {
953 year,
954 month,
955 title: format::month_year(year, u32::from(month), locale),
956 weekday_labels,
957 leading_blanks,
958 selected,
959 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
960 markers,
961 }
962}
963
964#[must_use]
967pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
968 Widget::SwipeAction {
969 child: Box::new(child),
970 actions: actions
971 .into_iter()
972 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
973 .collect(),
974 }
975}
976#[must_use]
977pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
978
979#[must_use]
980pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
981#[must_use]
982pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
983#[must_use]
984pub fn card(child: Widget, style: CardStyle) -> Widget {
985 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
986}
987#[must_use]
989pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
990 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
991}
992#[must_use]
996pub fn with_icon(widget: Widget, icon: Icon) -> Widget {
997 match widget {
998 Widget::Badge { label, tone, .. } => Widget::Badge { label, tone, icon: Some(icon) },
999 other => other,
1000 }
1001}
1002
1003#[must_use]
1007pub fn with_initials(widget: Widget, initials: impl Into<String>) -> Widget {
1008 match widget {
1009 Widget::Avatar { source, status, size, .. } => Widget::Avatar { source, status, initials: Some(initials.into()), size },
1010 other => other,
1011 }
1012}
1013
1014#[must_use]
1017pub fn with_avatar_size(widget: Widget, size: u8) -> Widget {
1018 match widget {
1019 Widget::Avatar { source, status, initials, .. } => Widget::Avatar { source, status, initials, size: Some(size) },
1020 other => other,
1021 }
1022}
1023
1024#[must_use]
1027pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
1028 match widget {
1029 Widget::Card { child, style, on_press, .. } => Widget::Card {
1030 child,
1031 style,
1032 on_press,
1033 on_long_press: Some(tok(on_long_press)),
1034 },
1035 other => other,
1036 }
1037}
1038#[must_use]
1041pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
1042 Widget::Box { children, align, scrim }
1043}
1044#[must_use]
1049pub fn steps(total: u8, current: u8) -> Widget {
1050 Widget::Steps { total, current: current.min(total), caption: false }
1051}
1052
1053#[must_use]
1056pub fn with_step_caption(widget: Widget) -> Widget {
1057 match widget {
1058 Widget::Steps { total, current, .. } => Widget::Steps { total, current, caption: true },
1059 other => other,
1060 }
1061}
1062
1063#[must_use]
1066pub fn step_text(template: Option<&str>, current: u8, total: u8) -> String {
1067 let t = template.filter(|t| !t.is_empty()).unwrap_or("Step {current} of {total}");
1068 t.replace("{current}", ¤t.to_string()).replace("{total}", &total.to_string())
1069}
1070
1071#[must_use]
1072pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children, columns: None } }
1073#[must_use]
1076pub fn with_columns(widget: Widget, columns: u8) -> Widget {
1077 match widget {
1078 Widget::Grid { children, .. } => Widget::Grid { children, columns: Some(columns.clamp(1, 4)) },
1079 other => other,
1080 }
1081}
1082#[must_use]
1087pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
1088 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
1089}
1090#[must_use]
1092pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
1093#[must_use]
1095pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
1096#[must_use]
1098pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None, initials: None, size: None } }
1099#[must_use]
1101pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
1102 Widget::Avatar { source: source.into(), status: Some(status), initials: None, size: None }
1103}
1104#[must_use]
1106pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
1107#[must_use]
1109pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
1110 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
1111}
1112
1113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1121pub struct ButtonOpts {
1122 pub tone: Tone,
1123 pub icon: Option<Icon>,
1124 pub wide: bool,
1125}
1126
1127impl Default for ButtonOpts {
1128 fn default() -> Self {
1129 Self { tone: Tone::Neutral, icon: None, wide: false }
1130 }
1131}
1132
1133impl ButtonOpts {
1134 #[must_use]
1136 pub const fn tone(mut self, tone: Tone) -> Self {
1137 self.tone = tone;
1138 self
1139 }
1140 #[must_use]
1142 pub const fn icon(mut self, icon: Icon) -> Self {
1143 self.icon = Some(icon);
1144 self
1145 }
1146 #[must_use]
1148 pub const fn wide(mut self) -> Self {
1149 self.wide = true;
1150 self
1151 }
1152}
1153
1154#[must_use]
1155pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
1156 button_with(label, style, on_press, ButtonOpts::default())
1157}
1158
1159#[must_use]
1161pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1162 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1163}
1164#[must_use]
1165pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1166 Widget::IconButton { icon, on_press: tok(on_press) }
1167}
1168#[must_use]
1169pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1170 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1171}
1172#[must_use]
1173pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1174 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1175}
1176#[must_use]
1180pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1181 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1182}
1183#[must_use]
1185pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1186 field(id, placeholder, value, FieldKind::Secure, None)
1187}
1188#[must_use]
1190pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1191 field(id, placeholder, value, FieldKind::Email, None)
1192}
1193#[must_use]
1195pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1196 field(id, placeholder, value, FieldKind::Number, None)
1197}
1198#[must_use]
1200pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1201 field(id, placeholder, value, FieldKind::Decimal, None)
1202}
1203#[must_use]
1205pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1206 field(id, placeholder, value, FieldKind::Phone, None)
1207}
1208#[must_use]
1210pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1211 field(id, placeholder, value, FieldKind::Url, None)
1212}
1213#[must_use]
1215pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1216 field(id, placeholder, value, FieldKind::Multiline, None)
1217}
1218#[must_use]
1221pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1222 match widget {
1223 Widget::TextField { id, placeholder, value, kind, .. } =>
1224 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1225 other => other,
1226 }
1227}
1228
1229#[must_use]
1233pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1234 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1235}
1236#[must_use]
1239pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1240 match widget {
1241 Widget::A11y { child, label, role, .. } =>
1242 Widget::A11y { child, label, hint: Some(hint.into()), role },
1243 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1244 }
1245}
1246#[must_use]
1248pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1249 match widget {
1250 Widget::A11y { child, label, hint, .. } =>
1251 Widget::A11y { child, label, hint, role: Some(role) },
1252 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1253 }
1254}
1255#[must_use]
1257pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1258 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1259}
1260#[must_use]
1262pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1263 Segment { label: label.into(), selected, on_select: tok(on_select) }
1264}
1265#[must_use]
1267pub fn segmented(segments: Vec<Segment>) -> Widget {
1268 Widget::Segmented { segments }
1269}
1270#[must_use]
1271pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1272 Widget::Toggle { id: id.into(), label: label.into(), value }
1273}
1274#[must_use]
1275pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1276 Widget::Checkbox { id: id.into(), label: label.into(), value }
1277}
1278#[must_use]
1279pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1280 Widget::Slider { id: id.into(), value, max }
1281}
1282#[must_use]
1283pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1284 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1285}
1286
1287#[must_use]
1289pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1290 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None, badge: None }
1291}
1292
1293#[must_use]
1295pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1296 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon), badge: None }
1297}
1298
1299#[must_use]
1302pub fn with_tab_dot(mut tab: Tab, label: impl Into<String>) -> Tab {
1303 tab.badge = Some(TabBadge { text: String::new(), label: label.into() });
1304 tab
1305}
1306
1307#[must_use]
1310pub fn with_tab_count(mut tab: Tab, count: u32, label: impl Into<String>) -> Tab {
1311 tab.badge = match count {
1312 0 => None,
1313 1..=99 => Some(TabBadge { text: count.to_string(), label: label.into() }),
1314 _ => Some(TabBadge { text: "99+".into(), label: label.into() }),
1315 };
1316 tab
1317}
1318
1319#[must_use]
1322pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1323 let title = title.into();
1324 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, appearance: None, bottom_bar: None }
1326}
1327
1328#[must_use]
1332pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1333 let title = title.into();
1334 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, appearance: None, bottom_bar: None }
1335}
1336
1337#[must_use]
1342pub fn nav_scaffold<R, E>(
1343 title: impl Into<String>,
1344 dark_mode: bool,
1345 tabs: Vec<Tab>,
1346 body: Widget,
1347 nav: &Nav<R>,
1348 on_back: E,
1349) -> Widget
1350where
1351 R: Clone + Serialize,
1352 E: Serialize,
1353{
1354 Widget::Scaffold {
1355 title: title.into(),
1356 body: Box::new(body),
1357 tabs,
1358 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1359 dark_mode,
1360 theme: None,
1361 fab: None,
1362 sheet: None,
1363 on_refresh: None,
1364 refreshing: false,
1365 route: nav.route_key(),
1366 depth: nav.depth(),
1367 labels: None,
1368 appearance: None,
1369 bottom_bar: None,
1370 }
1371}
1372
1373pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1377 match widget {
1378 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1379 title,
1380 body,
1381 tabs,
1382 back,
1383 dark_mode,
1384 theme: Some(theme),
1385 fab,
1386 sheet,
1387 on_refresh,
1388 refreshing,
1389 route,
1390 depth,
1391 labels,
1392 appearance,
1393 bottom_bar,
1394 },
1395 other => other,
1396 }
1397}
1398
1399pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1402 set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1403}
1404
1405pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1409 set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1410}
1411
1412#[must_use]
1420pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1421 match widget {
1422 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, .. } => {
1423 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children) }
1424 }
1425 other => other,
1426 }
1427}
1428
1429fn set_fab(widget: Widget, fab: Fab) -> Widget {
1430 match widget {
1431 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1432 title,
1433 body,
1434 tabs,
1435 back,
1436 dark_mode,
1437 theme,
1438 fab: Some(fab),
1439 sheet,
1440 on_refresh,
1441 refreshing,
1442 route,
1443 depth,
1444 labels,
1445 appearance,
1446 bottom_bar,
1447 },
1448 other => other,
1449 }
1450}
1451
1452pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1455 match widget {
1456 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1457 title: t,
1458 body,
1459 tabs,
1460 back,
1461 dark_mode,
1462 theme,
1463 fab,
1464 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1465 on_refresh,
1466 refreshing,
1467 route,
1468 depth,
1469 labels,
1470 appearance,
1471 bottom_bar,
1472 },
1473 other => other,
1474 }
1475}
1476
1477pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1481 match widget {
1482 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1483 title,
1484 body,
1485 tabs,
1486 back,
1487 dark_mode,
1488 theme,
1489 fab,
1490 sheet,
1491 on_refresh: Some(tok(on_refresh)),
1492 refreshing,
1493 route,
1494 depth,
1495 labels,
1496 appearance,
1497 bottom_bar,
1498 },
1499 Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1502 children,
1503 on_load_more,
1504 loading,
1505 has_more,
1506 on_refresh: Some(tok(on_refresh)),
1507 refreshing,
1508 end_label,
1509 fill,
1510 },
1511 other => other,
1512 }
1513}
1514
1515#[must_use]
1520pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1521 match widget {
1522 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, .. } => {
1523 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar }
1524 }
1525 other => other,
1526 }
1527}
1528
1529#[must_use]
1537pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1538 match widget {
1539 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, .. } => {
1540 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar }
1541 }
1542 other => other,
1543 }
1544}
1545
1546#[must_use]
1552pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1553 Widget::LazyList {
1554 children,
1555 on_load_more: Some(tok(on_load_more)),
1556 loading,
1557 has_more,
1558 on_refresh: None,
1559 refreshing: false,
1560 end_label: None,
1561 fill: false,
1562 }
1563}
1564
1565#[must_use]
1567pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1568 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1569}
1570
1571#[must_use]
1575pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1576 match widget {
1577 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1578 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1579 }
1580 other => other,
1581 }
1582}
1583
1584#[must_use]
1589pub fn with_fill(widget: Widget) -> Widget {
1590 match widget {
1591 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1592 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1593 }
1594 other => other,
1595 }
1596}
1597
1598#[cfg(test)]
1599mod tests {
1600 #[test]
1601 fn with_tab_count_formats_and_caps() {
1602 let t = || tab_icon("Nalog", Icon::Person, false, "Account");
1603 assert_eq!(with_tab_count(t(), 7, "7 novih").badge, Some(TabBadge { text: "7".into(), label: "7 novih".into() }));
1604 assert_eq!(with_tab_count(t(), 99, "").badge.unwrap().text, "99");
1605 assert_eq!(with_tab_count(t(), 100, "").badge.unwrap().text, "99+");
1606 assert_eq!(with_tab_count(t(), u32::MAX, "").badge.unwrap().text, "99+");
1607 }
1608
1609 #[test]
1610 fn with_tab_count_zero_clears_a_badge() {
1611 let dotted = with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke");
1612 assert!(dotted.badge.is_some());
1613 assert_eq!(with_tab_count(dotted, 0, "ignored").badge, None);
1614 }
1615
1616 #[test]
1617 fn with_tab_dot_has_empty_text_and_plain_tabs_have_no_badge() {
1618 assert_eq!(with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke").badge, Some(TabBadge { text: String::new(), label: "Nove poruke".into() }));
1619 assert_eq!(tab("Nalog", false, "Account").badge, None);
1620 assert_eq!(tab_icon("Nalog", Icon::Person, true, "Account").badge, None);
1621 let t = with_tab_count(with_tab_dot(tab("Nalog", false, "Account"), "a"), 3, "b");
1623 assert_eq!(t.badge, Some(TabBadge { text: "3".into(), label: "b".into() }));
1624 }
1625
1626 use super::*;
1627 use serde::Serialize;
1628
1629 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1630 enum Route {
1631 Home,
1632 Detail(u32),
1633 }
1634
1635 #[derive(Serialize)]
1636 enum Ev {
1637 Tap,
1638 Open(u32),
1639 }
1640
1641 #[test]
1644 fn plugin_response_carries_bytes_and_converts_text() {
1645 let r = PluginResponse::text(true, "hello");
1646 assert!(r.ok);
1647 assert_eq!(r.output, b"hello".to_vec());
1648 assert_eq!(r.as_text(), Some("hello"));
1649
1650 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1651 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1652 }
1653
1654 #[test]
1657 fn nav_push_pop_depth() {
1658 let mut nav = Nav::new(Route::Home);
1659 assert_eq!(nav.depth(), 1);
1660 assert!(!nav.can_go_back());
1661
1662 nav.push(Route::Detail(7));
1663 assert_eq!(nav.depth(), 2);
1664 assert!(nav.can_go_back());
1665 assert!(matches!(nav.current(), Route::Detail(7)));
1666
1667 nav.pop();
1668 assert_eq!(nav.depth(), 1);
1669 assert!(matches!(nav.current(), Route::Home));
1670
1671 nav.pop(); assert_eq!(nav.depth(), 1);
1673 }
1674
1675 #[test]
1676 fn nav_reset_replaces_stack() {
1677 let mut nav = Nav::new(Route::Home);
1678 nav.push(Route::Detail(1));
1679 nav.push(Route::Detail(2));
1680 nav.reset(Route::Detail(9));
1681 assert_eq!(nav.depth(), 1);
1682 assert!(matches!(nav.current(), Route::Detail(9)));
1683 }
1684
1685 #[test]
1686 fn nav_route_key_is_serialization() {
1687 let nav = Nav::new(Route::Detail(3));
1688 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1689 }
1690
1691 #[test]
1694 fn scaffold_sets_route_depth_and_no_back() {
1695 match scaffold("Home", false, vec![], text("x")) {
1696 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1697 assert_eq!(route, "Home");
1698 assert_eq!(depth, 1);
1699 assert!(back.is_none());
1700 assert!(!dark_mode);
1701 }
1702 other => panic!("expected Scaffold, got {other:?}"),
1703 }
1704 }
1705
1706 #[test]
1707 fn scaffold_back_is_depth_2_with_back() {
1708 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1709 Widget::Scaffold { depth, back, dark_mode, .. } => {
1710 assert_eq!(depth, 2);
1711 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1712 assert!(dark_mode);
1713 }
1714 other => panic!("expected Scaffold, got {other:?}"),
1715 }
1716 }
1717
1718 #[test]
1719 fn nav_scaffold_shows_back_only_when_poppable() {
1720 let mut nav = Nav::new(Route::Home);
1721 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1723 Widget::Scaffold { back, depth, route, .. } => {
1724 assert!(back.is_none());
1725 assert_eq!(depth, 1);
1726 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1727 }
1728 other => panic!("expected Scaffold, got {other:?}"),
1729 }
1730 nav.push(Route::Detail(2));
1732 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1733 Widget::Scaffold { back, depth, .. } => {
1734 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1735 assert_eq!(depth, 2);
1736 }
1737 other => panic!("expected Scaffold, got {other:?}"),
1738 }
1739 }
1740
1741 #[test]
1742 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1743 let l = ShellLabels::new().back("Nazad").ok("U redu");
1744 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1745 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1746 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1747 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1749 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1750 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1751 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1752 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1753 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1754 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1755 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1756 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1758 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1760 let nav = Nav::new(Route::Home);
1762 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1763 }
1764
1765 #[test]
1766 fn button_with_carries_tone_icon_and_width() {
1767 assert!(matches!(
1768 button("Go", ButtonStyle::Filled, Ev::Tap),
1769 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1770 ));
1771 assert!(matches!(
1772 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1773 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1774 ));
1775 }
1776
1777 #[test]
1778 fn buttons_carry_serialized_event_tokens() {
1779 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1780 Widget::Button { label, on_press, .. } => {
1781 assert_eq!(label, "Go");
1782 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1783 }
1784 other => panic!("expected Button, got {other:?}"),
1785 }
1786 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1787 Widget::Card { on_press, .. } => {
1788 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1789 }
1790 other => panic!("expected Card, got {other:?}"),
1791 }
1792 match card(text("c"), CardStyle::Elevated) {
1794 Widget::Card { on_press, on_long_press, .. } => {
1795 assert!(on_press.is_none());
1796 assert!(on_long_press.is_none());
1797 }
1798 other => panic!("expected Card, got {other:?}"),
1799 }
1800 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1802 Widget::Card { on_press, on_long_press, .. } => {
1803 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1804 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1805 }
1806 other => panic!("expected Card, got {other:?}"),
1807 }
1808 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1810 }
1811
1812 #[test]
1815 fn cx_notify_and_save_enqueue_notifications() {
1816 let mut cx = Cx::<Ev>::default();
1817 cx.notify("toast", "show", "hi");
1818 cx.save("blob");
1819 assert_eq!(cx.notifications.len(), 2);
1820 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1821 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1822 assert!(cx.requests.is_empty());
1823 }
1824
1825 #[test]
1826 fn cx_http_helpers_build_requests() {
1827 let mut cx = Cx::<Ev>::default();
1828 cx.get("http://h/x", |_| Ev::Tap);
1829 cx.post("http://h/y", "hello", |_| Ev::Tap);
1830 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1831 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1832 cx.delete("http://h/d", |_| Ev::Tap);
1833
1834 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1835 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1836 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1837
1838 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1839 assert_eq!(get_input["url"], "http://h/x");
1840 assert!(get_input["body"].is_null());
1841
1842 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1843 assert_eq!(put_input["url"], "http://h/p");
1844 assert_eq!(put_input["body"], "putbody");
1845 }
1846
1847 #[test]
1848 fn request_builder_emits_headers_in_order() {
1849 let mut cx = Cx::<Ev>::default();
1850 cx.request("PUT", "http://h/access-key")
1851 .bearer("tok123")
1852 .header("X-Trace-Id", "abc")
1853 .body("{}")
1854 .send(|_| Ev::Tap);
1855
1856 assert_eq!(cx.requests.len(), 1);
1857 let (call, _) = &cx.requests[0];
1858 assert_eq!(call.plugin, "http");
1859 assert_eq!(call.op, "PUT");
1860
1861 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1862 assert_eq!(input["url"], "http://h/access-key");
1863 assert_eq!(input["body"], "{}");
1864 assert_eq!(input["headers"][0]["name"], "Authorization");
1865 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1866 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1867 assert_eq!(input["headers"][1]["value"], "abc");
1868 }
1869
1870 #[test]
1871 fn helpers_emit_no_headers_field_content() {
1872 let mut cx = Cx::<Ev>::default();
1873 cx.get("http://h/x", |_| Ev::Tap);
1874 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1875 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1876 }
1877
1878 #[test]
1879 fn continuation_receives_decoded_outcome() {
1880 #[derive(Debug, PartialEq)]
1881 enum Got { Conflict, Offline, Other }
1882
1883 let classify = |r: PluginResponse| -> Got {
1884 match HttpOutcome::decode(&r.output).unwrap() {
1885 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1886 HttpOutcome::TransportError { .. } => Got::Offline,
1887 _ => Got::Other,
1888 }
1889 };
1890
1891 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1892 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1893
1894 let offline = HttpOutcome::TransportError { message: "refused".into() };
1895 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1896 }
1897
1898 #[test]
1899 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1900 let mut cx = Cx::<Ev>::default();
1905
1906 cx.request("GET", "http://h/x").send(|outcome| {
1907 match outcome {
1908 HttpOutcome::TransportError { message } => {
1909 assert!(
1910 message.contains("malformed http response"),
1911 "unexpected message: {message}"
1912 );
1913 }
1914 HttpOutcome::Response { .. } => {
1915 panic!("garbage bytes must not decode as a Response")
1916 }
1917 }
1918 Ev::Tap
1919 });
1920
1921 assert_eq!(cx.requests.len(), 1);
1922 let (_, continuation) = cx.requests.remove(0);
1923 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1926 }
1927
1928 #[test]
1929 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1930 let mut cx = Cx::<Ev>::default();
1931 cx.pick_photo(|_| Ev::Tap);
1932 cx.capture_photo(|_| Ev::Tap);
1933 assert_eq!(cx.requests.len(), 2);
1934 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", ""));
1937 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", ""));
1938 }
1939
1940 #[test]
1941 fn cx_capture_photo_routes_success_and_cancel() {
1942 let mut cx = Cx::<Ev>::default();
1944 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1945 let (_, then) = cx.requests.pop().unwrap();
1946 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1947
1948 let mut cx = Cx::<Ev>::default();
1950 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1951 let (_, then) = cx.requests.pop().unwrap();
1952 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1953 }
1954
1955 #[test]
1956 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1957 let mut cx = Cx::<Ev>::default();
1958 cx.copy("c");
1959 cx.share("s");
1960 cx.open_url("u");
1961 cx.toast("t");
1962 cx.haptic("heavy");
1963 let got: Vec<(&str, &str, &str)> = cx
1964 .notifications
1965 .iter()
1966 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1967 .collect();
1968 assert_eq!(
1969 got,
1970 vec![
1971 ("clipboard", "copy", "c"),
1972 ("share", "text", "s"),
1973 ("browser", "open", "u"),
1974 ("toast", "show", "t"),
1975 ("haptics", "heavy", ""), ]
1977 );
1978 assert!(cx.requests.is_empty());
1979 }
1980
1981 #[test]
1982 fn display_and_headline_builders() {
1983 assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
1984 assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
1985 let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
1986 }
1987
1988 #[test]
1989 fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
1990 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
1991 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
1992 assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
1993 assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
1994 }
1995
1996 #[test]
1997 fn with_theme_and_labels_keep_the_appearance() {
1998 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
1999 let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
2000 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
2001 }
2002
2003 #[test]
2004 fn appearance_query_and_stream_shapes() {
2005 let mut cx = Cx::<Ev>::default();
2006 cx.system_appearance(|_| Ev::Tap);
2007 let (call, _) = &cx.requests[0];
2008 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
2009 cx.subscribe_appearance("appr", |_| Ev::Tap);
2010 let (st, _) = &cx.streams[0];
2011 assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
2012 }
2013
2014 #[test]
2015 fn photo_with_calls_send_options_on_the_same_plugin() {
2016 let mut cx = Cx::<Ev>::default();
2017 cx.pick_photo_with(PhotoOptions::new().jpeg(), |_| Ev::Tap);
2018 cx.capture_photo_with(PhotoOptions::new(), |_| Ev::Tap);
2019 let (p, _) = &cx.requests[0];
2020 assert_eq!((p.plugin.as_str(), p.op.as_str(), p.input.as_str()), ("photo", "pick", r#"{"format":"jpeg"}"#));
2021 let (c, _) = &cx.requests[1];
2022 assert_eq!((c.plugin.as_str(), c.op.as_str(), c.input.as_str()), ("camera", "capture", "{}"));
2023 }
2024
2025 #[test]
2026 fn device_info_is_the_device_info_op() {
2027 let mut cx = Cx::<Ev>::default();
2028 cx.device_info(|_| Ev::Tap);
2029 let (call, _) = &cx.requests[0];
2030 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "info", ""));
2031 }
2032
2033 #[test]
2034 fn cx_device_model_is_a_request_not_a_notification() {
2035 let mut cx = Cx::<Ev>::default();
2036 cx.device_model(|_| Ev::Tap);
2037 assert!(cx.notifications.is_empty());
2038 assert_eq!(cx.requests.len(), 1);
2039 let (call, _) = &cx.requests[0];
2040 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
2041 }
2042
2043 #[test]
2044 fn cx_device_locale_requests_the_device_locale_op() {
2045 let mut cx = Cx::<Ev>::default();
2046 cx.device_locale(|_| Ev::Tap);
2047 assert!(cx.notifications.is_empty());
2048 assert_eq!(cx.requests.len(), 1);
2049 let (call, _) = &cx.requests[0];
2050 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
2051 }
2052
2053 #[test]
2054 fn cx_now_requests_the_datetime_now_op() {
2055 let mut cx = Cx::<Ev>::default();
2056 cx.now(|_| Ev::Tap);
2057 assert_eq!(cx.requests.len(), 1);
2058 let (call, _) = &cx.requests[0];
2059 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
2060 }
2061
2062 #[test]
2063 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
2064 let mut cx = Cx::<Ev>::default();
2065 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2066 assert!(cx.notifications.is_empty());
2068 assert!(cx.requests.is_empty());
2069 assert_eq!(cx.streams.len(), 1);
2070 let (call, on_event) = &cx.streams[0];
2071 assert_eq!(
2072 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
2073 ("ws", "websocket", "stream", "wss://h/x")
2074 );
2075 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
2077 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
2078 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
2079 }
2080
2081 #[test]
2082 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
2083 let mut cx = Cx::<Ev>::default();
2084 cx.unsubscribe("ws");
2085 assert!(cx.streams.is_empty());
2086 assert_eq!(cx.notifications.len(), 1);
2087 assert_eq!(
2089 cx.notifications[0],
2090 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
2091 );
2092 }
2093
2094 #[test]
2095 fn cx_confirm_serializes_title_message_and_routes_ok() {
2096 let mut cx = Cx::<Ev>::default();
2097 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2098 let (call, then) = cx.requests.pop().unwrap();
2099 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2100 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2101 assert_eq!(v["title"], "Delete?");
2102 assert_eq!(v["message"], "This cannot be undone.");
2103 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2105 }
2106
2107 #[test]
2108 fn cx_confirm_stays_byte_identical_on_the_wire() {
2109 let mut cx = Cx::<Ev>::default();
2110 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2111 let (call, _) = cx.requests.pop().unwrap();
2112 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2113 }
2114
2115 #[test]
2116 fn cx_confirm_with_sends_labels_and_destructive() {
2117 let mut cx = Cx::<Ev>::default();
2118 cx.confirm_with(
2119 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2120 .confirm_label("Otkaži termin")
2121 .cancel_label("Ne, vrati se")
2122 .destructive(),
2123 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2124 );
2125 let (call, then) = cx.requests.pop().unwrap();
2126 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2127 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2128 assert_eq!(v["title"], "Otkazati termin?");
2129 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2130 assert_eq!(v["confirm_label"], "Otkaži termin");
2131 assert_eq!(v["cancel_label"], "Ne, vrati se");
2132 assert_eq!(v["destructive"], true);
2133 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2134 let mut cx = Cx::<Ev>::default();
2136 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2137 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2138 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2139 }
2140
2141 #[test]
2142 fn with_step_caption_turns_the_caption_on() {
2143 assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2144 assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2145 assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2146 }
2147
2148 #[test]
2149 fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2150 let mut cx = Cx::<Ev>::default();
2151 cx.open_url("https://x");
2152 assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2153 cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2154 let (call, then) = cx.requests.pop().unwrap();
2155 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2156 assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2157 }
2158
2159 #[test]
2160 fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2161 let bar = vec![text("A"), text("B")];
2162 let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2163 assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2164 assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2165 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2166 let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2167 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2168 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2169 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2170 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2171 assert!(keep(with_theme(s.clone(), Theme::default())));
2172 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2173 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2174 }
2175
2176 #[test]
2177 fn steps_builder_clamps_and_step_text_fills_the_template() {
2178 assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2179 assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2180 assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2181 assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2182 assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2183 assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2184 }
2185
2186 #[test]
2187 fn with_columns_sets_clamps_and_ignores_other_widgets() {
2188 assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2189 assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2190 assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2191 assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2192 assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2193 }
2194
2195 #[test]
2196 fn badge_icon_and_avatar_initials_modifiers() {
2197 assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2198 assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2199 let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2200 assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2201 assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2202 assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2204 assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2205 assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2206 }
2207
2208 #[test]
2209 fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2210 let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2211 assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2212 let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2213 assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2214 }
2215
2216 #[test]
2217 fn snackbar_input_is_the_wire_json() {
2218 assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2219 assert_eq!(
2220 Snackbar::new("Cancelled").action("Undo").long().to_input(),
2221 r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2222 );
2223 }
2224
2225 #[test]
2226 fn cx_snackbar_sends_a_snackbar_show_request() {
2227 let mut cx = Cx::<Ev>::default();
2228 cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2229 let (call, then) = cx.requests.pop().unwrap();
2230 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2231 assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2232 assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2233 }
2234
2235 #[test]
2236 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2237 let mut cx = Cx::<Ev>::default();
2238 cx.pick_date(|_| Ev::Tap);
2239 cx.pick_time(|_| Ev::Tap);
2240 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2241
2242 let mut cx = Cx::<Ev>::default();
2243 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2244 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2245 let (date, _) = &cx.requests[0];
2246 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2247 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2248 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2249 let (time, _) = &cx.requests[1];
2250 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2251 }
2252
2253 #[test]
2256 fn text_builders_carry_their_style() {
2257 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2258 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2259 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2260 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2261 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2262 }
2263
2264 #[test]
2265 fn layout_and_content_builders_produce_their_variants() {
2266 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2267 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2268 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2269 assert!(matches!(divider(), Widget::Divider));
2270 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2271 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2272 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2273 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)));
2274 let rc = with_bracket(
2275 region_chart(
2276 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2277 vec![ChartTick::new(3.0, "3 Mt.")],
2278 65.0, 80.0,
2279 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2280 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2281 ),
2282 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2283 );
2284 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2285 assert!(matches!(
2287 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2288 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2289 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2290 ));
2291 assert!(matches!(
2292 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2293 Widget::SwipeAction { actions, .. } if actions.len() == 1
2294 ));
2295 assert!(matches!(
2297 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2298 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2299 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2300 ));
2301 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2302 assert!(matches!(
2304 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2305 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2306 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2307 ));
2308 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2310 assert!(matches!(
2311 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2312 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2313 ));
2314 assert!(matches!(
2316 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2317 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2318 ));
2319 assert!(matches!(
2320 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2321 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2322 ));
2323 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2325 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2326 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2327 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2328 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2329 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2330 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2332 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2334 Widget::Split { show_detail: true, on_back: Some(_), .. }));
2335 }
2336
2337 #[test]
2338 fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2339 assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2340 assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2341 let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2342 assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2343 let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2345 assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2346 assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2347 assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2348 }
2349
2350 #[test]
2351 fn input_builders_carry_ids_values_and_event_tokens() {
2352 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2353 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2354 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2355 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2357 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2358 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2359 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2360 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2362 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2363 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2364 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2365 with_captions(video_player("v", "u", true, -1, Ev::Tap),
2366 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2367 "p.jpg"), 9000), 1.5), 0.5));
2368 assert!(matches!(tuned,
2369 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2370 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2371 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2373 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2374 assert!(matches!(with_pip(divider()), Widget::Divider));
2376 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2377 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2378 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2379 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2380 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2381 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2382 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2383 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2384
2385 match chip("Latte", true, Ev::Open(2)) {
2386 Widget::Chip { selected, on_press, .. } => {
2387 assert!(selected);
2388 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2389 }
2390 other => panic!("expected Chip, got {other:?}"),
2391 }
2392 match stepper(5, Ev::Tap, Ev::Open(1)) {
2393 Widget::Stepper { value, on_decrement, on_increment } => {
2394 assert_eq!(value, 5);
2395 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2396 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2397 }
2398 other => panic!("expected Stepper, got {other:?}"),
2399 }
2400 let t = tab("Home", true, Ev::Tap);
2401 assert_eq!(t.label, "Home");
2402 assert!(t.selected);
2403 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2404 }
2405
2406 #[test]
2409 fn widget_tree_round_trips_through_serde() {
2410 let tree = scaffold(
2411 "Home",
2412 true,
2413 vec![tab("A", true, Ev::Tap)],
2414 column(vec![
2415 title("Hi"),
2416 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2417 image("u", ImageShape::Rounded, ImageRatio::Wide),
2418 slider("s", 2, 5),
2419 ]),
2420 );
2421 let s = serde_json::to_string(&tree).unwrap();
2422 let back: Widget = serde_json::from_str(&s).unwrap();
2423 assert_eq!(s, serde_json::to_string(&back).unwrap());
2424 }
2425
2426 #[test]
2427 fn actions_and_input_values_round_trip() {
2428 let actions = vec![
2429 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2430 Action::Input { id: "n".into(), value: InputValue::Int(7) },
2431 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2432 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2433 Action::Restore { data: "blob".into() },
2434 Action::Start,
2435 Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2436 ];
2437 for a in actions {
2438 let s = serde_json::to_string(&a).unwrap();
2439 let back: Action = serde_json::from_str(&s).unwrap();
2440 assert_eq!(s, serde_json::to_string(&back).unwrap());
2441 }
2442 }
2443
2444 #[derive(Default)]
2447 struct CounterModel {
2448 count: i32,
2449 restored: String,
2450 started: bool,
2451 last_input: String,
2452 app_build: String,
2453 }
2454
2455 #[derive(serde::Serialize, serde::Deserialize)]
2456 enum CounterEv {
2457 Inc,
2458 Add(i32),
2459 }
2460
2461 #[derive(Default)]
2462 struct CounterApp;
2463
2464 impl MobilerApp for CounterApp {
2465 type Event = CounterEv;
2466 type Model = CounterModel;
2467 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2468 match ev {
2469 CounterEv::Inc => model.count += 1,
2470 CounterEv::Add(n) => model.count += n,
2471 }
2472 }
2473 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2474 if let InputValue::Text(t) = value {
2475 model.last_input = format!("{id}={t}");
2476 }
2477 }
2478 fn restore(&self, data: &str, model: &mut CounterModel) {
2479 model.restored = data.to_string();
2480 }
2481 fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2482 model.started = true;
2483 model.app_build = cx.app_info().build.clone();
2484 }
2485 fn view(&self, model: &CounterModel) -> Widget {
2486 text(format!("{}", model.count))
2487 }
2488 }
2489
2490 #[test]
2491 fn shell_dispatches_fired_input_restore_and_start() {
2492 use crux_core::App as _;
2493 let shell = MobilerShell::<CounterApp>::default();
2494 let mut m = CounterModel::default();
2495
2496 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2498 assert_eq!(m.count, 5);
2499 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2501 assert_eq!(m.last_input, "name=bob");
2502 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2504 assert_eq!(m.restored, "saved");
2505 let _ = shell.update(Action::Start, &mut m);
2507 assert!(m.started);
2508 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2510 }
2511
2512 fn info(build: &str) -> AppInfo {
2513 AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2514 }
2515
2516 fn app_info_action(build: &str) -> Action {
2517 let i = info(build);
2518 Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2519 }
2520
2521 static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2524
2525 #[test]
2526 fn init_sees_app_info_sent_before_start() {
2527 use crux_core::App as _;
2528 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2529 let shell = MobilerShell::<CounterApp>::default();
2530 let mut m = CounterModel::default();
2531 let _ = shell.update(app_info_action("7"), &mut m);
2532 let _ = shell.update(Action::Start, &mut m);
2533 assert_eq!(m.app_build, "7");
2534 }
2535
2536 #[test]
2537 fn later_app_info_replaces_earlier() {
2538 use crux_core::App as _;
2539 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2540 let shell = MobilerShell::<CounterApp>::default();
2541 let mut m = CounterModel::default();
2542 let _ = shell.update(app_info_action("7"), &mut m);
2543 let _ = shell.update(app_info_action("8"), &mut m);
2544 let _ = shell.update(Action::Start, &mut m);
2545 assert_eq!(m.app_build, "8");
2546 }
2547
2548 #[test]
2549 fn app_info_action_does_not_touch_the_model() {
2550 use crux_core::App as _;
2551 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2552 let shell = MobilerShell::<CounterApp>::default();
2553 let mut m = CounterModel::default();
2554 let _ = shell.update(app_info_action("9"), &mut m);
2555 assert!(!m.started);
2556 assert_eq!(m.count, 0);
2557 assert!(m.restored.is_empty());
2558 assert!(m.last_input.is_empty());
2559 assert!(m.app_build.is_empty());
2560 }
2561
2562 #[test]
2563 fn cx_default_has_empty_app_info() {
2564 let cx = Cx::<Ev>::default();
2565 assert_eq!(cx.app_info(), &AppInfo::default());
2566 assert!(cx.app_info().platform.is_empty());
2567 }
2568
2569 #[test]
2570 fn cx_with_app_info_carries_it() {
2571 let cx = Cx::<Ev>::with_app_info(info("42"));
2572 assert_eq!(cx.app_info().build, "42");
2573 assert_eq!(cx.app_info().bundle_id, "rs.x");
2574 }
2575
2576 #[test]
2577 fn shell_ignores_a_malformed_fired_token() {
2578 use crux_core::App as _;
2579 let shell = MobilerShell::<CounterApp>::default();
2580 let mut m = CounterModel::default();
2581 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2584 assert_eq!(m.count, 0);
2585 }
2586
2587 #[derive(Default)]
2590 struct EffectsApp;
2591
2592 impl MobilerApp for EffectsApp {
2593 type Event = CounterEv;
2594 type Model = CounterModel;
2595 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2596 model.count += 1;
2597 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2598 cx.notify("toast", "show", "hi");
2599 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2600 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2601 }
2602 fn view(&self, model: &CounterModel) -> Widget {
2603 text(format!("{}", model.count))
2604 }
2605 }
2606
2607 #[test]
2608 fn shell_renders_before_requests_notifications_and_streams() {
2609 use crux_core::App as _;
2610 let shell = MobilerShell::<EffectsApp>::default();
2611 let mut m = CounterModel::default();
2612 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2613 let kinds: Vec<String> = cmd
2614 .effects()
2615 .map(|e| match e {
2616 Effect::Render(_) => "render".to_string(),
2617 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2618 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2619 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2620 })
2621 .collect();
2622 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2625 }
2626
2627 #[test]
2630 fn upload_builder_emits_transfer_stream_call() {
2631 let mut cx = Cx::<Ev>::default();
2632 let key = cx
2633 .upload("https://h/put", "file:///tmp/a.enc")
2634 .bearer("tok")
2635 .header("Content-Type", "application/octet-stream")
2636 .start("up-1", |_ev| Ev::Tap);
2637
2638 assert_eq!(key, "up-1");
2639 assert_eq!(cx.streams.len(), 1);
2640 let (call, _) = &cx.streams[0];
2641 assert_eq!(call.key, "up-1");
2642 assert_eq!(call.plugin, "transfer");
2643 assert_eq!(call.op, "upload");
2644
2645 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2646 assert_eq!(v["url"], "https://h/put");
2647 assert_eq!(v["source"], "file:///tmp/a.enc");
2648 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2650 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2651 assert_eq!(v["headers"][1]["name"], "Content-Type");
2652 }
2653
2654 #[test]
2655 fn download_builder_uses_dest_and_no_default_method() {
2656 let mut cx = Cx::<Ev>::default();
2657 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2658 let (call, _) = &cx.streams[0];
2659 assert_eq!(call.op, "download");
2660 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2661 assert_eq!(v["dest"], "/data/att-9.enc");
2662 assert!(v.get("source").is_none());
2663 }
2664
2665 #[test]
2666 fn start_continuation_decodes_progress_and_done() {
2667 use crate::http::HttpOutcome;
2668
2669 #[derive(Debug, PartialEq)]
2672 enum Got {
2673 Prog(u64),
2674 Done(u16),
2675 Bad,
2676 }
2677 #[derive(Debug, PartialEq)]
2678 struct GotEv(Got);
2679
2680 let mut cx = Cx::<GotEv>::default();
2681 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2682 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2683 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2684 Some(s) => Got::Done(s),
2685 None => Got::Bad,
2686 }),
2687 });
2688 let (_, cont) = &cx.streams[0];
2689
2690 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2691 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2692
2693 let done = TransferEvent::Done {
2694 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2695 handle: Some("/d".into()),
2696 };
2697 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2698 }
2699
2700 #[test]
2701 fn calendar_in_localizes_layout_and_clamps_markers() {
2702 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2704 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2705 assert_eq!(title, "Septembar 2026");
2706 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2707 assert_eq!(leading_blanks, 1);
2708 assert_eq!(on_day.len(), 30);
2709 assert_eq!(markers.len(), 30, "padded to one level per day");
2710 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2711 assert!(matches!(
2713 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2714 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2715 ));
2716 }
2717
2718 #[test]
2719 fn scroller_hint_is_opt_in() {
2720 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2721 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2722 }
2723}