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,
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) {
363 self.plugin("photo", "pick", options.to_input(), move |r| then(photo::from_response(&r)));
364 }
365
366 pub fn capture_photo_with(&mut self, options: PhotoOptions, then: impl FnOnce(Result<Photo, PhotoError>) -> E + Send + 'static) {
369 self.plugin("camera", "capture", options.to_input(), move |r| then(photo::from_response(&r)));
370 }
371
372 pub fn confirm(
376 &mut self,
377 title: impl Into<String>,
378 message: impl Into<String>,
379 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
380 ) {
381 self.confirm_with(Confirm::new(title, message), then);
382 }
383
384 pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
388 self.plugin("dialog", "confirm", dialog.to_input(), then);
389 }
390
391 pub fn snackbar(&mut self, snackbar: Snackbar, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
397 self.plugin("snackbar", "show", snackbar.to_input(), then);
398 }
399
400 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
405 self.plugin("datetime", "date", "", then);
406 }
407
408 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
413 self.plugin("datetime", "time", "", then);
414 }
415
416 pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
418 self.plugin("datetime", "date", picker.to_input(), then);
419 }
420
421 pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
423 self.plugin("datetime", "time", picker.to_input(), then);
424 }
425
426 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
433 self.plugin("datetime", "now", "", then);
434 }
435}
436
437pub trait MobilerApp: Default {
442 type Event: Serialize + DeserializeOwned + Send + 'static;
443 type Model: Default;
444
445 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
446
447 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
448 let _ = (id, value, model, cx);
449 }
450
451 fn restore(&self, data: &str, model: &mut Self::Model) {
454 let _ = (data, model);
455 }
456
457 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
460 let _ = (model, cx);
461 }
462
463 fn view(&self, model: &Self::Model) -> Widget;
464}
465
466pub struct MobilerShell<A>(PhantomData<fn() -> A>);
468
469impl<A> Default for MobilerShell<A> {
470 fn default() -> Self {
471 Self(PhantomData)
472 }
473}
474
475impl<A: MobilerApp> App for MobilerShell<A> {
476 type Event = Action;
477 type Model = A::Model;
478 type ViewModel = Widget;
479 type Effect = Effect;
480
481 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
482 let app = A::default();
483 let mut cx = Cx::<A::Event>::with_app_info(app_info::get());
484 match action {
485 Action::Fired { token } => {
486 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
487 app.update(event, model, &mut cx);
488 }
489 }
490 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
491 Action::Restore { data } => app.restore(&data, model),
492 Action::Start => app.init(model, &mut cx),
493 Action::AppInfo { version, build, platform, bundle_id } => {
494 app_info::set(AppInfo { version, build, platform, bundle_id });
495 }
496 }
497 let mut commands: Vec<Command<Effect, Action>> = vec![render()];
503 for op in cx.notifications {
504 commands.push(Command::notify_shell(op).build());
505 }
506 for (op, then) in cx.requests {
507 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
508 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
509 }));
510 }
511 for (op, then) in cx.streams {
512 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
515 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
516 }));
517 }
518 Command::all(commands)
519 }
520
521 fn view(&self, model: &Self::Model) -> Widget {
522 A::default().view(model)
523 }
524}
525
526#[derive(Clone, Debug)]
545pub struct Nav<R> {
546 stack: Vec<R>,
547}
548
549impl<R: Clone + Serialize> Nav<R> {
550 #[must_use]
552 pub fn new(root: R) -> Self {
553 Self { stack: vec![root] }
554 }
555 pub fn push(&mut self, route: R) {
557 self.stack.push(route);
558 }
559 pub fn pop(&mut self) {
561 if self.stack.len() > 1 {
562 self.stack.pop();
563 }
564 }
565 pub fn reset(&mut self, root: R) {
567 self.stack = vec![root];
568 }
569 #[must_use]
571 pub fn current(&self) -> &R {
572 self.stack.last().expect("nav stack is never empty")
573 }
574 #[must_use]
576 pub fn depth(&self) -> u32 {
577 self.stack.len() as u32
578 }
579 #[must_use]
581 pub fn can_go_back(&self) -> bool {
582 self.stack.len() > 1
583 }
584 fn route_key(&self) -> String {
587 serde_json::to_string(self.current()).expect("serialize route")
588 }
589}
590
591fn tok<E: Serialize>(event: E) -> String {
595 serde_json::to_string(&event).expect("serialize event")
596}
597
598#[must_use]
599pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
600 Widget::Text { content: content.into(), style }
601}
602#[must_use]
603pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
604#[must_use]
605pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
606#[must_use]
607pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
608#[must_use]
609pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
610#[must_use]
611pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
612#[must_use]
615pub fn display(content: impl Into<String>) -> Widget { styled(content, TextStyle::Display) }
616#[must_use]
618pub fn headline(content: impl Into<String>) -> Widget { styled(content, TextStyle::Headline) }
619
620#[must_use]
621pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
622 Widget::Image { source: source.into(), shape, ratio }
623}
624#[must_use]
625pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
626 Widget::Badge { label: label.into(), tone, icon: None }
627}
628#[must_use]
630pub fn color_dot(color: ProjectColor) -> Widget {
631 Widget::ColorDot { color }
632}
633#[must_use]
634pub fn divider() -> Widget { Widget::Divider }
635#[must_use]
637pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
638#[must_use]
640pub fn skeleton() -> Widget { Widget::Skeleton }
641#[must_use]
645pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
646#[must_use]
655pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
656 Widget::Video {
657 url: url.into(),
658 id: id.into(),
659 playing,
660 seek_to_ms,
661 controls: true,
662 looping: false,
663 muted: false,
664 on_ended: Some(tok(on_ended)),
665 poster: None,
666 start_at_ms: -1,
667 captions: Vec::new(),
668 rate: 1.0,
669 volume: 1.0,
670 urls: Vec::new(),
671 start_index: 0,
672 seek_index: -1,
673 allow_pip: false,
674 }
675}
676#[must_use]
682pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
683 Widget::Video {
684 url: urls.first().cloned().unwrap_or_default(),
685 id: id.into(),
686 playing,
687 seek_to_ms: -1,
688 controls: true,
689 looping: false,
690 muted: false,
691 on_ended: Some(tok(on_ended)),
692 poster: None,
693 start_at_ms: -1,
694 captions: Vec::new(),
695 rate: 1.0,
696 volume: 1.0,
697 urls,
698 start_index,
699 seek_index: -1,
700 allow_pip: false,
701 }
702}
703fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
706 match widget {
707 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
708 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
709 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
710 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
711 f(&mut v);
712 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
713 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
714 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
715 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
716 allow_pip: v.allow_pip }
717 }
718 other => other,
719 }
720}
721struct VideoFields {
722 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
723 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
724 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
725 seek_index: i64, allow_pip: bool,
726}
727#[must_use]
729pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
730#[must_use]
732pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
733#[must_use]
735pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
736#[must_use]
738pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
739 let poster = poster.into();
740 map_video(widget, move |v| v.poster = Some(poster))
741}
742#[must_use]
744pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
745 map_video(widget, move |v| v.start_at_ms = start_at_ms)
746}
747#[must_use]
749pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
750 map_video(widget, move |v| v.captions = captions)
751}
752#[must_use]
754pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
755#[must_use]
757pub fn with_volume(widget: Widget, volume: f32) -> Widget {
758 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
759}
760#[must_use]
762pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
763 map_video(widget, move |v| v.seek_index = index)
764}
765#[must_use]
767pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
768#[must_use]
773pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
774
775#[must_use]
781pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
782 Widget::Map {
783 id: id.into(),
784 center_lat,
785 center_lng,
786 zoom,
787 markers: Vec::new(),
788 style_url: None,
789 interactive: true,
790 }
791}
792#[must_use]
794pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
795 match widget {
796 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
797 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
798 other => other,
799 }
800}
801#[must_use]
803pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
804 match widget {
805 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
806 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
807 other => other,
808 }
809}
810#[must_use]
812pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
813 MapMarker { id: id.into(), lat, lng, title: None }
814}
815#[must_use]
817pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
818 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
819}
820fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
822 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
823}
824
825#[must_use]
828pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
829 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
830}
831#[must_use]
834pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
835 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
836}
837#[must_use]
841pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
842 Widget::Chart { series, labels, style, axis, legend }
843}
844#[must_use]
846pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
847 chart(series, labels, ChartStyle::StackedBar, true, true)
848}
849#[must_use]
851pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
852 chart(series, labels, ChartStyle::StackedBar100, false, true)
853}
854#[must_use]
856pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
857 chart(series, vec![], ChartStyle::Pie, false, true)
858}
859#[must_use]
861pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
862 chart(series, vec![], ChartStyle::Donut, false, true)
863}
864#[must_use]
867pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
868 chart(series, vec![], ChartStyle::Rings, false, true)
869}
870#[must_use]
872pub fn gauge_chart(series: ChartSeries) -> Widget {
873 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
874}
875
876#[must_use]
881pub fn region_chart(
882 regions: Vec<ChartRegion>,
883 ticks: Vec<ChartTick>,
884 x_max: f32,
885 y_max: f32,
886 ref_lines: Vec<ChartRefLine>,
887 legend: Vec<ChartLegendItem>,
888) -> Widget {
889 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
890}
891
892#[must_use]
894pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
895 match widget {
896 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
897 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
898 }
899 other => other,
900 }
901}
902
903fn days_in_month(year: u32, month: u8) -> u8 {
905 match month {
906 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
907 4 | 6 | 9 | 11 => 30,
908 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
909 _ => 30,
910 }
911}
912
913fn weekday(year: u32, month: u8, day: u8) -> u8 {
915 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
916 let y = if month < 3 { year - 1 } else { year };
917 let m = month as usize - 1;
918 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
919}
920
921#[must_use]
925pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
926 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
927}
928
929#[must_use]
934pub fn calendar_in<E: Serialize>(
935 locale: Locale,
936 year: u32,
937 month: u8,
938 selected: Option<u8>,
939 markers: &[u8],
940 on_day: impl Fn(u8) -> E,
941) -> Widget {
942 let n = days_in_month(year, month);
943 let start = locale.week_start().sun0();
944 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
945 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
946 let markers = if markers.is_empty() {
947 Vec::new()
948 } else {
949 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
950 };
951 Widget::Calendar {
952 year,
953 month,
954 title: format::month_year(year, u32::from(month), locale),
955 weekday_labels,
956 leading_blanks,
957 selected,
958 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
959 markers,
960 }
961}
962
963#[must_use]
966pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
967 Widget::SwipeAction {
968 child: Box::new(child),
969 actions: actions
970 .into_iter()
971 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
972 .collect(),
973 }
974}
975#[must_use]
976pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
977
978#[must_use]
979pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
980#[must_use]
981pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
982#[must_use]
983pub fn card(child: Widget, style: CardStyle) -> Widget {
984 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
985}
986#[must_use]
988pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
989 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
990}
991#[must_use]
995pub fn with_icon(widget: Widget, icon: Icon) -> Widget {
996 match widget {
997 Widget::Badge { label, tone, .. } => Widget::Badge { label, tone, icon: Some(icon) },
998 other => other,
999 }
1000}
1001
1002#[must_use]
1006pub fn with_initials(widget: Widget, initials: impl Into<String>) -> Widget {
1007 match widget {
1008 Widget::Avatar { source, status, size, .. } => Widget::Avatar { source, status, initials: Some(initials.into()), size },
1009 other => other,
1010 }
1011}
1012
1013#[must_use]
1016pub fn with_avatar_size(widget: Widget, size: u8) -> Widget {
1017 match widget {
1018 Widget::Avatar { source, status, initials, .. } => Widget::Avatar { source, status, initials, size: Some(size) },
1019 other => other,
1020 }
1021}
1022
1023#[must_use]
1026pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
1027 match widget {
1028 Widget::Card { child, style, on_press, .. } => Widget::Card {
1029 child,
1030 style,
1031 on_press,
1032 on_long_press: Some(tok(on_long_press)),
1033 },
1034 other => other,
1035 }
1036}
1037#[must_use]
1040pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
1041 Widget::Box { children, align, scrim }
1042}
1043#[must_use]
1048pub fn steps(total: u8, current: u8) -> Widget {
1049 Widget::Steps { total, current: current.min(total), caption: false }
1050}
1051
1052#[must_use]
1055pub fn with_step_caption(widget: Widget) -> Widget {
1056 match widget {
1057 Widget::Steps { total, current, .. } => Widget::Steps { total, current, caption: true },
1058 other => other,
1059 }
1060}
1061
1062#[must_use]
1065pub fn step_text(template: Option<&str>, current: u8, total: u8) -> String {
1066 let t = template.filter(|t| !t.is_empty()).unwrap_or("Step {current} of {total}");
1067 t.replace("{current}", ¤t.to_string()).replace("{total}", &total.to_string())
1068}
1069
1070#[must_use]
1071pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children, columns: None } }
1072#[must_use]
1075pub fn with_columns(widget: Widget, columns: u8) -> Widget {
1076 match widget {
1077 Widget::Grid { children, .. } => Widget::Grid { children, columns: Some(columns.clamp(1, 4)) },
1078 other => other,
1079 }
1080}
1081#[must_use]
1086pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
1087 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
1088}
1089#[must_use]
1091pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
1092#[must_use]
1094pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
1095#[must_use]
1097pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None, initials: None, size: None } }
1098#[must_use]
1100pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
1101 Widget::Avatar { source: source.into(), status: Some(status), initials: None, size: None }
1102}
1103#[must_use]
1105pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
1106#[must_use]
1108pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
1109 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
1110}
1111
1112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1120pub struct ButtonOpts {
1121 pub tone: Tone,
1122 pub icon: Option<Icon>,
1123 pub wide: bool,
1124}
1125
1126impl Default for ButtonOpts {
1127 fn default() -> Self {
1128 Self { tone: Tone::Neutral, icon: None, wide: false }
1129 }
1130}
1131
1132impl ButtonOpts {
1133 #[must_use]
1135 pub const fn tone(mut self, tone: Tone) -> Self {
1136 self.tone = tone;
1137 self
1138 }
1139 #[must_use]
1141 pub const fn icon(mut self, icon: Icon) -> Self {
1142 self.icon = Some(icon);
1143 self
1144 }
1145 #[must_use]
1147 pub const fn wide(mut self) -> Self {
1148 self.wide = true;
1149 self
1150 }
1151}
1152
1153#[must_use]
1154pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
1155 button_with(label, style, on_press, ButtonOpts::default())
1156}
1157
1158#[must_use]
1160pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1161 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1162}
1163#[must_use]
1164pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1165 Widget::IconButton { icon, on_press: tok(on_press) }
1166}
1167#[must_use]
1168pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1169 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1170}
1171#[must_use]
1172pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1173 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1174}
1175#[must_use]
1179pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1180 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1181}
1182#[must_use]
1184pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1185 field(id, placeholder, value, FieldKind::Secure, None)
1186}
1187#[must_use]
1189pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1190 field(id, placeholder, value, FieldKind::Email, None)
1191}
1192#[must_use]
1194pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1195 field(id, placeholder, value, FieldKind::Number, None)
1196}
1197#[must_use]
1199pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1200 field(id, placeholder, value, FieldKind::Decimal, None)
1201}
1202#[must_use]
1204pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1205 field(id, placeholder, value, FieldKind::Phone, None)
1206}
1207#[must_use]
1209pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1210 field(id, placeholder, value, FieldKind::Url, None)
1211}
1212#[must_use]
1214pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1215 field(id, placeholder, value, FieldKind::Multiline, None)
1216}
1217#[must_use]
1220pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1221 match widget {
1222 Widget::TextField { id, placeholder, value, kind, .. } =>
1223 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1224 other => other,
1225 }
1226}
1227
1228#[must_use]
1232pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1233 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1234}
1235#[must_use]
1238pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1239 match widget {
1240 Widget::A11y { child, label, role, .. } =>
1241 Widget::A11y { child, label, hint: Some(hint.into()), role },
1242 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1243 }
1244}
1245#[must_use]
1247pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1248 match widget {
1249 Widget::A11y { child, label, hint, .. } =>
1250 Widget::A11y { child, label, hint, role: Some(role) },
1251 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1252 }
1253}
1254#[must_use]
1256pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1257 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1258}
1259#[must_use]
1261pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1262 Segment { label: label.into(), selected, on_select: tok(on_select) }
1263}
1264#[must_use]
1266pub fn segmented(segments: Vec<Segment>) -> Widget {
1267 Widget::Segmented { segments }
1268}
1269#[must_use]
1270pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1271 Widget::Toggle { id: id.into(), label: label.into(), value }
1272}
1273#[must_use]
1274pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1275 Widget::Checkbox { id: id.into(), label: label.into(), value }
1276}
1277#[must_use]
1278pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1279 Widget::Slider { id: id.into(), value, max }
1280}
1281#[must_use]
1282pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1283 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1284}
1285
1286#[must_use]
1288pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1289 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1290}
1291
1292#[must_use]
1294pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1295 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1296}
1297
1298#[must_use]
1301pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1302 let title = title.into();
1303 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 }
1305}
1306
1307#[must_use]
1311pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1312 let title = title.into();
1313 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 }
1314}
1315
1316#[must_use]
1321pub fn nav_scaffold<R, E>(
1322 title: impl Into<String>,
1323 dark_mode: bool,
1324 tabs: Vec<Tab>,
1325 body: Widget,
1326 nav: &Nav<R>,
1327 on_back: E,
1328) -> Widget
1329where
1330 R: Clone + Serialize,
1331 E: Serialize,
1332{
1333 Widget::Scaffold {
1334 title: title.into(),
1335 body: Box::new(body),
1336 tabs,
1337 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1338 dark_mode,
1339 theme: None,
1340 fab: None,
1341 sheet: None,
1342 on_refresh: None,
1343 refreshing: false,
1344 route: nav.route_key(),
1345 depth: nav.depth(),
1346 labels: None,
1347 appearance: None,
1348 bottom_bar: None,
1349 }
1350}
1351
1352pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1356 match widget {
1357 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1358 title,
1359 body,
1360 tabs,
1361 back,
1362 dark_mode,
1363 theme: Some(theme),
1364 fab,
1365 sheet,
1366 on_refresh,
1367 refreshing,
1368 route,
1369 depth,
1370 labels,
1371 appearance,
1372 bottom_bar,
1373 },
1374 other => other,
1375 }
1376}
1377
1378pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1381 set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1382}
1383
1384pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1388 set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1389}
1390
1391#[must_use]
1399pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1400 match widget {
1401 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, .. } => {
1402 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children) }
1403 }
1404 other => other,
1405 }
1406}
1407
1408fn set_fab(widget: Widget, fab: Fab) -> Widget {
1409 match widget {
1410 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1411 title,
1412 body,
1413 tabs,
1414 back,
1415 dark_mode,
1416 theme,
1417 fab: Some(fab),
1418 sheet,
1419 on_refresh,
1420 refreshing,
1421 route,
1422 depth,
1423 labels,
1424 appearance,
1425 bottom_bar,
1426 },
1427 other => other,
1428 }
1429}
1430
1431pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1434 match widget {
1435 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1436 title: t,
1437 body,
1438 tabs,
1439 back,
1440 dark_mode,
1441 theme,
1442 fab,
1443 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1444 on_refresh,
1445 refreshing,
1446 route,
1447 depth,
1448 labels,
1449 appearance,
1450 bottom_bar,
1451 },
1452 other => other,
1453 }
1454}
1455
1456pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1460 match widget {
1461 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1462 title,
1463 body,
1464 tabs,
1465 back,
1466 dark_mode,
1467 theme,
1468 fab,
1469 sheet,
1470 on_refresh: Some(tok(on_refresh)),
1471 refreshing,
1472 route,
1473 depth,
1474 labels,
1475 appearance,
1476 bottom_bar,
1477 },
1478 Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1481 children,
1482 on_load_more,
1483 loading,
1484 has_more,
1485 on_refresh: Some(tok(on_refresh)),
1486 refreshing,
1487 end_label,
1488 fill,
1489 },
1490 other => other,
1491 }
1492}
1493
1494#[must_use]
1499pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1500 match widget {
1501 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, .. } => {
1502 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar }
1503 }
1504 other => other,
1505 }
1506}
1507
1508#[must_use]
1516pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1517 match widget {
1518 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, .. } => {
1519 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar }
1520 }
1521 other => other,
1522 }
1523}
1524
1525#[must_use]
1531pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1532 Widget::LazyList {
1533 children,
1534 on_load_more: Some(tok(on_load_more)),
1535 loading,
1536 has_more,
1537 on_refresh: None,
1538 refreshing: false,
1539 end_label: None,
1540 fill: false,
1541 }
1542}
1543
1544#[must_use]
1546pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1547 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1548}
1549
1550#[must_use]
1554pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1555 match widget {
1556 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1557 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1558 }
1559 other => other,
1560 }
1561}
1562
1563#[must_use]
1568pub fn with_fill(widget: Widget) -> Widget {
1569 match widget {
1570 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1571 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1572 }
1573 other => other,
1574 }
1575}
1576
1577#[cfg(test)]
1578mod tests {
1579 use super::*;
1580 use serde::Serialize;
1581
1582 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1583 enum Route {
1584 Home,
1585 Detail(u32),
1586 }
1587
1588 #[derive(Serialize)]
1589 enum Ev {
1590 Tap,
1591 Open(u32),
1592 }
1593
1594 #[test]
1597 fn plugin_response_carries_bytes_and_converts_text() {
1598 let r = PluginResponse::text(true, "hello");
1599 assert!(r.ok);
1600 assert_eq!(r.output, b"hello".to_vec());
1601 assert_eq!(r.as_text(), Some("hello"));
1602
1603 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1604 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1605 }
1606
1607 #[test]
1610 fn nav_push_pop_depth() {
1611 let mut nav = Nav::new(Route::Home);
1612 assert_eq!(nav.depth(), 1);
1613 assert!(!nav.can_go_back());
1614
1615 nav.push(Route::Detail(7));
1616 assert_eq!(nav.depth(), 2);
1617 assert!(nav.can_go_back());
1618 assert!(matches!(nav.current(), Route::Detail(7)));
1619
1620 nav.pop();
1621 assert_eq!(nav.depth(), 1);
1622 assert!(matches!(nav.current(), Route::Home));
1623
1624 nav.pop(); assert_eq!(nav.depth(), 1);
1626 }
1627
1628 #[test]
1629 fn nav_reset_replaces_stack() {
1630 let mut nav = Nav::new(Route::Home);
1631 nav.push(Route::Detail(1));
1632 nav.push(Route::Detail(2));
1633 nav.reset(Route::Detail(9));
1634 assert_eq!(nav.depth(), 1);
1635 assert!(matches!(nav.current(), Route::Detail(9)));
1636 }
1637
1638 #[test]
1639 fn nav_route_key_is_serialization() {
1640 let nav = Nav::new(Route::Detail(3));
1641 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1642 }
1643
1644 #[test]
1647 fn scaffold_sets_route_depth_and_no_back() {
1648 match scaffold("Home", false, vec![], text("x")) {
1649 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1650 assert_eq!(route, "Home");
1651 assert_eq!(depth, 1);
1652 assert!(back.is_none());
1653 assert!(!dark_mode);
1654 }
1655 other => panic!("expected Scaffold, got {other:?}"),
1656 }
1657 }
1658
1659 #[test]
1660 fn scaffold_back_is_depth_2_with_back() {
1661 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1662 Widget::Scaffold { depth, back, dark_mode, .. } => {
1663 assert_eq!(depth, 2);
1664 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1665 assert!(dark_mode);
1666 }
1667 other => panic!("expected Scaffold, got {other:?}"),
1668 }
1669 }
1670
1671 #[test]
1672 fn nav_scaffold_shows_back_only_when_poppable() {
1673 let mut nav = Nav::new(Route::Home);
1674 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1676 Widget::Scaffold { back, depth, route, .. } => {
1677 assert!(back.is_none());
1678 assert_eq!(depth, 1);
1679 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1680 }
1681 other => panic!("expected Scaffold, got {other:?}"),
1682 }
1683 nav.push(Route::Detail(2));
1685 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1686 Widget::Scaffold { back, depth, .. } => {
1687 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1688 assert_eq!(depth, 2);
1689 }
1690 other => panic!("expected Scaffold, got {other:?}"),
1691 }
1692 }
1693
1694 #[test]
1695 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1696 let l = ShellLabels::new().back("Nazad").ok("U redu");
1697 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1698 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1699 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1700 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1702 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1703 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1704 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1705 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1706 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1707 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1708 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1709 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1711 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1713 let nav = Nav::new(Route::Home);
1715 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1716 }
1717
1718 #[test]
1719 fn button_with_carries_tone_icon_and_width() {
1720 assert!(matches!(
1721 button("Go", ButtonStyle::Filled, Ev::Tap),
1722 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1723 ));
1724 assert!(matches!(
1725 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1726 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1727 ));
1728 }
1729
1730 #[test]
1731 fn buttons_carry_serialized_event_tokens() {
1732 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1733 Widget::Button { label, on_press, .. } => {
1734 assert_eq!(label, "Go");
1735 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1736 }
1737 other => panic!("expected Button, got {other:?}"),
1738 }
1739 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1740 Widget::Card { on_press, .. } => {
1741 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1742 }
1743 other => panic!("expected Card, got {other:?}"),
1744 }
1745 match card(text("c"), CardStyle::Elevated) {
1747 Widget::Card { on_press, on_long_press, .. } => {
1748 assert!(on_press.is_none());
1749 assert!(on_long_press.is_none());
1750 }
1751 other => panic!("expected Card, got {other:?}"),
1752 }
1753 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1755 Widget::Card { on_press, on_long_press, .. } => {
1756 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1757 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1758 }
1759 other => panic!("expected Card, got {other:?}"),
1760 }
1761 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1763 }
1764
1765 #[test]
1768 fn cx_notify_and_save_enqueue_notifications() {
1769 let mut cx = Cx::<Ev>::default();
1770 cx.notify("toast", "show", "hi");
1771 cx.save("blob");
1772 assert_eq!(cx.notifications.len(), 2);
1773 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1774 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1775 assert!(cx.requests.is_empty());
1776 }
1777
1778 #[test]
1779 fn cx_http_helpers_build_requests() {
1780 let mut cx = Cx::<Ev>::default();
1781 cx.get("http://h/x", |_| Ev::Tap);
1782 cx.post("http://h/y", "hello", |_| Ev::Tap);
1783 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1784 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1785 cx.delete("http://h/d", |_| Ev::Tap);
1786
1787 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1788 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1789 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1790
1791 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1792 assert_eq!(get_input["url"], "http://h/x");
1793 assert!(get_input["body"].is_null());
1794
1795 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1796 assert_eq!(put_input["url"], "http://h/p");
1797 assert_eq!(put_input["body"], "putbody");
1798 }
1799
1800 #[test]
1801 fn request_builder_emits_headers_in_order() {
1802 let mut cx = Cx::<Ev>::default();
1803 cx.request("PUT", "http://h/access-key")
1804 .bearer("tok123")
1805 .header("X-Trace-Id", "abc")
1806 .body("{}")
1807 .send(|_| Ev::Tap);
1808
1809 assert_eq!(cx.requests.len(), 1);
1810 let (call, _) = &cx.requests[0];
1811 assert_eq!(call.plugin, "http");
1812 assert_eq!(call.op, "PUT");
1813
1814 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1815 assert_eq!(input["url"], "http://h/access-key");
1816 assert_eq!(input["body"], "{}");
1817 assert_eq!(input["headers"][0]["name"], "Authorization");
1818 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1819 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1820 assert_eq!(input["headers"][1]["value"], "abc");
1821 }
1822
1823 #[test]
1824 fn helpers_emit_no_headers_field_content() {
1825 let mut cx = Cx::<Ev>::default();
1826 cx.get("http://h/x", |_| Ev::Tap);
1827 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1828 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1829 }
1830
1831 #[test]
1832 fn continuation_receives_decoded_outcome() {
1833 #[derive(Debug, PartialEq)]
1834 enum Got { Conflict, Offline, Other }
1835
1836 let classify = |r: PluginResponse| -> Got {
1837 match HttpOutcome::decode(&r.output).unwrap() {
1838 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1839 HttpOutcome::TransportError { .. } => Got::Offline,
1840 _ => Got::Other,
1841 }
1842 };
1843
1844 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1845 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1846
1847 let offline = HttpOutcome::TransportError { message: "refused".into() };
1848 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1849 }
1850
1851 #[test]
1852 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1853 let mut cx = Cx::<Ev>::default();
1858
1859 cx.request("GET", "http://h/x").send(|outcome| {
1860 match outcome {
1861 HttpOutcome::TransportError { message } => {
1862 assert!(
1863 message.contains("malformed http response"),
1864 "unexpected message: {message}"
1865 );
1866 }
1867 HttpOutcome::Response { .. } => {
1868 panic!("garbage bytes must not decode as a Response")
1869 }
1870 }
1871 Ev::Tap
1872 });
1873
1874 assert_eq!(cx.requests.len(), 1);
1875 let (_, continuation) = cx.requests.remove(0);
1876 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1879 }
1880
1881 #[test]
1882 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1883 let mut cx = Cx::<Ev>::default();
1884 cx.pick_photo(|_| Ev::Tap);
1885 cx.capture_photo(|_| Ev::Tap);
1886 assert_eq!(cx.requests.len(), 2);
1887 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", ""));
1890 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", ""));
1891 }
1892
1893 #[test]
1894 fn cx_capture_photo_routes_success_and_cancel() {
1895 let mut cx = Cx::<Ev>::default();
1897 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1898 let (_, then) = cx.requests.pop().unwrap();
1899 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1900
1901 let mut cx = Cx::<Ev>::default();
1903 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1904 let (_, then) = cx.requests.pop().unwrap();
1905 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1906 }
1907
1908 #[test]
1909 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1910 let mut cx = Cx::<Ev>::default();
1911 cx.copy("c");
1912 cx.share("s");
1913 cx.open_url("u");
1914 cx.toast("t");
1915 cx.haptic("heavy");
1916 let got: Vec<(&str, &str, &str)> = cx
1917 .notifications
1918 .iter()
1919 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1920 .collect();
1921 assert_eq!(
1922 got,
1923 vec![
1924 ("clipboard", "copy", "c"),
1925 ("share", "text", "s"),
1926 ("browser", "open", "u"),
1927 ("toast", "show", "t"),
1928 ("haptics", "heavy", ""), ]
1930 );
1931 assert!(cx.requests.is_empty());
1932 }
1933
1934 #[test]
1935 fn display_and_headline_builders() {
1936 assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
1937 assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
1938 let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
1939 }
1940
1941 #[test]
1942 fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
1943 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
1944 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
1945 assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
1946 assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
1947 }
1948
1949 #[test]
1950 fn with_theme_and_labels_keep_the_appearance() {
1951 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
1952 let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
1953 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
1954 }
1955
1956 #[test]
1957 fn appearance_query_and_stream_shapes() {
1958 let mut cx = Cx::<Ev>::default();
1959 cx.system_appearance(|_| Ev::Tap);
1960 let (call, _) = &cx.requests[0];
1961 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
1962 cx.subscribe_appearance("appr", |_| Ev::Tap);
1963 let (st, _) = &cx.streams[0];
1964 assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
1965 }
1966
1967 #[test]
1968 fn photo_with_calls_send_options_on_the_same_plugin() {
1969 let mut cx = Cx::<Ev>::default();
1970 cx.pick_photo_with(PhotoOptions::new().jpeg(), |_| Ev::Tap);
1971 cx.capture_photo_with(PhotoOptions::new(), |_| Ev::Tap);
1972 let (p, _) = &cx.requests[0];
1973 assert_eq!((p.plugin.as_str(), p.op.as_str(), p.input.as_str()), ("photo", "pick", r#"{"format":"jpeg"}"#));
1974 let (c, _) = &cx.requests[1];
1975 assert_eq!((c.plugin.as_str(), c.op.as_str(), c.input.as_str()), ("camera", "capture", "{}"));
1976 }
1977
1978 #[test]
1979 fn device_info_is_the_device_info_op() {
1980 let mut cx = Cx::<Ev>::default();
1981 cx.device_info(|_| Ev::Tap);
1982 let (call, _) = &cx.requests[0];
1983 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "info", ""));
1984 }
1985
1986 #[test]
1987 fn cx_device_model_is_a_request_not_a_notification() {
1988 let mut cx = Cx::<Ev>::default();
1989 cx.device_model(|_| Ev::Tap);
1990 assert!(cx.notifications.is_empty());
1991 assert_eq!(cx.requests.len(), 1);
1992 let (call, _) = &cx.requests[0];
1993 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1994 }
1995
1996 #[test]
1997 fn cx_device_locale_requests_the_device_locale_op() {
1998 let mut cx = Cx::<Ev>::default();
1999 cx.device_locale(|_| Ev::Tap);
2000 assert!(cx.notifications.is_empty());
2001 assert_eq!(cx.requests.len(), 1);
2002 let (call, _) = &cx.requests[0];
2003 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
2004 }
2005
2006 #[test]
2007 fn cx_now_requests_the_datetime_now_op() {
2008 let mut cx = Cx::<Ev>::default();
2009 cx.now(|_| Ev::Tap);
2010 assert_eq!(cx.requests.len(), 1);
2011 let (call, _) = &cx.requests[0];
2012 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
2013 }
2014
2015 #[test]
2016 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
2017 let mut cx = Cx::<Ev>::default();
2018 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2019 assert!(cx.notifications.is_empty());
2021 assert!(cx.requests.is_empty());
2022 assert_eq!(cx.streams.len(), 1);
2023 let (call, on_event) = &cx.streams[0];
2024 assert_eq!(
2025 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
2026 ("ws", "websocket", "stream", "wss://h/x")
2027 );
2028 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
2030 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
2031 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
2032 }
2033
2034 #[test]
2035 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
2036 let mut cx = Cx::<Ev>::default();
2037 cx.unsubscribe("ws");
2038 assert!(cx.streams.is_empty());
2039 assert_eq!(cx.notifications.len(), 1);
2040 assert_eq!(
2042 cx.notifications[0],
2043 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
2044 );
2045 }
2046
2047 #[test]
2048 fn cx_confirm_serializes_title_message_and_routes_ok() {
2049 let mut cx = Cx::<Ev>::default();
2050 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2051 let (call, then) = cx.requests.pop().unwrap();
2052 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2053 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2054 assert_eq!(v["title"], "Delete?");
2055 assert_eq!(v["message"], "This cannot be undone.");
2056 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2058 }
2059
2060 #[test]
2061 fn cx_confirm_stays_byte_identical_on_the_wire() {
2062 let mut cx = Cx::<Ev>::default();
2063 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2064 let (call, _) = cx.requests.pop().unwrap();
2065 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2066 }
2067
2068 #[test]
2069 fn cx_confirm_with_sends_labels_and_destructive() {
2070 let mut cx = Cx::<Ev>::default();
2071 cx.confirm_with(
2072 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2073 .confirm_label("Otkaži termin")
2074 .cancel_label("Ne, vrati se")
2075 .destructive(),
2076 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2077 );
2078 let (call, then) = cx.requests.pop().unwrap();
2079 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2080 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2081 assert_eq!(v["title"], "Otkazati termin?");
2082 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2083 assert_eq!(v["confirm_label"], "Otkaži termin");
2084 assert_eq!(v["cancel_label"], "Ne, vrati se");
2085 assert_eq!(v["destructive"], true);
2086 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2087 let mut cx = Cx::<Ev>::default();
2089 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2090 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2091 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2092 }
2093
2094 #[test]
2095 fn with_step_caption_turns_the_caption_on() {
2096 assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2097 assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2098 assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2099 }
2100
2101 #[test]
2102 fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2103 let mut cx = Cx::<Ev>::default();
2104 cx.open_url("https://x");
2105 assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2106 cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2107 let (call, then) = cx.requests.pop().unwrap();
2108 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2109 assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2110 }
2111
2112 #[test]
2113 fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2114 let bar = vec![text("A"), text("B")];
2115 let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2116 assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2117 assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2118 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2119 let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2120 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2121 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2122 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2123 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2124 assert!(keep(with_theme(s.clone(), Theme::default())));
2125 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2126 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2127 }
2128
2129 #[test]
2130 fn steps_builder_clamps_and_step_text_fills_the_template() {
2131 assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2132 assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2133 assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2134 assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2135 assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2136 assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2137 }
2138
2139 #[test]
2140 fn with_columns_sets_clamps_and_ignores_other_widgets() {
2141 assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2142 assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2143 assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2144 assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2145 assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2146 }
2147
2148 #[test]
2149 fn badge_icon_and_avatar_initials_modifiers() {
2150 assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2151 assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2152 let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2153 assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2154 assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2155 assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2157 assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2158 assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2159 }
2160
2161 #[test]
2162 fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2163 let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2164 assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2165 let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2166 assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2167 }
2168
2169 #[test]
2170 fn snackbar_input_is_the_wire_json() {
2171 assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2172 assert_eq!(
2173 Snackbar::new("Cancelled").action("Undo").long().to_input(),
2174 r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2175 );
2176 }
2177
2178 #[test]
2179 fn cx_snackbar_sends_a_snackbar_show_request() {
2180 let mut cx = Cx::<Ev>::default();
2181 cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2182 let (call, then) = cx.requests.pop().unwrap();
2183 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2184 assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2185 assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2186 }
2187
2188 #[test]
2189 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2190 let mut cx = Cx::<Ev>::default();
2191 cx.pick_date(|_| Ev::Tap);
2192 cx.pick_time(|_| Ev::Tap);
2193 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2194
2195 let mut cx = Cx::<Ev>::default();
2196 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2197 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2198 let (date, _) = &cx.requests[0];
2199 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2200 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2201 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2202 let (time, _) = &cx.requests[1];
2203 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2204 }
2205
2206 #[test]
2209 fn text_builders_carry_their_style() {
2210 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2211 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2212 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2213 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2214 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2215 }
2216
2217 #[test]
2218 fn layout_and_content_builders_produce_their_variants() {
2219 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2220 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2221 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2222 assert!(matches!(divider(), Widget::Divider));
2223 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2224 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2225 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2226 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)));
2227 let rc = with_bracket(
2228 region_chart(
2229 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2230 vec![ChartTick::new(3.0, "3 Mt.")],
2231 65.0, 80.0,
2232 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2233 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2234 ),
2235 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2236 );
2237 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2238 assert!(matches!(
2240 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2241 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2242 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2243 ));
2244 assert!(matches!(
2245 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2246 Widget::SwipeAction { actions, .. } if actions.len() == 1
2247 ));
2248 assert!(matches!(
2250 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2251 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2252 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2253 ));
2254 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2255 assert!(matches!(
2257 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2258 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2259 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2260 ));
2261 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2263 assert!(matches!(
2264 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2265 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2266 ));
2267 assert!(matches!(
2269 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2270 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2271 ));
2272 assert!(matches!(
2273 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2274 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2275 ));
2276 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2278 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2279 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2280 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2281 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2282 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2283 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2285 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2287 Widget::Split { show_detail: true, on_back: Some(_), .. }));
2288 }
2289
2290 #[test]
2291 fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2292 assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2293 assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2294 let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2295 assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2296 let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2298 assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2299 assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2300 assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2301 }
2302
2303 #[test]
2304 fn input_builders_carry_ids_values_and_event_tokens() {
2305 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2306 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2307 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2308 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2310 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2311 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2312 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2313 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2315 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2316 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2317 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2318 with_captions(video_player("v", "u", true, -1, Ev::Tap),
2319 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2320 "p.jpg"), 9000), 1.5), 0.5));
2321 assert!(matches!(tuned,
2322 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2323 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2324 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2326 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2327 assert!(matches!(with_pip(divider()), Widget::Divider));
2329 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2330 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2331 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2332 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2333 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2334 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2335 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2336 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2337
2338 match chip("Latte", true, Ev::Open(2)) {
2339 Widget::Chip { selected, on_press, .. } => {
2340 assert!(selected);
2341 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2342 }
2343 other => panic!("expected Chip, got {other:?}"),
2344 }
2345 match stepper(5, Ev::Tap, Ev::Open(1)) {
2346 Widget::Stepper { value, on_decrement, on_increment } => {
2347 assert_eq!(value, 5);
2348 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2349 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2350 }
2351 other => panic!("expected Stepper, got {other:?}"),
2352 }
2353 let t = tab("Home", true, Ev::Tap);
2354 assert_eq!(t.label, "Home");
2355 assert!(t.selected);
2356 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2357 }
2358
2359 #[test]
2362 fn widget_tree_round_trips_through_serde() {
2363 let tree = scaffold(
2364 "Home",
2365 true,
2366 vec![tab("A", true, Ev::Tap)],
2367 column(vec![
2368 title("Hi"),
2369 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2370 image("u", ImageShape::Rounded, ImageRatio::Wide),
2371 slider("s", 2, 5),
2372 ]),
2373 );
2374 let s = serde_json::to_string(&tree).unwrap();
2375 let back: Widget = serde_json::from_str(&s).unwrap();
2376 assert_eq!(s, serde_json::to_string(&back).unwrap());
2377 }
2378
2379 #[test]
2380 fn actions_and_input_values_round_trip() {
2381 let actions = vec![
2382 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2383 Action::Input { id: "n".into(), value: InputValue::Int(7) },
2384 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2385 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2386 Action::Restore { data: "blob".into() },
2387 Action::Start,
2388 Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2389 ];
2390 for a in actions {
2391 let s = serde_json::to_string(&a).unwrap();
2392 let back: Action = serde_json::from_str(&s).unwrap();
2393 assert_eq!(s, serde_json::to_string(&back).unwrap());
2394 }
2395 }
2396
2397 #[derive(Default)]
2400 struct CounterModel {
2401 count: i32,
2402 restored: String,
2403 started: bool,
2404 last_input: String,
2405 app_build: String,
2406 }
2407
2408 #[derive(serde::Serialize, serde::Deserialize)]
2409 enum CounterEv {
2410 Inc,
2411 Add(i32),
2412 }
2413
2414 #[derive(Default)]
2415 struct CounterApp;
2416
2417 impl MobilerApp for CounterApp {
2418 type Event = CounterEv;
2419 type Model = CounterModel;
2420 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2421 match ev {
2422 CounterEv::Inc => model.count += 1,
2423 CounterEv::Add(n) => model.count += n,
2424 }
2425 }
2426 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2427 if let InputValue::Text(t) = value {
2428 model.last_input = format!("{id}={t}");
2429 }
2430 }
2431 fn restore(&self, data: &str, model: &mut CounterModel) {
2432 model.restored = data.to_string();
2433 }
2434 fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2435 model.started = true;
2436 model.app_build = cx.app_info().build.clone();
2437 }
2438 fn view(&self, model: &CounterModel) -> Widget {
2439 text(format!("{}", model.count))
2440 }
2441 }
2442
2443 #[test]
2444 fn shell_dispatches_fired_input_restore_and_start() {
2445 use crux_core::App as _;
2446 let shell = MobilerShell::<CounterApp>::default();
2447 let mut m = CounterModel::default();
2448
2449 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2451 assert_eq!(m.count, 5);
2452 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2454 assert_eq!(m.last_input, "name=bob");
2455 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2457 assert_eq!(m.restored, "saved");
2458 let _ = shell.update(Action::Start, &mut m);
2460 assert!(m.started);
2461 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2463 }
2464
2465 fn info(build: &str) -> AppInfo {
2466 AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2467 }
2468
2469 fn app_info_action(build: &str) -> Action {
2470 let i = info(build);
2471 Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2472 }
2473
2474 static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2477
2478 #[test]
2479 fn init_sees_app_info_sent_before_start() {
2480 use crux_core::App as _;
2481 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2482 let shell = MobilerShell::<CounterApp>::default();
2483 let mut m = CounterModel::default();
2484 let _ = shell.update(app_info_action("7"), &mut m);
2485 let _ = shell.update(Action::Start, &mut m);
2486 assert_eq!(m.app_build, "7");
2487 }
2488
2489 #[test]
2490 fn later_app_info_replaces_earlier() {
2491 use crux_core::App as _;
2492 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2493 let shell = MobilerShell::<CounterApp>::default();
2494 let mut m = CounterModel::default();
2495 let _ = shell.update(app_info_action("7"), &mut m);
2496 let _ = shell.update(app_info_action("8"), &mut m);
2497 let _ = shell.update(Action::Start, &mut m);
2498 assert_eq!(m.app_build, "8");
2499 }
2500
2501 #[test]
2502 fn app_info_action_does_not_touch_the_model() {
2503 use crux_core::App as _;
2504 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2505 let shell = MobilerShell::<CounterApp>::default();
2506 let mut m = CounterModel::default();
2507 let _ = shell.update(app_info_action("9"), &mut m);
2508 assert!(!m.started);
2509 assert_eq!(m.count, 0);
2510 assert!(m.restored.is_empty());
2511 assert!(m.last_input.is_empty());
2512 assert!(m.app_build.is_empty());
2513 }
2514
2515 #[test]
2516 fn cx_default_has_empty_app_info() {
2517 let cx = Cx::<Ev>::default();
2518 assert_eq!(cx.app_info(), &AppInfo::default());
2519 assert!(cx.app_info().platform.is_empty());
2520 }
2521
2522 #[test]
2523 fn cx_with_app_info_carries_it() {
2524 let cx = Cx::<Ev>::with_app_info(info("42"));
2525 assert_eq!(cx.app_info().build, "42");
2526 assert_eq!(cx.app_info().bundle_id, "rs.x");
2527 }
2528
2529 #[test]
2530 fn shell_ignores_a_malformed_fired_token() {
2531 use crux_core::App as _;
2532 let shell = MobilerShell::<CounterApp>::default();
2533 let mut m = CounterModel::default();
2534 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2537 assert_eq!(m.count, 0);
2538 }
2539
2540 #[derive(Default)]
2543 struct EffectsApp;
2544
2545 impl MobilerApp for EffectsApp {
2546 type Event = CounterEv;
2547 type Model = CounterModel;
2548 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2549 model.count += 1;
2550 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2551 cx.notify("toast", "show", "hi");
2552 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2553 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2554 }
2555 fn view(&self, model: &CounterModel) -> Widget {
2556 text(format!("{}", model.count))
2557 }
2558 }
2559
2560 #[test]
2561 fn shell_renders_before_requests_notifications_and_streams() {
2562 use crux_core::App as _;
2563 let shell = MobilerShell::<EffectsApp>::default();
2564 let mut m = CounterModel::default();
2565 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2566 let kinds: Vec<String> = cmd
2567 .effects()
2568 .map(|e| match e {
2569 Effect::Render(_) => "render".to_string(),
2570 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2571 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2572 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2573 })
2574 .collect();
2575 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2578 }
2579
2580 #[test]
2583 fn upload_builder_emits_transfer_stream_call() {
2584 let mut cx = Cx::<Ev>::default();
2585 let key = cx
2586 .upload("https://h/put", "file:///tmp/a.enc")
2587 .bearer("tok")
2588 .header("Content-Type", "application/octet-stream")
2589 .start("up-1", |_ev| Ev::Tap);
2590
2591 assert_eq!(key, "up-1");
2592 assert_eq!(cx.streams.len(), 1);
2593 let (call, _) = &cx.streams[0];
2594 assert_eq!(call.key, "up-1");
2595 assert_eq!(call.plugin, "transfer");
2596 assert_eq!(call.op, "upload");
2597
2598 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2599 assert_eq!(v["url"], "https://h/put");
2600 assert_eq!(v["source"], "file:///tmp/a.enc");
2601 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2603 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2604 assert_eq!(v["headers"][1]["name"], "Content-Type");
2605 }
2606
2607 #[test]
2608 fn download_builder_uses_dest_and_no_default_method() {
2609 let mut cx = Cx::<Ev>::default();
2610 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2611 let (call, _) = &cx.streams[0];
2612 assert_eq!(call.op, "download");
2613 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2614 assert_eq!(v["dest"], "/data/att-9.enc");
2615 assert!(v.get("source").is_none());
2616 }
2617
2618 #[test]
2619 fn start_continuation_decodes_progress_and_done() {
2620 use crate::http::HttpOutcome;
2621
2622 #[derive(Debug, PartialEq)]
2625 enum Got {
2626 Prog(u64),
2627 Done(u16),
2628 Bad,
2629 }
2630 #[derive(Debug, PartialEq)]
2631 struct GotEv(Got);
2632
2633 let mut cx = Cx::<GotEv>::default();
2634 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2635 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2636 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2637 Some(s) => Got::Done(s),
2638 None => Got::Bad,
2639 }),
2640 });
2641 let (_, cont) = &cx.streams[0];
2642
2643 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2644 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2645
2646 let done = TransferEvent::Done {
2647 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2648 handle: Some("/d".into()),
2649 };
2650 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2651 }
2652
2653 #[test]
2654 fn calendar_in_localizes_layout_and_clamps_markers() {
2655 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2657 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2658 assert_eq!(title, "Septembar 2026");
2659 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2660 assert_eq!(leading_blanks, 1);
2661 assert_eq!(on_day.len(), 30);
2662 assert_eq!(markers.len(), 30, "padded to one level per day");
2663 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2664 assert!(matches!(
2666 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2667 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2668 ));
2669 }
2670
2671 #[test]
2672 fn scroller_hint_is_opt_in() {
2673 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2674 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2675 }
2676}