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