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 }
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 }
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 }
1392}
1393
1394pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1398 match widget {
1399 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1400 title,
1401 body,
1402 tabs,
1403 back,
1404 dark_mode,
1405 theme: Some(theme),
1406 fab,
1407 sheet,
1408 on_refresh,
1409 refreshing,
1410 route,
1411 depth,
1412 labels,
1413 appearance,
1414 bottom_bar,
1415 },
1416 other => other,
1417 }
1418}
1419
1420pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1423 set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1424}
1425
1426pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1430 set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1431}
1432
1433#[must_use]
1441pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1442 match widget {
1443 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, .. } => {
1444 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children) }
1445 }
1446 other => other,
1447 }
1448}
1449
1450fn set_fab(widget: Widget, fab: Fab) -> Widget {
1451 match widget {
1452 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1453 title,
1454 body,
1455 tabs,
1456 back,
1457 dark_mode,
1458 theme,
1459 fab: Some(fab),
1460 sheet,
1461 on_refresh,
1462 refreshing,
1463 route,
1464 depth,
1465 labels,
1466 appearance,
1467 bottom_bar,
1468 },
1469 other => other,
1470 }
1471}
1472
1473pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1476 match widget {
1477 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1478 title: t,
1479 body,
1480 tabs,
1481 back,
1482 dark_mode,
1483 theme,
1484 fab,
1485 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1486 on_refresh,
1487 refreshing,
1488 route,
1489 depth,
1490 labels,
1491 appearance,
1492 bottom_bar,
1493 },
1494 other => other,
1495 }
1496}
1497
1498pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1502 match widget {
1503 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1504 title,
1505 body,
1506 tabs,
1507 back,
1508 dark_mode,
1509 theme,
1510 fab,
1511 sheet,
1512 on_refresh: Some(tok(on_refresh)),
1513 refreshing,
1514 route,
1515 depth,
1516 labels,
1517 appearance,
1518 bottom_bar,
1519 },
1520 Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1523 children,
1524 on_load_more,
1525 loading,
1526 has_more,
1527 on_refresh: Some(tok(on_refresh)),
1528 refreshing,
1529 end_label,
1530 fill,
1531 },
1532 other => other,
1533 }
1534}
1535
1536#[must_use]
1541pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1542 match widget {
1543 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, .. } => {
1544 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar }
1545 }
1546 other => other,
1547 }
1548}
1549
1550#[must_use]
1558pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1559 match widget {
1560 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, .. } => {
1561 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar }
1562 }
1563 other => other,
1564 }
1565}
1566
1567#[must_use]
1573pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1574 Widget::LazyList {
1575 children,
1576 on_load_more: Some(tok(on_load_more)),
1577 loading,
1578 has_more,
1579 on_refresh: None,
1580 refreshing: false,
1581 end_label: None,
1582 fill: false,
1583 }
1584}
1585
1586#[must_use]
1588pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1589 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1590}
1591
1592#[must_use]
1596pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1597 match widget {
1598 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1599 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1600 }
1601 other => other,
1602 }
1603}
1604
1605#[must_use]
1610pub fn with_fill(widget: Widget) -> Widget {
1611 match widget {
1612 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1613 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1614 }
1615 other => other,
1616 }
1617}
1618
1619#[cfg(test)]
1620mod tests {
1621 #[test]
1622 fn with_tab_count_formats_and_caps() {
1623 let t = || tab_icon("Nalog", Icon::Person, false, "Account");
1624 assert_eq!(with_tab_count(t(), 7, "7 novih").badge, Some(TabBadge { text: "7".into(), label: "7 novih".into() }));
1625 assert_eq!(with_tab_count(t(), 99, "").badge.unwrap().text, "99");
1626 assert_eq!(with_tab_count(t(), 100, "").badge.unwrap().text, "99+");
1627 assert_eq!(with_tab_count(t(), u32::MAX, "").badge.unwrap().text, "99+");
1628 }
1629
1630 #[test]
1631 fn with_tab_count_zero_clears_a_badge() {
1632 let dotted = with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke");
1633 assert!(dotted.badge.is_some());
1634 assert_eq!(with_tab_count(dotted, 0, "ignored").badge, None);
1635 }
1636
1637 #[test]
1638 fn with_tab_dot_has_empty_text_and_plain_tabs_have_no_badge() {
1639 assert_eq!(with_tab_dot(tab("Nalog", false, "Account"), "Nove poruke").badge, Some(TabBadge { text: String::new(), label: "Nove poruke".into() }));
1640 assert_eq!(tab("Nalog", false, "Account").badge, None);
1641 assert_eq!(tab_icon("Nalog", Icon::Person, true, "Account").badge, None);
1642 let t = with_tab_count(with_tab_dot(tab("Nalog", false, "Account"), "a"), 3, "b");
1644 assert_eq!(t.badge, Some(TabBadge { text: "3".into(), label: "b".into() }));
1645 }
1646
1647 use super::*;
1648 use serde::Serialize;
1649
1650 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1651 enum Route {
1652 Home,
1653 Detail(u32),
1654 }
1655
1656 #[derive(Serialize)]
1657 enum Ev {
1658 Tap,
1659 Open(u32),
1660 }
1661
1662 #[test]
1665 fn plugin_response_carries_bytes_and_converts_text() {
1666 let r = PluginResponse::text(true, "hello");
1667 assert!(r.ok);
1668 assert_eq!(r.output, b"hello".to_vec());
1669 assert_eq!(r.as_text(), Some("hello"));
1670
1671 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1672 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1673 }
1674
1675 #[test]
1678 fn nav_push_pop_depth() {
1679 let mut nav = Nav::new(Route::Home);
1680 assert_eq!(nav.depth(), 1);
1681 assert!(!nav.can_go_back());
1682
1683 nav.push(Route::Detail(7));
1684 assert_eq!(nav.depth(), 2);
1685 assert!(nav.can_go_back());
1686 assert!(matches!(nav.current(), Route::Detail(7)));
1687
1688 nav.pop();
1689 assert_eq!(nav.depth(), 1);
1690 assert!(matches!(nav.current(), Route::Home));
1691
1692 nav.pop(); assert_eq!(nav.depth(), 1);
1694 }
1695
1696 #[test]
1697 fn nav_reset_replaces_stack() {
1698 let mut nav = Nav::new(Route::Home);
1699 nav.push(Route::Detail(1));
1700 nav.push(Route::Detail(2));
1701 nav.reset(Route::Detail(9));
1702 assert_eq!(nav.depth(), 1);
1703 assert!(matches!(nav.current(), Route::Detail(9)));
1704 }
1705
1706 #[test]
1707 fn nav_route_key_is_serialization() {
1708 let nav = Nav::new(Route::Detail(3));
1709 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1710 }
1711
1712 #[test]
1715 fn scaffold_sets_route_depth_and_no_back() {
1716 match scaffold("Home", false, vec![], text("x")) {
1717 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1718 assert_eq!(route, "Home");
1719 assert_eq!(depth, 1);
1720 assert!(back.is_none());
1721 assert!(!dark_mode);
1722 }
1723 other => panic!("expected Scaffold, got {other:?}"),
1724 }
1725 }
1726
1727 #[test]
1728 fn scaffold_back_is_depth_2_with_back() {
1729 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1730 Widget::Scaffold { depth, back, dark_mode, .. } => {
1731 assert_eq!(depth, 2);
1732 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1733 assert!(dark_mode);
1734 }
1735 other => panic!("expected Scaffold, got {other:?}"),
1736 }
1737 }
1738
1739 #[test]
1740 fn nav_scaffold_shows_back_only_when_poppable() {
1741 let mut nav = Nav::new(Route::Home);
1742 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1744 Widget::Scaffold { back, depth, route, .. } => {
1745 assert!(back.is_none());
1746 assert_eq!(depth, 1);
1747 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1748 }
1749 other => panic!("expected Scaffold, got {other:?}"),
1750 }
1751 nav.push(Route::Detail(2));
1753 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1754 Widget::Scaffold { back, depth, .. } => {
1755 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1756 assert_eq!(depth, 2);
1757 }
1758 other => panic!("expected Scaffold, got {other:?}"),
1759 }
1760 }
1761
1762 #[test]
1763 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1764 let l = ShellLabels::new().back("Nazad").ok("U redu");
1765 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1766 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1767 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1768 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1770 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1771 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1772 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1773 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1774 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1775 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1776 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1777 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1779 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1781 let nav = Nav::new(Route::Home);
1783 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1784 }
1785
1786 #[test]
1787 fn button_with_carries_tone_icon_and_width() {
1788 assert!(matches!(
1789 button("Go", ButtonStyle::Filled, Ev::Tap),
1790 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1791 ));
1792 assert!(matches!(
1793 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1794 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1795 ));
1796 }
1797
1798 #[test]
1799 fn buttons_carry_serialized_event_tokens() {
1800 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1801 Widget::Button { label, on_press, .. } => {
1802 assert_eq!(label, "Go");
1803 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1804 }
1805 other => panic!("expected Button, got {other:?}"),
1806 }
1807 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1808 Widget::Card { on_press, .. } => {
1809 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1810 }
1811 other => panic!("expected Card, got {other:?}"),
1812 }
1813 match card(text("c"), CardStyle::Elevated) {
1815 Widget::Card { on_press, on_long_press, .. } => {
1816 assert!(on_press.is_none());
1817 assert!(on_long_press.is_none());
1818 }
1819 other => panic!("expected Card, got {other:?}"),
1820 }
1821 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1823 Widget::Card { on_press, on_long_press, .. } => {
1824 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1825 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1826 }
1827 other => panic!("expected Card, got {other:?}"),
1828 }
1829 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1831 }
1832
1833 #[test]
1836 fn cx_notify_and_save_enqueue_notifications() {
1837 let mut cx = Cx::<Ev>::default();
1838 cx.notify("toast", "show", "hi");
1839 cx.save("blob");
1840 assert_eq!(cx.notifications.len(), 2);
1841 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1842 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1843 assert!(cx.requests.is_empty());
1844 }
1845
1846 #[test]
1847 fn cx_http_helpers_build_requests() {
1848 let mut cx = Cx::<Ev>::default();
1849 cx.get("http://h/x", |_| Ev::Tap);
1850 cx.post("http://h/y", "hello", |_| Ev::Tap);
1851 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1852 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1853 cx.delete("http://h/d", |_| Ev::Tap);
1854
1855 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1856 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1857 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1858
1859 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1860 assert_eq!(get_input["url"], "http://h/x");
1861 assert!(get_input["body"].is_null());
1862
1863 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1864 assert_eq!(put_input["url"], "http://h/p");
1865 assert_eq!(put_input["body"], "putbody");
1866 }
1867
1868 #[test]
1869 fn request_builder_emits_headers_in_order() {
1870 let mut cx = Cx::<Ev>::default();
1871 cx.request("PUT", "http://h/access-key")
1872 .bearer("tok123")
1873 .header("X-Trace-Id", "abc")
1874 .body("{}")
1875 .send(|_| Ev::Tap);
1876
1877 assert_eq!(cx.requests.len(), 1);
1878 let (call, _) = &cx.requests[0];
1879 assert_eq!(call.plugin, "http");
1880 assert_eq!(call.op, "PUT");
1881
1882 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1883 assert_eq!(input["url"], "http://h/access-key");
1884 assert_eq!(input["body"], "{}");
1885 assert_eq!(input["headers"][0]["name"], "Authorization");
1886 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1887 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1888 assert_eq!(input["headers"][1]["value"], "abc");
1889 }
1890
1891 #[test]
1892 fn helpers_emit_no_headers_field_content() {
1893 let mut cx = Cx::<Ev>::default();
1894 cx.get("http://h/x", |_| Ev::Tap);
1895 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1896 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1897 }
1898
1899 #[test]
1900 fn continuation_receives_decoded_outcome() {
1901 #[derive(Debug, PartialEq)]
1902 enum Got { Conflict, Offline, Other }
1903
1904 let classify = |r: PluginResponse| -> Got {
1905 match HttpOutcome::decode(&r.output).unwrap() {
1906 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1907 HttpOutcome::TransportError { .. } => Got::Offline,
1908 _ => Got::Other,
1909 }
1910 };
1911
1912 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1913 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1914
1915 let offline = HttpOutcome::TransportError { message: "refused".into() };
1916 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1917 }
1918
1919 #[test]
1920 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1921 let mut cx = Cx::<Ev>::default();
1926
1927 cx.request("GET", "http://h/x").send(|outcome| {
1928 match outcome {
1929 HttpOutcome::TransportError { message } => {
1930 assert!(
1931 message.contains("malformed http response"),
1932 "unexpected message: {message}"
1933 );
1934 }
1935 HttpOutcome::Response { .. } => {
1936 panic!("garbage bytes must not decode as a Response")
1937 }
1938 }
1939 Ev::Tap
1940 });
1941
1942 assert_eq!(cx.requests.len(), 1);
1943 let (_, continuation) = cx.requests.remove(0);
1944 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1947 }
1948
1949 #[test]
1950 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1951 let mut cx = Cx::<Ev>::default();
1952 cx.pick_photo(|_| Ev::Tap);
1953 cx.capture_photo(|_| Ev::Tap);
1954 assert_eq!(cx.requests.len(), 2);
1955 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", ""));
1958 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", ""));
1959 }
1960
1961 #[test]
1962 fn cx_capture_photo_routes_success_and_cancel() {
1963 let mut cx = Cx::<Ev>::default();
1965 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1966 let (_, then) = cx.requests.pop().unwrap();
1967 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1968
1969 let mut cx = Cx::<Ev>::default();
1971 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1972 let (_, then) = cx.requests.pop().unwrap();
1973 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1974 }
1975
1976 #[test]
1977 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1978 let mut cx = Cx::<Ev>::default();
1979 cx.copy("c");
1980 cx.share("s");
1981 cx.open_url("u");
1982 cx.toast("t");
1983 cx.haptic("heavy");
1984 let got: Vec<(&str, &str, &str)> = cx
1985 .notifications
1986 .iter()
1987 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1988 .collect();
1989 assert_eq!(
1990 got,
1991 vec![
1992 ("clipboard", "copy", "c"),
1993 ("share", "text", "s"),
1994 ("browser", "open", "u"),
1995 ("toast", "show", "t"),
1996 ("haptics", "heavy", ""), ]
1998 );
1999 assert!(cx.requests.is_empty());
2000 }
2001
2002 #[test]
2003 fn display_and_headline_builders() {
2004 assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
2005 assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
2006 let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
2007 }
2008
2009 #[test]
2010 fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
2011 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
2012 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
2013 assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
2014 assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
2015 }
2016
2017 #[test]
2018 fn with_theme_and_labels_keep_the_appearance() {
2019 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
2020 let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
2021 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
2022 }
2023
2024 #[test]
2025 fn appearance_query_and_stream_shapes() {
2026 let mut cx = Cx::<Ev>::default();
2027 cx.system_appearance(|_| Ev::Tap);
2028 let (call, _) = &cx.requests[0];
2029 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
2030 cx.subscribe_appearance("appr", |_| Ev::Tap);
2031 let (st, _) = &cx.streams[0];
2032 assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
2033 }
2034
2035 #[test]
2036 fn photo_with_calls_send_options_on_the_same_plugin() {
2037 let mut cx = Cx::<Ev>::default();
2038 cx.pick_photo_with(PhotoOptions::new().jpeg(), |_| Ev::Tap);
2039 cx.capture_photo_with(PhotoOptions::new(), |_| Ev::Tap);
2040 let (p, _) = &cx.requests[0];
2041 assert_eq!((p.plugin.as_str(), p.op.as_str(), p.input.as_str()), ("photo", "pick", r#"{"format":"jpeg"}"#));
2042 let (c, _) = &cx.requests[1];
2043 assert_eq!((c.plugin.as_str(), c.op.as_str(), c.input.as_str()), ("camera", "capture", "{}"));
2044 }
2045
2046 #[test]
2047 fn device_info_is_the_device_info_op() {
2048 let mut cx = Cx::<Ev>::default();
2049 cx.device_info(|_| Ev::Tap);
2050 let (call, _) = &cx.requests[0];
2051 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "info", ""));
2052 }
2053
2054 #[test]
2055 fn cx_device_model_is_a_request_not_a_notification() {
2056 let mut cx = Cx::<Ev>::default();
2057 cx.device_model(|_| Ev::Tap);
2058 assert!(cx.notifications.is_empty());
2059 assert_eq!(cx.requests.len(), 1);
2060 let (call, _) = &cx.requests[0];
2061 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
2062 }
2063
2064 #[test]
2065 fn cx_device_locale_requests_the_device_locale_op() {
2066 let mut cx = Cx::<Ev>::default();
2067 cx.device_locale(|_| Ev::Tap);
2068 assert!(cx.notifications.is_empty());
2069 assert_eq!(cx.requests.len(), 1);
2070 let (call, _) = &cx.requests[0];
2071 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
2072 }
2073
2074 #[test]
2075 fn cx_now_requests_the_datetime_now_op() {
2076 let mut cx = Cx::<Ev>::default();
2077 cx.now(|_| Ev::Tap);
2078 assert_eq!(cx.requests.len(), 1);
2079 let (call, _) = &cx.requests[0];
2080 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
2081 }
2082
2083 #[test]
2084 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
2085 let mut cx = Cx::<Ev>::default();
2086 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2087 assert!(cx.notifications.is_empty());
2089 assert!(cx.requests.is_empty());
2090 assert_eq!(cx.streams.len(), 1);
2091 let (call, on_event) = &cx.streams[0];
2092 assert_eq!(
2093 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
2094 ("ws", "websocket", "stream", "wss://h/x")
2095 );
2096 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
2098 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
2099 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
2100 }
2101
2102 #[test]
2103 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
2104 let mut cx = Cx::<Ev>::default();
2105 cx.unsubscribe("ws");
2106 assert!(cx.streams.is_empty());
2107 assert_eq!(cx.notifications.len(), 1);
2108 assert_eq!(
2110 cx.notifications[0],
2111 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
2112 );
2113 }
2114
2115 #[test]
2116 fn cx_confirm_serializes_title_message_and_routes_ok() {
2117 let mut cx = Cx::<Ev>::default();
2118 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2119 let (call, then) = cx.requests.pop().unwrap();
2120 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2121 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2122 assert_eq!(v["title"], "Delete?");
2123 assert_eq!(v["message"], "This cannot be undone.");
2124 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2126 }
2127
2128 #[test]
2129 fn cx_confirm_stays_byte_identical_on_the_wire() {
2130 let mut cx = Cx::<Ev>::default();
2131 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2132 let (call, _) = cx.requests.pop().unwrap();
2133 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2134 }
2135
2136 #[test]
2137 fn cx_confirm_with_sends_labels_and_destructive() {
2138 let mut cx = Cx::<Ev>::default();
2139 cx.confirm_with(
2140 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2141 .confirm_label("Otkaži termin")
2142 .cancel_label("Ne, vrati se")
2143 .destructive(),
2144 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2145 );
2146 let (call, then) = cx.requests.pop().unwrap();
2147 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2148 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2149 assert_eq!(v["title"], "Otkazati termin?");
2150 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2151 assert_eq!(v["confirm_label"], "Otkaži termin");
2152 assert_eq!(v["cancel_label"], "Ne, vrati se");
2153 assert_eq!(v["destructive"], true);
2154 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2155 let mut cx = Cx::<Ev>::default();
2157 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2158 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2159 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2160 }
2161
2162 #[test]
2163 fn with_step_caption_turns_the_caption_on() {
2164 assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2165 assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2166 assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2167 }
2168
2169 #[test]
2170 fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2171 let mut cx = Cx::<Ev>::default();
2172 cx.open_url("https://x");
2173 assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2174 cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2175 let (call, then) = cx.requests.pop().unwrap();
2176 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2177 assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2178 }
2179
2180 #[test]
2181 fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2182 let bar = vec![text("A"), text("B")];
2183 let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2184 assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2185 assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2186 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2187 let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2188 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2189 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2190 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2191 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2192 assert!(keep(with_theme(s.clone(), Theme::default())));
2193 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2194 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2195 }
2196
2197 #[test]
2198 fn steps_builder_clamps_and_step_text_fills_the_template() {
2199 assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2200 assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2201 assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2202 assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2203 assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2204 assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2205 }
2206
2207 #[test]
2208 fn with_columns_sets_clamps_and_ignores_other_widgets() {
2209 assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2210 assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2211 assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2212 assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2213 assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2214 }
2215
2216 #[test]
2217 fn badge_icon_and_avatar_initials_modifiers() {
2218 assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2219 assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2220 let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2221 assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2222 assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2223 assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2225 assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2226 assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2227 }
2228
2229 #[test]
2230 fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2231 let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2232 assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2233 let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2234 assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2235 }
2236
2237 #[test]
2238 fn snackbar_input_is_the_wire_json() {
2239 assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2240 assert_eq!(
2241 Snackbar::new("Cancelled").action("Undo").long().to_input(),
2242 r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2243 );
2244 }
2245
2246 #[test]
2247 fn cx_snackbar_sends_a_snackbar_show_request() {
2248 let mut cx = Cx::<Ev>::default();
2249 cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2250 let (call, then) = cx.requests.pop().unwrap();
2251 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2252 assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2253 assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2254 }
2255
2256 #[test]
2257 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2258 let mut cx = Cx::<Ev>::default();
2259 cx.pick_date(|_| Ev::Tap);
2260 cx.pick_time(|_| Ev::Tap);
2261 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2262
2263 let mut cx = Cx::<Ev>::default();
2264 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2265 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2266 let (date, _) = &cx.requests[0];
2267 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2268 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2269 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2270 let (time, _) = &cx.requests[1];
2271 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2272 }
2273
2274 #[test]
2277 fn text_builders_carry_their_style() {
2278 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2279 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2280 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2281 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2282 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2283 }
2284
2285 #[test]
2286 fn layout_and_content_builders_produce_their_variants() {
2287 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2288 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2289 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2290 assert!(matches!(divider(), Widget::Divider));
2291 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2292 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2293 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2294 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)));
2295 let rc = with_bracket(
2296 region_chart(
2297 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2298 vec![ChartTick::new(3.0, "3 Mt.")],
2299 65.0, 80.0,
2300 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2301 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2302 ),
2303 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2304 );
2305 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2306 assert!(matches!(
2308 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2309 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2310 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2311 ));
2312 assert!(matches!(
2313 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2314 Widget::SwipeAction { actions, .. } if actions.len() == 1
2315 ));
2316 assert!(matches!(
2318 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2319 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2320 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2321 ));
2322 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2323 assert!(matches!(
2325 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2326 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2327 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2328 ));
2329 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2331 assert!(matches!(
2332 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2333 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2334 ));
2335 assert!(matches!(
2337 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2338 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2339 ));
2340 assert!(matches!(
2341 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2342 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2343 ));
2344 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2346 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2347 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2348 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2349 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2350 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2351 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2353 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2355 Widget::Split { show_detail: true, on_back: Some(_), .. }));
2356 }
2357
2358 #[test]
2359 fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2360 assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2361 assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2362 let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2363 assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2364 let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2366 assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2367 assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2368 assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2369 }
2370
2371 #[test]
2372 fn input_builders_carry_ids_values_and_event_tokens() {
2373 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2374 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2375 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2376 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2378 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2379 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2380 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2381 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2383 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2384 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2385 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2386 with_captions(video_player("v", "u", true, -1, Ev::Tap),
2387 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2388 "p.jpg"), 9000), 1.5), 0.5));
2389 assert!(matches!(tuned,
2390 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2391 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2392 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2394 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2395 assert!(matches!(with_pip(divider()), Widget::Divider));
2397 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2398 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2399 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2400 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2401 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2402 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2403 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2404 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2405
2406 match chip("Latte", true, Ev::Open(2)) {
2407 Widget::Chip { selected, on_press, .. } => {
2408 assert!(selected);
2409 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2410 }
2411 other => panic!("expected Chip, got {other:?}"),
2412 }
2413 match stepper(5, Ev::Tap, Ev::Open(1)) {
2414 Widget::Stepper { value, on_decrement, on_increment } => {
2415 assert_eq!(value, 5);
2416 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2417 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2418 }
2419 other => panic!("expected Stepper, got {other:?}"),
2420 }
2421 let t = tab("Home", true, Ev::Tap);
2422 assert_eq!(t.label, "Home");
2423 assert!(t.selected);
2424 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2425 }
2426
2427 #[test]
2430 fn widget_tree_round_trips_through_serde() {
2431 let tree = scaffold(
2432 "Home",
2433 true,
2434 vec![tab("A", true, Ev::Tap)],
2435 column(vec![
2436 title("Hi"),
2437 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2438 image("u", ImageShape::Rounded, ImageRatio::Wide),
2439 slider("s", 2, 5),
2440 ]),
2441 );
2442 let s = serde_json::to_string(&tree).unwrap();
2443 let back: Widget = serde_json::from_str(&s).unwrap();
2444 assert_eq!(s, serde_json::to_string(&back).unwrap());
2445 }
2446
2447 #[test]
2448 fn actions_and_input_values_round_trip() {
2449 let actions = vec![
2450 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2451 Action::Input { id: "n".into(), value: InputValue::Int(7) },
2452 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2453 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2454 Action::Restore { data: "blob".into() },
2455 Action::Start,
2456 Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2457 ];
2458 for a in actions {
2459 let s = serde_json::to_string(&a).unwrap();
2460 let back: Action = serde_json::from_str(&s).unwrap();
2461 assert_eq!(s, serde_json::to_string(&back).unwrap());
2462 }
2463 }
2464
2465 #[derive(Default)]
2468 struct CounterModel {
2469 count: i32,
2470 restored: String,
2471 started: bool,
2472 last_input: String,
2473 app_build: String,
2474 }
2475
2476 #[derive(serde::Serialize, serde::Deserialize)]
2477 enum CounterEv {
2478 Inc,
2479 Add(i32),
2480 }
2481
2482 #[derive(Default)]
2483 struct CounterApp;
2484
2485 impl MobilerApp for CounterApp {
2486 type Event = CounterEv;
2487 type Model = CounterModel;
2488 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2489 match ev {
2490 CounterEv::Inc => model.count += 1,
2491 CounterEv::Add(n) => model.count += n,
2492 }
2493 }
2494 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2495 if let InputValue::Text(t) = value {
2496 model.last_input = format!("{id}={t}");
2497 }
2498 }
2499 fn restore(&self, data: &str, model: &mut CounterModel) {
2500 model.restored = data.to_string();
2501 }
2502 fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2503 model.started = true;
2504 model.app_build = cx.app_info().build.clone();
2505 }
2506 fn view(&self, model: &CounterModel) -> Widget {
2507 text(format!("{}", model.count))
2508 }
2509 }
2510
2511 #[test]
2512 fn shell_dispatches_fired_input_restore_and_start() {
2513 use crux_core::App as _;
2514 let shell = MobilerShell::<CounterApp>::default();
2515 let mut m = CounterModel::default();
2516
2517 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2519 assert_eq!(m.count, 5);
2520 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2522 assert_eq!(m.last_input, "name=bob");
2523 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2525 assert_eq!(m.restored, "saved");
2526 let _ = shell.update(Action::Start, &mut m);
2528 assert!(m.started);
2529 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2531 }
2532
2533 fn info(build: &str) -> AppInfo {
2534 AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2535 }
2536
2537 fn app_info_action(build: &str) -> Action {
2538 let i = info(build);
2539 Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2540 }
2541
2542 static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2545
2546 #[test]
2547 fn init_sees_app_info_sent_before_start() {
2548 use crux_core::App as _;
2549 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2550 let shell = MobilerShell::<CounterApp>::default();
2551 let mut m = CounterModel::default();
2552 let _ = shell.update(app_info_action("7"), &mut m);
2553 let _ = shell.update(Action::Start, &mut m);
2554 assert_eq!(m.app_build, "7");
2555 }
2556
2557 #[test]
2558 fn later_app_info_replaces_earlier() {
2559 use crux_core::App as _;
2560 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2561 let shell = MobilerShell::<CounterApp>::default();
2562 let mut m = CounterModel::default();
2563 let _ = shell.update(app_info_action("7"), &mut m);
2564 let _ = shell.update(app_info_action("8"), &mut m);
2565 let _ = shell.update(Action::Start, &mut m);
2566 assert_eq!(m.app_build, "8");
2567 }
2568
2569 #[test]
2570 fn app_info_action_does_not_touch_the_model() {
2571 use crux_core::App as _;
2572 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2573 let shell = MobilerShell::<CounterApp>::default();
2574 let mut m = CounterModel::default();
2575 let _ = shell.update(app_info_action("9"), &mut m);
2576 assert!(!m.started);
2577 assert_eq!(m.count, 0);
2578 assert!(m.restored.is_empty());
2579 assert!(m.last_input.is_empty());
2580 assert!(m.app_build.is_empty());
2581 }
2582
2583 #[test]
2584 fn cx_default_has_empty_app_info() {
2585 let cx = Cx::<Ev>::default();
2586 assert_eq!(cx.app_info(), &AppInfo::default());
2587 assert!(cx.app_info().platform.is_empty());
2588 }
2589
2590 #[test]
2591 fn cx_with_app_info_carries_it() {
2592 let cx = Cx::<Ev>::with_app_info(info("42"));
2593 assert_eq!(cx.app_info().build, "42");
2594 assert_eq!(cx.app_info().bundle_id, "rs.x");
2595 }
2596
2597 #[test]
2598 fn shell_ignores_a_malformed_fired_token() {
2599 use crux_core::App as _;
2600 let shell = MobilerShell::<CounterApp>::default();
2601 let mut m = CounterModel::default();
2602 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2605 assert_eq!(m.count, 0);
2606 }
2607
2608 #[derive(Default)]
2611 struct EffectsApp;
2612
2613 impl MobilerApp for EffectsApp {
2614 type Event = CounterEv;
2615 type Model = CounterModel;
2616 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2617 model.count += 1;
2618 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2619 cx.notify("toast", "show", "hi");
2620 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2621 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2622 }
2623 fn view(&self, model: &CounterModel) -> Widget {
2624 text(format!("{}", model.count))
2625 }
2626 }
2627
2628 #[test]
2629 fn shell_renders_before_requests_notifications_and_streams() {
2630 use crux_core::App as _;
2631 let shell = MobilerShell::<EffectsApp>::default();
2632 let mut m = CounterModel::default();
2633 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2634 let kinds: Vec<String> = cmd
2635 .effects()
2636 .map(|e| match e {
2637 Effect::Render(_) => "render".to_string(),
2638 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2639 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2640 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2641 })
2642 .collect();
2643 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2646 }
2647
2648 #[test]
2651 fn upload_builder_emits_transfer_stream_call() {
2652 let mut cx = Cx::<Ev>::default();
2653 let key = cx
2654 .upload("https://h/put", "file:///tmp/a.enc")
2655 .bearer("tok")
2656 .header("Content-Type", "application/octet-stream")
2657 .start("up-1", |_ev| Ev::Tap);
2658
2659 assert_eq!(key, "up-1");
2660 assert_eq!(cx.streams.len(), 1);
2661 let (call, _) = &cx.streams[0];
2662 assert_eq!(call.key, "up-1");
2663 assert_eq!(call.plugin, "transfer");
2664 assert_eq!(call.op, "upload");
2665
2666 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2667 assert_eq!(v["url"], "https://h/put");
2668 assert_eq!(v["source"], "file:///tmp/a.enc");
2669 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2671 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2672 assert_eq!(v["headers"][1]["name"], "Content-Type");
2673 }
2674
2675 #[test]
2676 fn download_builder_uses_dest_and_no_default_method() {
2677 let mut cx = Cx::<Ev>::default();
2678 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2679 let (call, _) = &cx.streams[0];
2680 assert_eq!(call.op, "download");
2681 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2682 assert_eq!(v["dest"], "/data/att-9.enc");
2683 assert!(v.get("source").is_none());
2684 }
2685
2686 #[test]
2687 fn start_continuation_decodes_progress_and_done() {
2688 use crate::http::HttpOutcome;
2689
2690 #[derive(Debug, PartialEq)]
2693 enum Got {
2694 Prog(u64),
2695 Done(u16),
2696 Bad,
2697 }
2698 #[derive(Debug, PartialEq)]
2699 struct GotEv(Got);
2700
2701 let mut cx = Cx::<GotEv>::default();
2702 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2703 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2704 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2705 Some(s) => Got::Done(s),
2706 None => Got::Bad,
2707 }),
2708 });
2709 let (_, cont) = &cx.streams[0];
2710
2711 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2712 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2713
2714 let done = TransferEvent::Done {
2715 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2716 handle: Some("/d".into()),
2717 };
2718 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2719 }
2720
2721 #[test]
2722 fn calendar_in_localizes_layout_and_clamps_markers() {
2723 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2725 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2726 assert_eq!(title, "Septembar 2026");
2727 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2728 assert_eq!(leading_blanks, 1);
2729 assert_eq!(on_day.len(), 30);
2730 assert_eq!(markers.len(), 30, "padded to one level per day");
2731 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2732 assert!(matches!(
2734 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2735 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2736 ));
2737 }
2738
2739 #[test]
2740 fn scroller_hint_is_opt_in() {
2741 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2742 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2743 }
2744
2745 fn copy_input(cx: &Cx<Ev>, i: usize) -> serde_json::Value {
2747 let (call, _) = &cx.requests[i];
2748 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("clipboard_with", "copy"));
2749 serde_json::from_str(&call.input).unwrap()
2750 }
2751
2752 #[test]
2753 fn copy_with_and_copy_sensitive_send_the_whole_options_object() {
2754 let mut cx = Cx::<Ev>::default();
2755 cx.copy_with("plain", CopyOptions::new(), |_| Ev::Tap);
2756 cx.copy_sensitive("JBSWY3DPEHPK3PXP", |_| Ev::Tap);
2757 cx.copy_with(
2758 "",
2759 CopyOptions::sensitive().expires_after(std::time::Duration::from_secs(30)).local_only(false),
2760 |_| Ev::Tap,
2761 );
2762 cx.copy_with("x", CopyOptions::sensitive().never_expires().mark_sensitive(false), |_| Ev::Tap);
2763 assert_eq!(copy_input(&cx, 0), serde_json::json!({"text":"plain","sensitive":false,"expires_ms":null,"local_only":false}));
2764 assert_eq!(copy_input(&cx, 1), serde_json::json!({"text":"JBSWY3DPEHPK3PXP","sensitive":true,"expires_ms":120000,"local_only":true}));
2765 assert_eq!(copy_input(&cx, 2), serde_json::json!({"text":"","sensitive":true,"expires_ms":30000,"local_only":false}));
2766 assert_eq!(copy_input(&cx, 3), serde_json::json!({"text":"x","sensitive":false,"expires_ms":null,"local_only":true}));
2767 assert!(cx.notifications.is_empty(), "copy_with is a request, never a notification");
2768 assert_eq!(CopyOptions::default(), CopyOptions::new());
2769 }
2770
2771 #[test]
2772 fn expires_after_is_clamped_and_saturates() {
2773 let mut cx = Cx::<Ev>::default();
2774 cx.copy_with("a", CopyOptions::new().expires_after(std::time::Duration::from_millis(10)), |_| Ev::Tap);
2775 cx.copy_with("b", CopyOptions::new().expires_after(std::time::Duration::MAX), |_| Ev::Tap);
2776 assert_eq!(copy_input(&cx, 0)["expires_ms"], serde_json::json!(1000));
2777 assert_eq!(copy_input(&cx, 1)["expires_ms"], serde_json::json!(u64::MAX));
2778 }
2779
2780 #[test]
2781 fn copy_with_input_round_trips_tricky_text() {
2782 let tricky = "a \"quoted\" \\ back\nslash\t🔑 ćčž";
2783 let mut cx = Cx::<Ev>::default();
2784 cx.copy_with(tricky, CopyOptions::sensitive(), |_| Ev::Tap);
2785 assert_eq!(copy_input(&cx, 0)["text"], serde_json::json!(tricky));
2786 }
2787
2788 #[test]
2790 fn plain_copy_is_unchanged_and_options_never_go_to_clipboard() {
2791 let mut cx = Cx::<Ev>::default();
2792 cx.copy("c");
2793 cx.copy_with("o", CopyOptions::sensitive(), |_| Ev::Tap);
2794 cx.copy_sensitive("s", |_| Ev::Tap);
2795 let notes: Vec<(&str, &str, &str)> =
2796 cx.notifications.iter().map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str())).collect();
2797 assert_eq!(notes, vec![("clipboard", "copy", "c")]);
2798 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "clipboard_with"));
2799 }
2800}