1use std::marker::PhantomData;
9
10pub mod app_info;
11pub mod bunny;
12pub mod clipboard;
13pub mod device;
14pub mod photo;
15pub mod dialog;
16pub mod format;
17pub mod http;
18pub mod i18n;
19pub mod transfer;
20pub use app_info::AppInfo;
21pub use clipboard::{CopyApplied, CopyExpiry, CopyOptions};
22pub use device::DeviceInfo;
23pub use photo::{Photo, PhotoError, PhotoFormat, PhotoOptions};
24pub use dialog::{Confirm, Picker, Snackbar, SnackbarDuration};
25pub use format::{Currency, Locale, Weekday};
26pub use http::{HttpHeader, HttpOutcome};
27pub use i18n::{Catalog, negotiate};
28pub use transfer::TransferEvent;
29
30use crux_core::{
31 App, Command,
32 capability::Operation,
33 macros::effect,
34 render::{RenderOperation, render},
35};
36use facet::Facet;
37use serde::{Deserialize, Serialize, de::DeserializeOwned};
38
39pub use mobiler_ui::{
40 A11yRole, Action, Appearance, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
41 ChartSeries, ChartStyle, ChartTick, ColorRoles, Corner, FamilyRole, Density, Fab, FieldKind, FontFamily, Icon,
42 ImageRatio, ImageShape, InputValue, MapMarker, Palette, ProjectColor, Radius, Rgb, Rgba, Segment, Shapes, Sheet, ShellLabels, Spacing, SwipeButton, Tab, TabBadge,
43 TextStyle, Theme, Tone, TonePair, TypeScale, TypeSpec, Widget,
44};
45
46#[effect(facet_typegen)]
50#[derive(Debug)]
51pub enum Effect {
52 Render(RenderOperation),
53 PluginNotify(PluginNotify),
55 Plugin(PluginCall),
57 PluginStream(PluginStreamCall),
62}
63
64#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
65pub struct PluginNotify {
66 pub plugin: String,
67 pub op: String,
68 pub input: String,
69}
70impl Operation for PluginNotify {
71 type Output = ();
72}
73
74#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
75pub struct PluginCall {
76 pub plugin: String,
77 pub op: String,
78 pub input: String,
79}
80impl Operation for PluginCall {
81 type Output = PluginResponse;
82}
83
84#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
88pub struct PluginStreamCall {
89 pub key: String,
90 pub plugin: String,
91 pub op: String,
92 pub input: String,
93}
94impl Operation for PluginStreamCall {
95 type Output = PluginResponse;
96}
97
98#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
107pub struct PluginResponse {
108 pub ok: bool,
109 pub output: Vec<u8>,
110}
111
112impl PluginResponse {
113 pub fn text(ok: bool, s: impl Into<String>) -> Self {
115 Self { ok, output: s.into().into_bytes() }
116 }
117
118 pub fn as_text(&self) -> Option<&str> {
120 std::str::from_utf8(&self.output).ok()
121 }
122}
123
124type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
125type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
127
128pub struct Cx<E> {
131 notifications: Vec<PluginNotify>,
132 requests: Vec<(PluginCall, Continuation<E>)>,
133 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
134 app_info: AppInfo,
135}
136
137impl<E> Default for Cx<E> {
138 fn default() -> Self {
139 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new(), app_info: AppInfo::default() }
140 }
141}
142
143impl<E> Cx<E> {
144 #[must_use]
146 pub fn with_app_info(info: AppInfo) -> Self {
147 Self { app_info: info, ..Self::default() }
148 }
149
150 #[must_use]
155 pub fn app_info(&self) -> &AppInfo {
156 &self.app_info
157 }
158
159 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
161 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
162 }
163
164 pub fn plugin(
167 &mut self,
168 plugin: impl Into<String>,
169 op: impl Into<String>,
170 input: impl Into<String>,
171 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
172 ) {
173 self.requests
174 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
175 }
176
177 pub fn subscribe(
185 &mut self,
186 key: impl Into<String>,
187 plugin: impl Into<String>,
188 op: impl Into<String>,
189 input: impl Into<String>,
190 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
191 ) {
192 self.streams.push((
193 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
194 Box::new(on_event),
195 ));
196 }
197
198 pub fn unsubscribe(&mut self, key: impl Into<String>) {
202 self.notify("stream", "unsubscribe", key);
203 }
204
205 pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
210 crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
211 }
212
213 pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
216 crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
217 }
218
219 pub fn save(&mut self, data: impl Into<String>) {
225 self.notify("storage", "save", data);
226 }
227
228 pub fn copy(&mut self, text: impl Into<String>) {
230 self.notify("clipboard", "copy", text);
231 }
232
233 pub fn copy_with(&mut self, text: impl Into<String>, options: CopyOptions, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
241 let input = options.to_input(&text.into());
242 self.plugin("clipboard_with", "copy", input, then);
243 }
244
245 pub fn copy_sensitive(&mut self, text: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
249 self.copy_with(text, CopyOptions::sensitive(), then);
250 }
251
252 pub fn share(&mut self, text: impl Into<String>) {
254 self.notify("share", "text", text);
255 }
256
257 pub fn open_url(&mut self, url: impl Into<String>) {
260 self.notify("browser", "open", url);
261 }
262
263 pub fn open_url_then(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
270 self.plugin("browser", "open", url, then);
271 }
272
273 pub fn toast(&mut self, text: impl Into<String>) {
275 self.notify("toast", "show", text);
276 }
277
278 pub fn haptic(&mut self, style: impl Into<String>) {
281 self.notify("haptics", style, "");
282 }
283
284 pub fn request(
299 &mut self,
300 method: impl Into<String>,
301 url: impl Into<String>,
302 ) -> crate::http::RequestBuilder<'_, E> {
303 crate::http::RequestBuilder::new(self, method.into(), url.into())
304 }
305
306 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
308 self.request("GET", url).send(then);
309 }
310 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
312 self.request("POST", url).body(body).send(then);
313 }
314 pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
316 self.request("PUT", url).body(body).send(then);
317 }
318 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
320 self.request("PATCH", url).body(body).send(then);
321 }
322 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
324 self.request("DELETE", url).send(then);
325 }
326
327 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
331 self.plugin("device", "model", "", then);
332 }
333
334 pub fn device_info(&mut self, then: impl FnOnce(Option<DeviceInfo>) -> E + Send + 'static) {
338 self.plugin("device", "info", "", move |r| then(device::from_response(&r)));
339 }
340
341 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
346 self.plugin("device", "locale", "", then);
347 }
348
349 pub fn system_appearance(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
352 self.plugin("device", "appearance", "", then);
353 }
354
355 pub fn subscribe_appearance(&mut self, key: impl Into<String>, on_event: impl Fn(PluginResponse) -> E + Send + 'static) {
358 self.subscribe(key, "appearance", "changes", "", on_event);
359 }
360
361 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
366 self.plugin("photo", "pick", "", then);
367 }
368
369 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
376 self.plugin("camera", "capture", "", then);
377 }
378
379 pub fn pick_photo_with(&mut self, options: PhotoOptions, then: impl FnOnce(Result<Photo, PhotoError>) -> E + Send + 'static) {
385 self.plugin("photo", "pick", options.to_input(), move |r| then(photo::from_response(&r)));
386 }
387
388 pub fn capture_photo_with(&mut self, options: PhotoOptions, then: impl FnOnce(Result<Photo, PhotoError>) -> E + Send + 'static) {
391 self.plugin("camera", "capture", options.to_input(), move |r| then(photo::from_response(&r)));
392 }
393
394 pub fn confirm(
398 &mut self,
399 title: impl Into<String>,
400 message: impl Into<String>,
401 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
402 ) {
403 self.confirm_with(Confirm::new(title, message), then);
404 }
405
406 pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
410 self.plugin("dialog", "confirm", dialog.to_input(), then);
411 }
412
413 pub fn snackbar(&mut self, snackbar: Snackbar, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
419 self.plugin("snackbar", "show", snackbar.to_input(), then);
420 }
421
422 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
427 self.plugin("datetime", "date", "", then);
428 }
429
430 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
435 self.plugin("datetime", "time", "", then);
436 }
437
438 pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
440 self.plugin("datetime", "date", picker.to_input(), then);
441 }
442
443 pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
445 self.plugin("datetime", "time", picker.to_input(), then);
446 }
447
448 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
455 self.plugin("datetime", "now", "", then);
456 }
457}
458
459pub trait MobilerApp: Default {
464 type Event: Serialize + DeserializeOwned + Send + 'static;
465 type Model: Default;
466
467 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
468
469 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
470 let _ = (id, value, model, cx);
471 }
472
473 fn restore(&self, data: &str, model: &mut Self::Model) {
476 let _ = (data, model);
477 }
478
479 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
482 let _ = (model, cx);
483 }
484
485 fn view(&self, model: &Self::Model) -> Widget;
486}
487
488pub struct MobilerShell<A>(PhantomData<fn() -> A>);
490
491impl<A> Default for MobilerShell<A> {
492 fn default() -> Self {
493 Self(PhantomData)
494 }
495}
496
497impl<A: MobilerApp> App for MobilerShell<A> {
498 type Event = Action;
499 type Model = A::Model;
500 type ViewModel = Widget;
501 type Effect = Effect;
502
503 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
504 let app = A::default();
505 let mut cx = Cx::<A::Event>::with_app_info(app_info::get());
506 match action {
507 Action::Fired { token } => {
508 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
509 app.update(event, model, &mut cx);
510 }
511 }
512 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
513 Action::Restore { data } => app.restore(&data, model),
514 Action::Start => app.init(model, &mut cx),
515 Action::AppInfo { version, build, platform, bundle_id } => {
516 app_info::set(AppInfo { version, build, platform, bundle_id });
517 }
518 }
519 let mut commands: Vec<Command<Effect, Action>> = vec![render()];
525 for op in cx.notifications {
526 commands.push(Command::notify_shell(op).build());
527 }
528 for (op, then) in cx.requests {
529 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
530 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
531 }));
532 }
533 for (op, then) in cx.streams {
534 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
537 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
538 }));
539 }
540 Command::all(commands)
541 }
542
543 fn view(&self, model: &Self::Model) -> Widget {
544 A::default().view(model)
545 }
546}
547
548#[derive(Clone, Debug)]
567pub struct Nav<R> {
568 stack: Vec<R>,
569}
570
571impl<R: Clone + Serialize> Nav<R> {
572 #[must_use]
574 pub fn new(root: R) -> Self {
575 Self { stack: vec![root] }
576 }
577 pub fn push(&mut self, route: R) {
579 self.stack.push(route);
580 }
581 pub fn pop(&mut self) {
583 if self.stack.len() > 1 {
584 self.stack.pop();
585 }
586 }
587 pub fn reset(&mut self, root: R) {
589 self.stack = vec![root];
590 }
591 #[must_use]
593 pub fn current(&self) -> &R {
594 self.stack.last().expect("nav stack is never empty")
595 }
596 #[must_use]
598 pub fn depth(&self) -> u32 {
599 self.stack.len() as u32
600 }
601 #[must_use]
603 pub fn can_go_back(&self) -> bool {
604 self.stack.len() > 1
605 }
606 fn route_key(&self) -> String {
609 serde_json::to_string(self.current()).expect("serialize route")
610 }
611}
612
613fn tok<E: Serialize>(event: E) -> String {
617 serde_json::to_string(&event).expect("serialize event")
618}
619
620#[must_use]
621pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
622 Widget::Text { content: content.into(), style }
623}
624#[must_use]
625pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
626#[must_use]
627pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
628#[must_use]
629pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
630#[must_use]
631pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
632#[must_use]
633pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
634#[must_use]
637pub fn display(content: impl Into<String>) -> Widget { styled(content, TextStyle::Display) }
638#[must_use]
640pub fn headline(content: impl Into<String>) -> Widget { styled(content, TextStyle::Headline) }
641
642#[must_use]
643pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
644 Widget::Image { source: source.into(), shape, ratio }
645}
646#[must_use]
647pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
648 Widget::Badge { label: label.into(), tone, icon: None }
649}
650#[must_use]
652pub fn color_dot(color: ProjectColor) -> Widget {
653 Widget::ColorDot { color }
654}
655#[must_use]
656pub fn divider() -> Widget { Widget::Divider }
657#[must_use]
659pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
660#[must_use]
662pub fn skeleton() -> Widget { Widget::Skeleton }
663#[must_use]
667pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
668#[must_use]
677pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
678 Widget::Video {
679 url: url.into(),
680 id: id.into(),
681 playing,
682 seek_to_ms,
683 controls: true,
684 looping: false,
685 muted: false,
686 on_ended: Some(tok(on_ended)),
687 poster: None,
688 start_at_ms: -1,
689 captions: Vec::new(),
690 rate: 1.0,
691 volume: 1.0,
692 urls: Vec::new(),
693 start_index: 0,
694 seek_index: -1,
695 allow_pip: false,
696 }
697}
698#[must_use]
704pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
705 Widget::Video {
706 url: urls.first().cloned().unwrap_or_default(),
707 id: id.into(),
708 playing,
709 seek_to_ms: -1,
710 controls: true,
711 looping: false,
712 muted: false,
713 on_ended: Some(tok(on_ended)),
714 poster: None,
715 start_at_ms: -1,
716 captions: Vec::new(),
717 rate: 1.0,
718 volume: 1.0,
719 urls,
720 start_index,
721 seek_index: -1,
722 allow_pip: false,
723 }
724}
725fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
728 match widget {
729 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
730 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
731 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
732 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
733 f(&mut v);
734 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
735 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
736 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
737 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
738 allow_pip: v.allow_pip }
739 }
740 other => other,
741 }
742}
743struct VideoFields {
744 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
745 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
746 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
747 seek_index: i64, allow_pip: bool,
748}
749#[must_use]
751pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
752#[must_use]
754pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
755#[must_use]
757pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
758#[must_use]
760pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
761 let poster = poster.into();
762 map_video(widget, move |v| v.poster = Some(poster))
763}
764#[must_use]
766pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
767 map_video(widget, move |v| v.start_at_ms = start_at_ms)
768}
769#[must_use]
771pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
772 map_video(widget, move |v| v.captions = captions)
773}
774#[must_use]
776pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
777#[must_use]
779pub fn with_volume(widget: Widget, volume: f32) -> Widget {
780 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
781}
782#[must_use]
784pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
785 map_video(widget, move |v| v.seek_index = index)
786}
787#[must_use]
789pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
790#[must_use]
795pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
796
797#[must_use]
803pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
804 Widget::Map {
805 id: id.into(),
806 center_lat,
807 center_lng,
808 zoom,
809 markers: Vec::new(),
810 style_url: None,
811 interactive: true,
812 }
813}
814#[must_use]
816pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
817 match widget {
818 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
819 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
820 other => other,
821 }
822}
823#[must_use]
825pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
826 match widget {
827 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
828 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
829 other => other,
830 }
831}
832#[must_use]
834pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
835 MapMarker { id: id.into(), lat, lng, title: None }
836}
837#[must_use]
839pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
840 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
841}
842fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
844 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
845}
846
847#[must_use]
850pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
851 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
852}
853#[must_use]
856pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
857 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
858}
859#[must_use]
863pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
864 Widget::Chart { series, labels, style, axis, legend }
865}
866#[must_use]
868pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
869 chart(series, labels, ChartStyle::StackedBar, true, true)
870}
871#[must_use]
873pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
874 chart(series, labels, ChartStyle::StackedBar100, false, true)
875}
876#[must_use]
878pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
879 chart(series, vec![], ChartStyle::Pie, false, true)
880}
881#[must_use]
883pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
884 chart(series, vec![], ChartStyle::Donut, false, true)
885}
886#[must_use]
889pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
890 chart(series, vec![], ChartStyle::Rings, false, true)
891}
892#[must_use]
894pub fn gauge_chart(series: ChartSeries) -> Widget {
895 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
896}
897
898#[must_use]
903pub fn region_chart(
904 regions: Vec<ChartRegion>,
905 ticks: Vec<ChartTick>,
906 x_max: f32,
907 y_max: f32,
908 ref_lines: Vec<ChartRefLine>,
909 legend: Vec<ChartLegendItem>,
910) -> Widget {
911 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
912}
913
914#[must_use]
916pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
917 match widget {
918 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
919 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
920 }
921 other => other,
922 }
923}
924
925fn days_in_month(year: u32, month: u8) -> u8 {
927 match month {
928 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
929 4 | 6 | 9 | 11 => 30,
930 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
931 _ => 30,
932 }
933}
934
935fn weekday(year: u32, month: u8, day: u8) -> u8 {
937 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
938 let y = if month < 3 { year - 1 } else { year };
939 let m = month as usize - 1;
940 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
941}
942
943#[must_use]
947pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
948 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
949}
950
951#[must_use]
956pub fn calendar_in<E: Serialize>(
957 locale: Locale,
958 year: u32,
959 month: u8,
960 selected: Option<u8>,
961 markers: &[u8],
962 on_day: impl Fn(u8) -> E,
963) -> Widget {
964 let n = days_in_month(year, month);
965 let start = locale.week_start().sun0();
966 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
967 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
968 let markers = if markers.is_empty() {
969 Vec::new()
970 } else {
971 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
972 };
973 Widget::Calendar {
974 year,
975 month,
976 title: format::month_year(year, u32::from(month), locale),
977 weekday_labels,
978 leading_blanks,
979 selected,
980 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
981 markers,
982 }
983}
984
985#[must_use]
988pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
989 Widget::SwipeAction {
990 child: Box::new(child),
991 actions: actions
992 .into_iter()
993 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
994 .collect(),
995 }
996}
997#[must_use]
998pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
999
1000#[must_use]
1001pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
1002#[must_use]
1003pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
1004#[must_use]
1005pub fn card(child: Widget, style: CardStyle) -> Widget {
1006 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
1007}
1008#[must_use]
1010pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
1011 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
1012}
1013#[must_use]
1017pub fn with_icon(widget: Widget, icon: Icon) -> Widget {
1018 match widget {
1019 Widget::Badge { label, tone, .. } => Widget::Badge { label, tone, icon: Some(icon) },
1020 other => other,
1021 }
1022}
1023
1024#[must_use]
1028pub fn with_initials(widget: Widget, initials: impl Into<String>) -> Widget {
1029 match widget {
1030 Widget::Avatar { source, status, size, .. } => Widget::Avatar { source, status, initials: Some(initials.into()), size },
1031 other => other,
1032 }
1033}
1034
1035#[must_use]
1038pub fn with_avatar_size(widget: Widget, size: u8) -> Widget {
1039 match widget {
1040 Widget::Avatar { source, status, initials, .. } => Widget::Avatar { source, status, initials, size: Some(size) },
1041 other => other,
1042 }
1043}
1044
1045#[must_use]
1048pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
1049 match widget {
1050 Widget::Card { child, style, on_press, .. } => Widget::Card {
1051 child,
1052 style,
1053 on_press,
1054 on_long_press: Some(tok(on_long_press)),
1055 },
1056 other => other,
1057 }
1058}
1059#[must_use]
1062pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
1063 Widget::Box { children, align, scrim }
1064}
1065#[must_use]
1070pub fn steps(total: u8, current: u8) -> Widget {
1071 Widget::Steps { total, current: current.min(total), caption: false }
1072}
1073
1074#[must_use]
1077pub fn with_step_caption(widget: Widget) -> Widget {
1078 match widget {
1079 Widget::Steps { total, current, .. } => Widget::Steps { total, current, caption: true },
1080 other => other,
1081 }
1082}
1083
1084#[must_use]
1087pub fn step_text(template: Option<&str>, current: u8, total: u8) -> String {
1088 let t = template.filter(|t| !t.is_empty()).unwrap_or("Step {current} of {total}");
1089 t.replace("{current}", ¤t.to_string()).replace("{total}", &total.to_string())
1090}
1091
1092#[must_use]
1093pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children, columns: None } }
1094#[must_use]
1097pub fn with_columns(widget: Widget, columns: u8) -> Widget {
1098 match widget {
1099 Widget::Grid { children, .. } => Widget::Grid { children, columns: Some(columns.clamp(1, 4)) },
1100 other => other,
1101 }
1102}
1103#[must_use]
1108pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
1109 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
1110}
1111#[must_use]
1113pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
1114#[must_use]
1116pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
1117#[must_use]
1119pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None, initials: None, size: None } }
1120#[must_use]
1122pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
1123 Widget::Avatar { source: source.into(), status: Some(status), initials: None, size: None }
1124}
1125#[must_use]
1127pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
1128#[must_use]
1130pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
1131 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
1132}
1133
1134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1142pub struct ButtonOpts {
1143 pub tone: Tone,
1144 pub icon: Option<Icon>,
1145 pub wide: bool,
1146}
1147
1148impl Default for ButtonOpts {
1149 fn default() -> Self {
1150 Self { tone: Tone::Neutral, icon: None, wide: false }
1151 }
1152}
1153
1154impl ButtonOpts {
1155 #[must_use]
1157 pub const fn tone(mut self, tone: Tone) -> Self {
1158 self.tone = tone;
1159 self
1160 }
1161 #[must_use]
1163 pub const fn icon(mut self, icon: Icon) -> Self {
1164 self.icon = Some(icon);
1165 self
1166 }
1167 #[must_use]
1169 pub const fn wide(mut self) -> Self {
1170 self.wide = true;
1171 self
1172 }
1173}
1174
1175#[must_use]
1176pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
1177 button_with(label, style, on_press, ButtonOpts::default())
1178}
1179
1180#[must_use]
1182pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1183 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1184}
1185#[must_use]
1186pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1187 Widget::IconButton { icon, on_press: tok(on_press) }
1188}
1189#[must_use]
1190pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1191 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1192}
1193#[must_use]
1194pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1195 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1196}
1197#[must_use]
1201pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1202 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1203}
1204#[must_use]
1206pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1207 field(id, placeholder, value, FieldKind::Secure, None)
1208}
1209#[must_use]
1211pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1212 field(id, placeholder, value, FieldKind::Email, None)
1213}
1214#[must_use]
1216pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1217 field(id, placeholder, value, FieldKind::Number, None)
1218}
1219#[must_use]
1221pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1222 field(id, placeholder, value, FieldKind::Decimal, None)
1223}
1224#[must_use]
1226pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1227 field(id, placeholder, value, FieldKind::Phone, None)
1228}
1229#[must_use]
1231pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1232 field(id, placeholder, value, FieldKind::Url, None)
1233}
1234#[must_use]
1236pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1237 field(id, placeholder, value, FieldKind::Multiline, None)
1238}
1239#[must_use]
1242pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1243 match widget {
1244 Widget::TextField { id, placeholder, value, kind, .. } =>
1245 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1246 other => other,
1247 }
1248}
1249
1250#[must_use]
1254pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1255 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1256}
1257#[must_use]
1260pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1261 match widget {
1262 Widget::A11y { child, label, role, .. } =>
1263 Widget::A11y { child, label, hint: Some(hint.into()), role },
1264 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1265 }
1266}
1267#[must_use]
1269pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1270 match widget {
1271 Widget::A11y { child, label, hint, .. } =>
1272 Widget::A11y { child, label, hint, role: Some(role) },
1273 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1274 }
1275}
1276#[must_use]
1278pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1279 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1280}
1281#[must_use]
1283pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1284 Segment { label: label.into(), selected, on_select: tok(on_select) }
1285}
1286#[must_use]
1288pub fn segmented(segments: Vec<Segment>) -> Widget {
1289 Widget::Segmented { segments }
1290}
1291#[must_use]
1292pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1293 Widget::Toggle { id: id.into(), label: label.into(), value }
1294}
1295#[must_use]
1296pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1297 Widget::Checkbox { id: id.into(), label: label.into(), value }
1298}
1299#[must_use]
1300pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1301 Widget::Slider { id: id.into(), value, max }
1302}
1303#[must_use]
1304pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1305 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1306}
1307
1308#[must_use]
1310pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1311 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None, badge: None }
1312}
1313
1314#[must_use]
1316pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1317 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon), badge: None }
1318}
1319
1320#[must_use]
1323pub fn with_tab_dot(mut tab: Tab, label: impl Into<String>) -> Tab {
1324 tab.badge = Some(TabBadge { text: String::new(), label: label.into() });
1325 tab
1326}
1327
1328#[must_use]
1331pub fn with_tab_count(mut tab: Tab, count: u32, label: impl Into<String>) -> Tab {
1332 tab.badge = match count {
1333 0 => None,
1334 1..=99 => Some(TabBadge { text: count.to_string(), label: label.into() }),
1335 _ => Some(TabBadge { text: "99+".into(), label: label.into() }),
1336 };
1337 tab
1338}
1339
1340#[must_use]
1343pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1344 let title = title.into();
1345 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, ios_glass_tabs: false }
1347}
1348
1349#[must_use]
1353pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1354 let title = title.into();
1355 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, ios_glass_tabs: false }
1356}
1357
1358#[must_use]
1363pub fn nav_scaffold<R, E>(
1364 title: impl Into<String>,
1365 dark_mode: bool,
1366 tabs: Vec<Tab>,
1367 body: Widget,
1368 nav: &Nav<R>,
1369 on_back: E,
1370) -> Widget
1371where
1372 R: Clone + Serialize,
1373 E: Serialize,
1374{
1375 Widget::Scaffold {
1376 title: title.into(),
1377 body: Box::new(body),
1378 tabs,
1379 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1380 dark_mode,
1381 theme: None,
1382 fab: None,
1383 sheet: None,
1384 on_refresh: None,
1385 refreshing: false,
1386 route: nav.route_key(),
1387 depth: nav.depth(),
1388 labels: None,
1389 appearance: None,
1390 bottom_bar: None,
1391 ios_glass_tabs: false,
1392 }
1393}
1394
1395pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1399 match widget {
1400 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, ios_glass_tabs, .. } => Widget::Scaffold {
1401 title,
1402 body,
1403 tabs,
1404 back,
1405 dark_mode,
1406 theme: Some(theme),
1407 fab,
1408 sheet,
1409 on_refresh,
1410 refreshing,
1411 route,
1412 depth,
1413 labels,
1414 appearance,
1415 bottom_bar,
1416 ios_glass_tabs,
1417 },
1418 other => other,
1419 }
1420}
1421
1422pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1425 set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1426}
1427
1428pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1432 set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1433}
1434
1435#[must_use]
1443pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1444 match widget {
1445 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, ios_glass_tabs, .. } => {
1446 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children), ios_glass_tabs }
1447 }
1448 other => other,
1449 }
1450}
1451
1452#[must_use]
1456pub fn with_ios_glass_tabs(widget: Widget) -> Widget {
1457 match widget {
1458 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => {
1459 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, ios_glass_tabs: true }
1460 }
1461 other => other,
1462 }
1463}
1464
1465fn set_fab(widget: Widget, fab: Fab) -> Widget {
1466 match widget {
1467 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, ios_glass_tabs, .. } => Widget::Scaffold {
1468 title,
1469 body,
1470 tabs,
1471 back,
1472 dark_mode,
1473 theme,
1474 fab: Some(fab),
1475 sheet,
1476 on_refresh,
1477 refreshing,
1478 route,
1479 depth,
1480 labels,
1481 appearance,
1482 bottom_bar,
1483 ios_glass_tabs,
1484 },
1485 other => other,
1486 }
1487}
1488
1489pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1492 match widget {
1493 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, ios_glass_tabs, .. } => Widget::Scaffold {
1494 title: t,
1495 body,
1496 tabs,
1497 back,
1498 dark_mode,
1499 theme,
1500 fab,
1501 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1502 on_refresh,
1503 refreshing,
1504 route,
1505 depth,
1506 labels,
1507 appearance,
1508 bottom_bar,
1509 ios_glass_tabs,
1510 },
1511 other => other,
1512 }
1513}
1514
1515pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1519 match widget {
1520 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, ios_glass_tabs, .. } => Widget::Scaffold {
1521 title,
1522 body,
1523 tabs,
1524 back,
1525 dark_mode,
1526 theme,
1527 fab,
1528 sheet,
1529 on_refresh: Some(tok(on_refresh)),
1530 refreshing,
1531 route,
1532 depth,
1533 labels,
1534 appearance,
1535 bottom_bar,
1536 ios_glass_tabs,
1537 },
1538 Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1541 children,
1542 on_load_more,
1543 loading,
1544 has_more,
1545 on_refresh: Some(tok(on_refresh)),
1546 refreshing,
1547 end_label,
1548 fill,
1549 },
1550 other => other,
1551 }
1552}
1553
1554#[must_use]
1559pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1560 match widget {
1561 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, ios_glass_tabs, .. } => {
1562 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar, ios_glass_tabs }
1563 }
1564 other => other,
1565 }
1566}
1567
1568#[must_use]
1576pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1577 match widget {
1578 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, ios_glass_tabs, .. } => {
1579 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar, ios_glass_tabs }
1580 }
1581 other => other,
1582 }
1583}
1584
1585#[must_use]
1591pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1592 Widget::LazyList {
1593 children,
1594 on_load_more: Some(tok(on_load_more)),
1595 loading,
1596 has_more,
1597 on_refresh: None,
1598 refreshing: false,
1599 end_label: None,
1600 fill: false,
1601 }
1602}
1603
1604#[must_use]
1606pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1607 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1608}
1609
1610#[must_use]
1614pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1615 match widget {
1616 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1617 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1618 }
1619 other => other,
1620 }
1621}
1622
1623#[must_use]
1628pub fn with_fill(widget: Widget) -> Widget {
1629 match widget {
1630 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1631 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1632 }
1633 other => other,
1634 }
1635}
1636
1637#[cfg(test)]
1638mod tests {
1639 #[test]
1640 fn with_tab_count_formats_and_caps() {
1641 let t = || tab_icon("Nalog", Icon::Person, false, "Account");
1642 assert_eq!(with_tab_count(t(), 7, "7 novih").badge, Some(TabBadge { text: "7".into(), label: "7 novih".into() }));
1643 assert_eq!(with_tab_count(t(), 99, "").badge.unwrap().text, "99");
1644 assert_eq!(with_tab_count(t(), 100, "").badge.unwrap().text, "99+");
1645 assert_eq!(with_tab_count(t(), u32::MAX, "").badge.unwrap().text, "99+");
1646 }
1647
1648 #[test]
1649 fn with_tab_count_zero_clears_a_badge() {
1650 let dotted = with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke");
1651 assert!(dotted.badge.is_some());
1652 assert_eq!(with_tab_count(dotted, 0, "ignored").badge, None);
1653 }
1654
1655 #[test]
1656 fn with_tab_dot_has_empty_text_and_plain_tabs_have_no_badge() {
1657 assert_eq!(with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke").badge, Some(TabBadge { text: String::new(), label: "Nove poruke".into() }));
1658 assert_eq!(tab("Nalog", false, "Account").badge, None);
1659 assert_eq!(tab_icon("Nalog", Icon::Person, true, "Account").badge, None);
1660 let t = with_tab_count(with_tab_dot(tab("Nalog", false, "Account"), "a"), 3, "b");
1662 assert_eq!(t.badge, Some(TabBadge { text: "3".into(), label: "b".into() }));
1663 }
1664
1665 use super::*;
1666 use serde::Serialize;
1667
1668 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1669 enum Route {
1670 Home,
1671 Detail(u32),
1672 }
1673
1674 #[derive(Serialize)]
1675 enum Ev {
1676 Tap,
1677 Open(u32),
1678 }
1679
1680 #[test]
1683 fn plugin_response_carries_bytes_and_converts_text() {
1684 let r = PluginResponse::text(true, "hello");
1685 assert!(r.ok);
1686 assert_eq!(r.output, b"hello".to_vec());
1687 assert_eq!(r.as_text(), Some("hello"));
1688
1689 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1690 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1691 }
1692
1693 #[test]
1696 fn nav_push_pop_depth() {
1697 let mut nav = Nav::new(Route::Home);
1698 assert_eq!(nav.depth(), 1);
1699 assert!(!nav.can_go_back());
1700
1701 nav.push(Route::Detail(7));
1702 assert_eq!(nav.depth(), 2);
1703 assert!(nav.can_go_back());
1704 assert!(matches!(nav.current(), Route::Detail(7)));
1705
1706 nav.pop();
1707 assert_eq!(nav.depth(), 1);
1708 assert!(matches!(nav.current(), Route::Home));
1709
1710 nav.pop(); assert_eq!(nav.depth(), 1);
1712 }
1713
1714 #[test]
1715 fn nav_reset_replaces_stack() {
1716 let mut nav = Nav::new(Route::Home);
1717 nav.push(Route::Detail(1));
1718 nav.push(Route::Detail(2));
1719 nav.reset(Route::Detail(9));
1720 assert_eq!(nav.depth(), 1);
1721 assert!(matches!(nav.current(), Route::Detail(9)));
1722 }
1723
1724 #[test]
1725 fn nav_route_key_is_serialization() {
1726 let nav = Nav::new(Route::Detail(3));
1727 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1728 }
1729
1730 #[test]
1733 fn scaffold_sets_route_depth_and_no_back() {
1734 match scaffold("Home", false, vec![], text("x")) {
1735 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1736 assert_eq!(route, "Home");
1737 assert_eq!(depth, 1);
1738 assert!(back.is_none());
1739 assert!(!dark_mode);
1740 }
1741 other => panic!("expected Scaffold, got {other:?}"),
1742 }
1743 }
1744
1745 #[test]
1746 fn scaffold_back_is_depth_2_with_back() {
1747 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1748 Widget::Scaffold { depth, back, dark_mode, .. } => {
1749 assert_eq!(depth, 2);
1750 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1751 assert!(dark_mode);
1752 }
1753 other => panic!("expected Scaffold, got {other:?}"),
1754 }
1755 }
1756
1757 #[test]
1758 fn nav_scaffold_shows_back_only_when_poppable() {
1759 let mut nav = Nav::new(Route::Home);
1760 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1762 Widget::Scaffold { back, depth, route, .. } => {
1763 assert!(back.is_none());
1764 assert_eq!(depth, 1);
1765 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1766 }
1767 other => panic!("expected Scaffold, got {other:?}"),
1768 }
1769 nav.push(Route::Detail(2));
1771 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1772 Widget::Scaffold { back, depth, .. } => {
1773 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1774 assert_eq!(depth, 2);
1775 }
1776 other => panic!("expected Scaffold, got {other:?}"),
1777 }
1778 }
1779
1780 #[test]
1781 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1782 let l = ShellLabels::new().back("Nazad").ok("U redu");
1783 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1784 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1785 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1786 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1788 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1789 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1790 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1791 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1792 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1793 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1794 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1795 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1797 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1799 let nav = Nav::new(Route::Home);
1801 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1802 }
1803
1804 #[test]
1805 fn button_with_carries_tone_icon_and_width() {
1806 assert!(matches!(
1807 button("Go", ButtonStyle::Filled, Ev::Tap),
1808 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1809 ));
1810 assert!(matches!(
1811 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1812 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1813 ));
1814 }
1815
1816 #[test]
1817 fn buttons_carry_serialized_event_tokens() {
1818 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1819 Widget::Button { label, on_press, .. } => {
1820 assert_eq!(label, "Go");
1821 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1822 }
1823 other => panic!("expected Button, got {other:?}"),
1824 }
1825 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1826 Widget::Card { on_press, .. } => {
1827 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1828 }
1829 other => panic!("expected Card, got {other:?}"),
1830 }
1831 match card(text("c"), CardStyle::Elevated) {
1833 Widget::Card { on_press, on_long_press, .. } => {
1834 assert!(on_press.is_none());
1835 assert!(on_long_press.is_none());
1836 }
1837 other => panic!("expected Card, got {other:?}"),
1838 }
1839 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1841 Widget::Card { on_press, on_long_press, .. } => {
1842 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1843 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1844 }
1845 other => panic!("expected Card, got {other:?}"),
1846 }
1847 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1849 }
1850
1851 #[test]
1854 fn cx_notify_and_save_enqueue_notifications() {
1855 let mut cx = Cx::<Ev>::default();
1856 cx.notify("toast", "show", "hi");
1857 cx.save("blob");
1858 assert_eq!(cx.notifications.len(), 2);
1859 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1860 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1861 assert!(cx.requests.is_empty());
1862 }
1863
1864 #[test]
1865 fn cx_http_helpers_build_requests() {
1866 let mut cx = Cx::<Ev>::default();
1867 cx.get("http://h/x", |_| Ev::Tap);
1868 cx.post("http://h/y", "hello", |_| Ev::Tap);
1869 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1870 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1871 cx.delete("http://h/d", |_| Ev::Tap);
1872
1873 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1874 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1875 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1876
1877 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1878 assert_eq!(get_input["url"], "http://h/x");
1879 assert!(get_input["body"].is_null());
1880
1881 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1882 assert_eq!(put_input["url"], "http://h/p");
1883 assert_eq!(put_input["body"], "putbody");
1884 }
1885
1886 #[test]
1887 fn request_builder_emits_headers_in_order() {
1888 let mut cx = Cx::<Ev>::default();
1889 cx.request("PUT", "http://h/access-key")
1890 .bearer("tok123")
1891 .header("X-Trace-Id", "abc")
1892 .body("{}")
1893 .send(|_| Ev::Tap);
1894
1895 assert_eq!(cx.requests.len(), 1);
1896 let (call, _) = &cx.requests[0];
1897 assert_eq!(call.plugin, "http");
1898 assert_eq!(call.op, "PUT");
1899
1900 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1901 assert_eq!(input["url"], "http://h/access-key");
1902 assert_eq!(input["body"], "{}");
1903 assert_eq!(input["headers"][0]["name"], "Authorization");
1904 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1905 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1906 assert_eq!(input["headers"][1]["value"], "abc");
1907 }
1908
1909 #[test]
1910 fn helpers_emit_no_headers_field_content() {
1911 let mut cx = Cx::<Ev>::default();
1912 cx.get("http://h/x", |_| Ev::Tap);
1913 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1914 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1915 }
1916
1917 #[test]
1918 fn continuation_receives_decoded_outcome() {
1919 #[derive(Debug, PartialEq)]
1920 enum Got { Conflict, Offline, Other }
1921
1922 let classify = |r: PluginResponse| -> Got {
1923 match HttpOutcome::decode(&r.output).unwrap() {
1924 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1925 HttpOutcome::TransportError { .. } => Got::Offline,
1926 _ => Got::Other,
1927 }
1928 };
1929
1930 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1931 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1932
1933 let offline = HttpOutcome::TransportError { message: "refused".into() };
1934 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1935 }
1936
1937 #[test]
1938 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1939 let mut cx = Cx::<Ev>::default();
1944
1945 cx.request("GET", "http://h/x").send(|outcome| {
1946 match outcome {
1947 HttpOutcome::TransportError { message } => {
1948 assert!(
1949 message.contains("malformed http response"),
1950 "unexpected message: {message}"
1951 );
1952 }
1953 HttpOutcome::Response { .. } => {
1954 panic!("garbage bytes must not decode as a Response")
1955 }
1956 }
1957 Ev::Tap
1958 });
1959
1960 assert_eq!(cx.requests.len(), 1);
1961 let (_, continuation) = cx.requests.remove(0);
1962 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1965 }
1966
1967 #[test]
1968 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1969 let mut cx = Cx::<Ev>::default();
1970 cx.pick_photo(|_| Ev::Tap);
1971 cx.capture_photo(|_| Ev::Tap);
1972 assert_eq!(cx.requests.len(), 2);
1973 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", ""));
1976 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", ""));
1977 }
1978
1979 #[test]
1980 fn cx_capture_photo_routes_success_and_cancel() {
1981 let mut cx = Cx::<Ev>::default();
1983 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1984 let (_, then) = cx.requests.pop().unwrap();
1985 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1986
1987 let mut cx = Cx::<Ev>::default();
1989 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1990 let (_, then) = cx.requests.pop().unwrap();
1991 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1992 }
1993
1994 #[test]
1995 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1996 let mut cx = Cx::<Ev>::default();
1997 cx.copy("c");
1998 cx.share("s");
1999 cx.open_url("u");
2000 cx.toast("t");
2001 cx.haptic("heavy");
2002 let got: Vec<(&str, &str, &str)> = cx
2003 .notifications
2004 .iter()
2005 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
2006 .collect();
2007 assert_eq!(
2008 got,
2009 vec![
2010 ("clipboard", "copy", "c"),
2011 ("share", "text", "s"),
2012 ("browser", "open", "u"),
2013 ("toast", "show", "t"),
2014 ("haptics", "heavy", ""), ]
2016 );
2017 assert!(cx.requests.is_empty());
2018 }
2019
2020 #[test]
2021 fn display_and_headline_builders() {
2022 assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
2023 assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
2024 let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
2025 }
2026
2027 #[test]
2028 fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
2029 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
2030 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
2031 assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
2032 assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
2033 }
2034
2035 #[test]
2036 fn with_theme_and_labels_keep_the_appearance() {
2037 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
2038 let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
2039 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
2040 }
2041
2042 #[test]
2043 fn appearance_query_and_stream_shapes() {
2044 let mut cx = Cx::<Ev>::default();
2045 cx.system_appearance(|_| Ev::Tap);
2046 let (call, _) = &cx.requests[0];
2047 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
2048 cx.subscribe_appearance("appr", |_| Ev::Tap);
2049 let (st, _) = &cx.streams[0];
2050 assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
2051 }
2052
2053 #[test]
2054 fn photo_with_calls_send_options_on_the_same_plugin() {
2055 let mut cx = Cx::<Ev>::default();
2056 cx.pick_photo_with(PhotoOptions::new().jpeg(), |_| Ev::Tap);
2057 cx.capture_photo_with(PhotoOptions::new(), |_| Ev::Tap);
2058 let (p, _) = &cx.requests[0];
2059 assert_eq!((p.plugin.as_str(), p.op.as_str(), p.input.as_str()), ("photo", "pick", r#"{"format":"jpeg"}"#));
2060 let (c, _) = &cx.requests[1];
2061 assert_eq!((c.plugin.as_str(), c.op.as_str(), c.input.as_str()), ("camera", "capture", "{}"));
2062 }
2063
2064 #[test]
2065 fn device_info_is_the_device_info_op() {
2066 let mut cx = Cx::<Ev>::default();
2067 cx.device_info(|_| Ev::Tap);
2068 let (call, _) = &cx.requests[0];
2069 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "info", ""));
2070 }
2071
2072 #[test]
2073 fn cx_device_model_is_a_request_not_a_notification() {
2074 let mut cx = Cx::<Ev>::default();
2075 cx.device_model(|_| Ev::Tap);
2076 assert!(cx.notifications.is_empty());
2077 assert_eq!(cx.requests.len(), 1);
2078 let (call, _) = &cx.requests[0];
2079 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
2080 }
2081
2082 #[test]
2083 fn cx_device_locale_requests_the_device_locale_op() {
2084 let mut cx = Cx::<Ev>::default();
2085 cx.device_locale(|_| Ev::Tap);
2086 assert!(cx.notifications.is_empty());
2087 assert_eq!(cx.requests.len(), 1);
2088 let (call, _) = &cx.requests[0];
2089 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
2090 }
2091
2092 #[test]
2093 fn cx_now_requests_the_datetime_now_op() {
2094 let mut cx = Cx::<Ev>::default();
2095 cx.now(|_| Ev::Tap);
2096 assert_eq!(cx.requests.len(), 1);
2097 let (call, _) = &cx.requests[0];
2098 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
2099 }
2100
2101 #[test]
2102 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
2103 let mut cx = Cx::<Ev>::default();
2104 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2105 assert!(cx.notifications.is_empty());
2107 assert!(cx.requests.is_empty());
2108 assert_eq!(cx.streams.len(), 1);
2109 let (call, on_event) = &cx.streams[0];
2110 assert_eq!(
2111 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
2112 ("ws", "websocket", "stream", "wss://h/x")
2113 );
2114 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
2116 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
2117 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
2118 }
2119
2120 #[test]
2121 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
2122 let mut cx = Cx::<Ev>::default();
2123 cx.unsubscribe("ws");
2124 assert!(cx.streams.is_empty());
2125 assert_eq!(cx.notifications.len(), 1);
2126 assert_eq!(
2128 cx.notifications[0],
2129 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
2130 );
2131 }
2132
2133 #[test]
2134 fn cx_confirm_serializes_title_message_and_routes_ok() {
2135 let mut cx = Cx::<Ev>::default();
2136 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2137 let (call, then) = cx.requests.pop().unwrap();
2138 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2139 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2140 assert_eq!(v["title"], "Delete?");
2141 assert_eq!(v["message"], "This cannot be undone.");
2142 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2144 }
2145
2146 #[test]
2147 fn cx_confirm_stays_byte_identical_on_the_wire() {
2148 let mut cx = Cx::<Ev>::default();
2149 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2150 let (call, _) = cx.requests.pop().unwrap();
2151 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2152 }
2153
2154 #[test]
2155 fn cx_confirm_with_sends_labels_and_destructive() {
2156 let mut cx = Cx::<Ev>::default();
2157 cx.confirm_with(
2158 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2159 .confirm_label("Otkaži termin")
2160 .cancel_label("Ne, vrati se")
2161 .destructive(),
2162 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2163 );
2164 let (call, then) = cx.requests.pop().unwrap();
2165 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2166 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2167 assert_eq!(v["title"], "Otkazati termin?");
2168 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2169 assert_eq!(v["confirm_label"], "Otkaži termin");
2170 assert_eq!(v["cancel_label"], "Ne, vrati se");
2171 assert_eq!(v["destructive"], true);
2172 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2173 let mut cx = Cx::<Ev>::default();
2175 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2176 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2177 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2178 }
2179
2180 #[test]
2181 fn with_step_caption_turns_the_caption_on() {
2182 assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2183 assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2184 assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2185 }
2186
2187 #[test]
2188 fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2189 let mut cx = Cx::<Ev>::default();
2190 cx.open_url("https://x");
2191 assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2192 cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2193 let (call, then) = cx.requests.pop().unwrap();
2194 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2195 assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2196 }
2197
2198 #[test]
2199 fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2200 let bar = vec![text("A"), text("B")];
2201 let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2202 assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2203 assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2204 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2205 let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2206 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2207 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2208 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2209 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2210 assert!(keep(with_theme(s.clone(), Theme::default())));
2211 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2212 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2213 }
2214
2215 #[test]
2216 fn with_ios_glass_tabs_sets_and_every_scaffold_builder_keeps_it() {
2217 let s = with_ios_glass_tabs(scaffold("T", false, vec![], text("x")));
2218 assert!(matches!(&s, Widget::Scaffold { ios_glass_tabs: true, .. }));
2219 assert!(matches!(with_ios_glass_tabs(text("x")), Widget::Text { .. }));
2220 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { ios_glass_tabs: false, .. }));
2221 assert!(matches!(scaffold_back("T", false, vec![], text("x"), Ev::Tap), Widget::Scaffold { ios_glass_tabs: false, .. }));
2222 let keep = |w: Widget| matches!(w, Widget::Scaffold { ios_glass_tabs: true, .. });
2223 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2224 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2225 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2226 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2227 assert!(keep(with_theme(s.clone(), Theme::default())));
2228 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2229 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2230 assert!(keep(with_bottom_bar(s.clone(), vec![text("b")])));
2231 }
2232
2233 #[test]
2234 fn steps_builder_clamps_and_step_text_fills_the_template() {
2235 assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2236 assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2237 assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2238 assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2239 assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2240 assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2241 }
2242
2243 #[test]
2244 fn with_columns_sets_clamps_and_ignores_other_widgets() {
2245 assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2246 assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2247 assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2248 assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2249 assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2250 }
2251
2252 #[test]
2253 fn badge_icon_and_avatar_initials_modifiers() {
2254 assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2255 assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2256 let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2257 assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2258 assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2259 assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2261 assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2262 assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2263 }
2264
2265 #[test]
2266 fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2267 let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2268 assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2269 let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2270 assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2271 }
2272
2273 #[test]
2274 fn snackbar_input_is_the_wire_json() {
2275 assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2276 assert_eq!(
2277 Snackbar::new("Cancelled").action("Undo").long().to_input(),
2278 r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2279 );
2280 }
2281
2282 #[test]
2283 fn cx_snackbar_sends_a_snackbar_show_request() {
2284 let mut cx = Cx::<Ev>::default();
2285 cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2286 let (call, then) = cx.requests.pop().unwrap();
2287 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2288 assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2289 assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2290 }
2291
2292 #[test]
2293 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2294 let mut cx = Cx::<Ev>::default();
2295 cx.pick_date(|_| Ev::Tap);
2296 cx.pick_time(|_| Ev::Tap);
2297 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2298
2299 let mut cx = Cx::<Ev>::default();
2300 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2301 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2302 let (date, _) = &cx.requests[0];
2303 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2304 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2305 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2306 let (time, _) = &cx.requests[1];
2307 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2308 }
2309
2310 #[test]
2313 fn text_builders_carry_their_style() {
2314 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2315 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2316 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2317 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2318 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2319 }
2320
2321 #[test]
2322 fn layout_and_content_builders_produce_their_variants() {
2323 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2324 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2325 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2326 assert!(matches!(divider(), Widget::Divider));
2327 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2328 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2329 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2330 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)));
2331 let rc = with_bracket(
2332 region_chart(
2333 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2334 vec![ChartTick::new(3.0, "3 Mt.")],
2335 65.0, 80.0,
2336 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2337 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2338 ),
2339 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2340 );
2341 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2342 assert!(matches!(
2344 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2345 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2346 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2347 ));
2348 assert!(matches!(
2349 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2350 Widget::SwipeAction { actions, .. } if actions.len() == 1
2351 ));
2352 assert!(matches!(
2354 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2355 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2356 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2357 ));
2358 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2359 assert!(matches!(
2361 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2362 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2363 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2364 ));
2365 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2367 assert!(matches!(
2368 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2369 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2370 ));
2371 assert!(matches!(
2373 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2374 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2375 ));
2376 assert!(matches!(
2377 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2378 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2379 ));
2380 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2382 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2383 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2384 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2385 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2386 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2387 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2389 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2391 Widget::Split { show_detail: true, on_back: Some(_), .. }));
2392 }
2393
2394 #[test]
2395 fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2396 assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2397 assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2398 let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2399 assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2400 let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2402 assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2403 assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2404 assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2405 }
2406
2407 #[test]
2408 fn input_builders_carry_ids_values_and_event_tokens() {
2409 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2410 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2411 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2412 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2414 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2415 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2416 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2417 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2419 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2420 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2421 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2422 with_captions(video_player("v", "u", true, -1, Ev::Tap),
2423 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2424 "p.jpg"), 9000), 1.5), 0.5));
2425 assert!(matches!(tuned,
2426 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2427 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2428 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2430 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2431 assert!(matches!(with_pip(divider()), Widget::Divider));
2433 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2434 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2435 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2436 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2437 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2438 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2439 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2440 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2441
2442 match chip("Latte", true, Ev::Open(2)) {
2443 Widget::Chip { selected, on_press, .. } => {
2444 assert!(selected);
2445 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2446 }
2447 other => panic!("expected Chip, got {other:?}"),
2448 }
2449 match stepper(5, Ev::Tap, Ev::Open(1)) {
2450 Widget::Stepper { value, on_decrement, on_increment } => {
2451 assert_eq!(value, 5);
2452 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2453 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2454 }
2455 other => panic!("expected Stepper, got {other:?}"),
2456 }
2457 let t = tab("Home", true, Ev::Tap);
2458 assert_eq!(t.label, "Home");
2459 assert!(t.selected);
2460 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2461 }
2462
2463 #[test]
2466 fn widget_tree_round_trips_through_serde() {
2467 let tree = scaffold(
2468 "Home",
2469 true,
2470 vec![tab("A", true, Ev::Tap)],
2471 column(vec![
2472 title("Hi"),
2473 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2474 image("u", ImageShape::Rounded, ImageRatio::Wide),
2475 slider("s", 2, 5),
2476 ]),
2477 );
2478 let s = serde_json::to_string(&tree).unwrap();
2479 let back: Widget = serde_json::from_str(&s).unwrap();
2480 assert_eq!(s, serde_json::to_string(&back).unwrap());
2481 }
2482
2483 #[test]
2484 fn actions_and_input_values_round_trip() {
2485 let actions = vec![
2486 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2487 Action::Input { id: "n".into(), value: InputValue::Int(7) },
2488 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2489 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2490 Action::Restore { data: "blob".into() },
2491 Action::Start,
2492 Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2493 ];
2494 for a in actions {
2495 let s = serde_json::to_string(&a).unwrap();
2496 let back: Action = serde_json::from_str(&s).unwrap();
2497 assert_eq!(s, serde_json::to_string(&back).unwrap());
2498 }
2499 }
2500
2501 #[derive(Default)]
2504 struct CounterModel {
2505 count: i32,
2506 restored: String,
2507 started: bool,
2508 last_input: String,
2509 app_build: String,
2510 }
2511
2512 #[derive(serde::Serialize, serde::Deserialize)]
2513 enum CounterEv {
2514 Inc,
2515 Add(i32),
2516 }
2517
2518 #[derive(Default)]
2519 struct CounterApp;
2520
2521 impl MobilerApp for CounterApp {
2522 type Event = CounterEv;
2523 type Model = CounterModel;
2524 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2525 match ev {
2526 CounterEv::Inc => model.count += 1,
2527 CounterEv::Add(n) => model.count += n,
2528 }
2529 }
2530 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2531 if let InputValue::Text(t) = value {
2532 model.last_input = format!("{id}={t}");
2533 }
2534 }
2535 fn restore(&self, data: &str, model: &mut CounterModel) {
2536 model.restored = data.to_string();
2537 }
2538 fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2539 model.started = true;
2540 model.app_build = cx.app_info().build.clone();
2541 }
2542 fn view(&self, model: &CounterModel) -> Widget {
2543 text(format!("{}", model.count))
2544 }
2545 }
2546
2547 #[test]
2548 fn shell_dispatches_fired_input_restore_and_start() {
2549 use crux_core::App as _;
2550 let shell = MobilerShell::<CounterApp>::default();
2551 let mut m = CounterModel::default();
2552
2553 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2555 assert_eq!(m.count, 5);
2556 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2558 assert_eq!(m.last_input, "name=bob");
2559 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2561 assert_eq!(m.restored, "saved");
2562 let _ = shell.update(Action::Start, &mut m);
2564 assert!(m.started);
2565 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2567 }
2568
2569 fn info(build: &str) -> AppInfo {
2570 AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2571 }
2572
2573 fn app_info_action(build: &str) -> Action {
2574 let i = info(build);
2575 Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2576 }
2577
2578 static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2581
2582 #[test]
2583 fn init_sees_app_info_sent_before_start() {
2584 use crux_core::App as _;
2585 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2586 let shell = MobilerShell::<CounterApp>::default();
2587 let mut m = CounterModel::default();
2588 let _ = shell.update(app_info_action("7"), &mut m);
2589 let _ = shell.update(Action::Start, &mut m);
2590 assert_eq!(m.app_build, "7");
2591 }
2592
2593 #[test]
2594 fn later_app_info_replaces_earlier() {
2595 use crux_core::App as _;
2596 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2597 let shell = MobilerShell::<CounterApp>::default();
2598 let mut m = CounterModel::default();
2599 let _ = shell.update(app_info_action("7"), &mut m);
2600 let _ = shell.update(app_info_action("8"), &mut m);
2601 let _ = shell.update(Action::Start, &mut m);
2602 assert_eq!(m.app_build, "8");
2603 }
2604
2605 #[test]
2606 fn app_info_action_does_not_touch_the_model() {
2607 use crux_core::App as _;
2608 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2609 let shell = MobilerShell::<CounterApp>::default();
2610 let mut m = CounterModel::default();
2611 let _ = shell.update(app_info_action("9"), &mut m);
2612 assert!(!m.started);
2613 assert_eq!(m.count, 0);
2614 assert!(m.restored.is_empty());
2615 assert!(m.last_input.is_empty());
2616 assert!(m.app_build.is_empty());
2617 }
2618
2619 #[test]
2620 fn cx_default_has_empty_app_info() {
2621 let cx = Cx::<Ev>::default();
2622 assert_eq!(cx.app_info(), &AppInfo::default());
2623 assert!(cx.app_info().platform.is_empty());
2624 }
2625
2626 #[test]
2627 fn cx_with_app_info_carries_it() {
2628 let cx = Cx::<Ev>::with_app_info(info("42"));
2629 assert_eq!(cx.app_info().build, "42");
2630 assert_eq!(cx.app_info().bundle_id, "rs.x");
2631 }
2632
2633 #[test]
2634 fn shell_ignores_a_malformed_fired_token() {
2635 use crux_core::App as _;
2636 let shell = MobilerShell::<CounterApp>::default();
2637 let mut m = CounterModel::default();
2638 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2641 assert_eq!(m.count, 0);
2642 }
2643
2644 #[derive(Default)]
2647 struct EffectsApp;
2648
2649 impl MobilerApp for EffectsApp {
2650 type Event = CounterEv;
2651 type Model = CounterModel;
2652 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2653 model.count += 1;
2654 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2655 cx.notify("toast", "show", "hi");
2656 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2657 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2658 }
2659 fn view(&self, model: &CounterModel) -> Widget {
2660 text(format!("{}", model.count))
2661 }
2662 }
2663
2664 #[test]
2665 fn shell_renders_before_requests_notifications_and_streams() {
2666 use crux_core::App as _;
2667 let shell = MobilerShell::<EffectsApp>::default();
2668 let mut m = CounterModel::default();
2669 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2670 let kinds: Vec<String> = cmd
2671 .effects()
2672 .map(|e| match e {
2673 Effect::Render(_) => "render".to_string(),
2674 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2675 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2676 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2677 })
2678 .collect();
2679 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2682 }
2683
2684 #[test]
2687 fn upload_builder_emits_transfer_stream_call() {
2688 let mut cx = Cx::<Ev>::default();
2689 let key = cx
2690 .upload("https://h/put", "file:///tmp/a.enc")
2691 .bearer("tok")
2692 .header("Content-Type", "application/octet-stream")
2693 .start("up-1", |_ev| Ev::Tap);
2694
2695 assert_eq!(key, "up-1");
2696 assert_eq!(cx.streams.len(), 1);
2697 let (call, _) = &cx.streams[0];
2698 assert_eq!(call.key, "up-1");
2699 assert_eq!(call.plugin, "transfer");
2700 assert_eq!(call.op, "upload");
2701
2702 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2703 assert_eq!(v["url"], "https://h/put");
2704 assert_eq!(v["source"], "file:///tmp/a.enc");
2705 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2707 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2708 assert_eq!(v["headers"][1]["name"], "Content-Type");
2709 }
2710
2711 #[test]
2712 fn download_builder_uses_dest_and_no_default_method() {
2713 let mut cx = Cx::<Ev>::default();
2714 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2715 let (call, _) = &cx.streams[0];
2716 assert_eq!(call.op, "download");
2717 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2718 assert_eq!(v["dest"], "/data/att-9.enc");
2719 assert!(v.get("source").is_none());
2720 }
2721
2722 #[test]
2723 fn start_continuation_decodes_progress_and_done() {
2724 use crate::http::HttpOutcome;
2725
2726 #[derive(Debug, PartialEq)]
2729 enum Got {
2730 Prog(u64),
2731 Done(u16),
2732 Bad,
2733 }
2734 #[derive(Debug, PartialEq)]
2735 struct GotEv(Got);
2736
2737 let mut cx = Cx::<GotEv>::default();
2738 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2739 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2740 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2741 Some(s) => Got::Done(s),
2742 None => Got::Bad,
2743 }),
2744 });
2745 let (_, cont) = &cx.streams[0];
2746
2747 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2748 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2749
2750 let done = TransferEvent::Done {
2751 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2752 handle: Some("/d".into()),
2753 };
2754 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2755 }
2756
2757 #[test]
2758 fn calendar_in_localizes_layout_and_clamps_markers() {
2759 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2761 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2762 assert_eq!(title, "Septembar 2026");
2763 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2764 assert_eq!(leading_blanks, 1);
2765 assert_eq!(on_day.len(), 30);
2766 assert_eq!(markers.len(), 30, "padded to one level per day");
2767 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2768 assert!(matches!(
2770 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2771 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2772 ));
2773 let Widget::Calendar { title, weekday_labels, leading_blanks, .. } =
2775 calendar_in(Locale::PlPl, 2026, 12, None, &[], |_| Ev::Tap)
2776 else {
2777 panic!("not a calendar")
2778 };
2779 assert_eq!(title, "Grudzień 2026");
2780 assert_eq!(weekday_labels, ["P", "W", "Ś", "C", "P", "S", "N"]);
2781 assert_eq!(leading_blanks, 1);
2782 }
2783
2784 #[test]
2785 fn scroller_hint_is_opt_in() {
2786 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2787 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2788 }
2789
2790 fn copy_input(cx: &Cx<Ev>, i: usize) -> serde_json::Value {
2792 let (call, _) = &cx.requests[i];
2793 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("clipboard_with", "copy"));
2794 serde_json::from_str(&call.input).unwrap()
2795 }
2796
2797 #[test]
2798 fn copy_with_and_copy_sensitive_send_the_whole_options_object() {
2799 let mut cx = Cx::<Ev>::default();
2800 cx.copy_with("plain", CopyOptions::new(), |_| Ev::Tap);
2801 cx.copy_sensitive("JBSWY3DPEHPK3PXP", |_| Ev::Tap);
2802 cx.copy_with(
2803 "",
2804 CopyOptions::sensitive().expires_after(std::time::Duration::from_secs(30)).local_only(false),
2805 |_| Ev::Tap,
2806 );
2807 cx.copy_with("x", CopyOptions::sensitive().never_expires().mark_sensitive(false), |_| Ev::Tap);
2808 assert_eq!(copy_input(&cx, 0), serde_json::json!({"text":"plain","sensitive":false,"expires_ms":null,"local_only":false}));
2809 assert_eq!(copy_input(&cx, 1), serde_json::json!({"text":"JBSWY3DPEHPK3PXP","sensitive":true,"expires_ms":120000,"local_only":true}));
2810 assert_eq!(copy_input(&cx, 2), serde_json::json!({"text":"","sensitive":true,"expires_ms":30000,"local_only":false}));
2811 assert_eq!(copy_input(&cx, 3), serde_json::json!({"text":"x","sensitive":false,"expires_ms":null,"local_only":true}));
2812 assert!(cx.notifications.is_empty(), "copy_with is a request, never a notification");
2813 assert_eq!(CopyOptions::default(), CopyOptions::new());
2814 }
2815
2816 #[test]
2817 fn expires_after_is_clamped_and_saturates() {
2818 let mut cx = Cx::<Ev>::default();
2819 cx.copy_with("a", CopyOptions::new().expires_after(std::time::Duration::from_millis(10)), |_| Ev::Tap);
2820 cx.copy_with("b", CopyOptions::new().expires_after(std::time::Duration::MAX), |_| Ev::Tap);
2821 assert_eq!(copy_input(&cx, 0)["expires_ms"], serde_json::json!(1000));
2822 assert_eq!(copy_input(&cx, 1)["expires_ms"], serde_json::json!(u64::MAX));
2823 }
2824
2825 #[test]
2826 fn copy_with_input_round_trips_tricky_text() {
2827 let tricky = "a \"quoted\" \\ back\nslash\t🔑 ćčž";
2828 let mut cx = Cx::<Ev>::default();
2829 cx.copy_with(tricky, CopyOptions::sensitive(), |_| Ev::Tap);
2830 assert_eq!(copy_input(&cx, 0)["text"], serde_json::json!(tricky));
2831 }
2832
2833 #[test]
2835 fn plain_copy_is_unchanged_and_options_never_go_to_clipboard() {
2836 let mut cx = Cx::<Ev>::default();
2837 cx.copy("c");
2838 cx.copy_with("o", CopyOptions::sensitive(), |_| Ev::Tap);
2839 cx.copy_sensitive("s", |_| Ev::Tap);
2840 let notes: Vec<(&str, &str, &str)> =
2841 cx.notifications.iter().map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str())).collect();
2842 assert_eq!(notes, vec![("clipboard", "copy", "c")]);
2843 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "clipboard_with"));
2844 }
2845}