1use std::marker::PhantomData;
9
10pub mod app_info;
11pub mod bunny;
12pub mod dialog;
13pub mod format;
14pub mod http;
15pub mod i18n;
16pub mod transfer;
17pub use app_info::AppInfo;
18pub use dialog::{Confirm, Picker, Snackbar, SnackbarDuration};
19pub use format::{Currency, Locale, Weekday};
20pub use http::{HttpHeader, HttpOutcome};
21pub use i18n::{Catalog, negotiate};
22pub use transfer::TransferEvent;
23
24use crux_core::{
25 App, Command,
26 capability::Operation,
27 macros::effect,
28 render::{RenderOperation, render},
29};
30use facet::Facet;
31use serde::{Deserialize, Serialize, de::DeserializeOwned};
32
33pub use mobiler_ui::{
34 A11yRole, Action, Appearance, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
35 ChartSeries, ChartStyle, ChartTick, ColorRoles, Corner, FamilyRole, Density, Fab, FieldKind, FontFamily, Icon,
36 ImageRatio, ImageShape, InputValue, MapMarker, Palette, ProjectColor, Radius, Rgb, Rgba, Segment, Shapes, Sheet, ShellLabels, Spacing, SwipeButton, Tab,
37 TextStyle, Theme, Tone, TonePair, TypeScale, TypeSpec, Widget,
38};
39
40#[effect(facet_typegen)]
44#[derive(Debug)]
45pub enum Effect {
46 Render(RenderOperation),
47 PluginNotify(PluginNotify),
49 Plugin(PluginCall),
51 PluginStream(PluginStreamCall),
56}
57
58#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
59pub struct PluginNotify {
60 pub plugin: String,
61 pub op: String,
62 pub input: String,
63}
64impl Operation for PluginNotify {
65 type Output = ();
66}
67
68#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
69pub struct PluginCall {
70 pub plugin: String,
71 pub op: String,
72 pub input: String,
73}
74impl Operation for PluginCall {
75 type Output = PluginResponse;
76}
77
78#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginStreamCall {
83 pub key: String,
84 pub plugin: String,
85 pub op: String,
86 pub input: String,
87}
88impl Operation for PluginStreamCall {
89 type Output = PluginResponse;
90}
91
92#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
101pub struct PluginResponse {
102 pub ok: bool,
103 pub output: Vec<u8>,
104}
105
106impl PluginResponse {
107 pub fn text(ok: bool, s: impl Into<String>) -> Self {
109 Self { ok, output: s.into().into_bytes() }
110 }
111
112 pub fn as_text(&self) -> Option<&str> {
114 std::str::from_utf8(&self.output).ok()
115 }
116}
117
118type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
119type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
121
122pub struct Cx<E> {
125 notifications: Vec<PluginNotify>,
126 requests: Vec<(PluginCall, Continuation<E>)>,
127 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
128 app_info: AppInfo,
129}
130
131impl<E> Default for Cx<E> {
132 fn default() -> Self {
133 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new(), app_info: AppInfo::default() }
134 }
135}
136
137impl<E> Cx<E> {
138 #[must_use]
140 pub fn with_app_info(info: AppInfo) -> Self {
141 Self { app_info: info, ..Self::default() }
142 }
143
144 #[must_use]
149 pub fn app_info(&self) -> &AppInfo {
150 &self.app_info
151 }
152
153 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
155 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
156 }
157
158 pub fn plugin(
161 &mut self,
162 plugin: impl Into<String>,
163 op: impl Into<String>,
164 input: impl Into<String>,
165 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
166 ) {
167 self.requests
168 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
169 }
170
171 pub fn subscribe(
179 &mut self,
180 key: impl Into<String>,
181 plugin: impl Into<String>,
182 op: impl Into<String>,
183 input: impl Into<String>,
184 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
185 ) {
186 self.streams.push((
187 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
188 Box::new(on_event),
189 ));
190 }
191
192 pub fn unsubscribe(&mut self, key: impl Into<String>) {
196 self.notify("stream", "unsubscribe", key);
197 }
198
199 pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
202 crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
203 }
204
205 pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
208 crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
209 }
210
211 pub fn save(&mut self, data: impl Into<String>) {
217 self.notify("storage", "save", data);
218 }
219
220 pub fn copy(&mut self, text: impl Into<String>) {
222 self.notify("clipboard", "copy", text);
223 }
224
225 pub fn share(&mut self, text: impl Into<String>) {
227 self.notify("share", "text", text);
228 }
229
230 pub fn open_url(&mut self, url: impl Into<String>) {
233 self.notify("browser", "open", url);
234 }
235
236 pub fn open_url_then(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
243 self.plugin("browser", "open", url, then);
244 }
245
246 pub fn toast(&mut self, text: impl Into<String>) {
248 self.notify("toast", "show", text);
249 }
250
251 pub fn haptic(&mut self, style: impl Into<String>) {
254 self.notify("haptics", style, "");
255 }
256
257 pub fn request(
272 &mut self,
273 method: impl Into<String>,
274 url: impl Into<String>,
275 ) -> crate::http::RequestBuilder<'_, E> {
276 crate::http::RequestBuilder::new(self, method.into(), url.into())
277 }
278
279 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
281 self.request("GET", url).send(then);
282 }
283 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
285 self.request("POST", url).body(body).send(then);
286 }
287 pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
289 self.request("PUT", url).body(body).send(then);
290 }
291 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
293 self.request("PATCH", url).body(body).send(then);
294 }
295 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
297 self.request("DELETE", url).send(then);
298 }
299
300 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
304 self.plugin("device", "model", "", then);
305 }
306
307 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
312 self.plugin("device", "locale", "", then);
313 }
314
315 pub fn system_appearance(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
318 self.plugin("device", "appearance", "", then);
319 }
320
321 pub fn subscribe_appearance(&mut self, key: impl Into<String>, on_event: impl Fn(PluginResponse) -> E + Send + 'static) {
324 self.subscribe(key, "appearance", "changes", "", on_event);
325 }
326
327 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
332 self.plugin("photo", "pick", "", then);
333 }
334
335 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
342 self.plugin("camera", "capture", "", then);
343 }
344
345 pub fn confirm(
349 &mut self,
350 title: impl Into<String>,
351 message: impl Into<String>,
352 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
353 ) {
354 self.confirm_with(Confirm::new(title, message), then);
355 }
356
357 pub fn confirm_with(&mut self, dialog: Confirm, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
361 self.plugin("dialog", "confirm", dialog.to_input(), then);
362 }
363
364 pub fn snackbar(&mut self, snackbar: Snackbar, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
370 self.plugin("snackbar", "show", snackbar.to_input(), then);
371 }
372
373 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
378 self.plugin("datetime", "date", "", then);
379 }
380
381 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
386 self.plugin("datetime", "time", "", then);
387 }
388
389 pub fn pick_date_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
391 self.plugin("datetime", "date", picker.to_input(), then);
392 }
393
394 pub fn pick_time_with(&mut self, picker: Picker, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
396 self.plugin("datetime", "time", picker.to_input(), then);
397 }
398
399 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
406 self.plugin("datetime", "now", "", then);
407 }
408}
409
410pub trait MobilerApp: Default {
415 type Event: Serialize + DeserializeOwned + Send + 'static;
416 type Model: Default;
417
418 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
419
420 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
421 let _ = (id, value, model, cx);
422 }
423
424 fn restore(&self, data: &str, model: &mut Self::Model) {
427 let _ = (data, model);
428 }
429
430 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
433 let _ = (model, cx);
434 }
435
436 fn view(&self, model: &Self::Model) -> Widget;
437}
438
439pub struct MobilerShell<A>(PhantomData<fn() -> A>);
441
442impl<A> Default for MobilerShell<A> {
443 fn default() -> Self {
444 Self(PhantomData)
445 }
446}
447
448impl<A: MobilerApp> App for MobilerShell<A> {
449 type Event = Action;
450 type Model = A::Model;
451 type ViewModel = Widget;
452 type Effect = Effect;
453
454 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
455 let app = A::default();
456 let mut cx = Cx::<A::Event>::with_app_info(app_info::get());
457 match action {
458 Action::Fired { token } => {
459 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
460 app.update(event, model, &mut cx);
461 }
462 }
463 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
464 Action::Restore { data } => app.restore(&data, model),
465 Action::Start => app.init(model, &mut cx),
466 Action::AppInfo { version, build, platform, bundle_id } => {
467 app_info::set(AppInfo { version, build, platform, bundle_id });
468 }
469 }
470 let mut commands: Vec<Command<Effect, Action>> = vec![render()];
476 for op in cx.notifications {
477 commands.push(Command::notify_shell(op).build());
478 }
479 for (op, then) in cx.requests {
480 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
481 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
482 }));
483 }
484 for (op, then) in cx.streams {
485 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
488 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
489 }));
490 }
491 Command::all(commands)
492 }
493
494 fn view(&self, model: &Self::Model) -> Widget {
495 A::default().view(model)
496 }
497}
498
499#[derive(Clone, Debug)]
518pub struct Nav<R> {
519 stack: Vec<R>,
520}
521
522impl<R: Clone + Serialize> Nav<R> {
523 #[must_use]
525 pub fn new(root: R) -> Self {
526 Self { stack: vec![root] }
527 }
528 pub fn push(&mut self, route: R) {
530 self.stack.push(route);
531 }
532 pub fn pop(&mut self) {
534 if self.stack.len() > 1 {
535 self.stack.pop();
536 }
537 }
538 pub fn reset(&mut self, root: R) {
540 self.stack = vec![root];
541 }
542 #[must_use]
544 pub fn current(&self) -> &R {
545 self.stack.last().expect("nav stack is never empty")
546 }
547 #[must_use]
549 pub fn depth(&self) -> u32 {
550 self.stack.len() as u32
551 }
552 #[must_use]
554 pub fn can_go_back(&self) -> bool {
555 self.stack.len() > 1
556 }
557 fn route_key(&self) -> String {
560 serde_json::to_string(self.current()).expect("serialize route")
561 }
562}
563
564fn tok<E: Serialize>(event: E) -> String {
568 serde_json::to_string(&event).expect("serialize event")
569}
570
571#[must_use]
572pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
573 Widget::Text { content: content.into(), style }
574}
575#[must_use]
576pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
577#[must_use]
578pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
579#[must_use]
580pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
581#[must_use]
582pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
583#[must_use]
584pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
585#[must_use]
588pub fn display(content: impl Into<String>) -> Widget { styled(content, TextStyle::Display) }
589#[must_use]
591pub fn headline(content: impl Into<String>) -> Widget { styled(content, TextStyle::Headline) }
592
593#[must_use]
594pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
595 Widget::Image { source: source.into(), shape, ratio }
596}
597#[must_use]
598pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
599 Widget::Badge { label: label.into(), tone, icon: None }
600}
601#[must_use]
603pub fn color_dot(color: ProjectColor) -> Widget {
604 Widget::ColorDot { color }
605}
606#[must_use]
607pub fn divider() -> Widget { Widget::Divider }
608#[must_use]
610pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
611#[must_use]
613pub fn skeleton() -> Widget { Widget::Skeleton }
614#[must_use]
618pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
619#[must_use]
628pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
629 Widget::Video {
630 url: url.into(),
631 id: id.into(),
632 playing,
633 seek_to_ms,
634 controls: true,
635 looping: false,
636 muted: false,
637 on_ended: Some(tok(on_ended)),
638 poster: None,
639 start_at_ms: -1,
640 captions: Vec::new(),
641 rate: 1.0,
642 volume: 1.0,
643 urls: Vec::new(),
644 start_index: 0,
645 seek_index: -1,
646 allow_pip: false,
647 }
648}
649#[must_use]
655pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
656 Widget::Video {
657 url: urls.first().cloned().unwrap_or_default(),
658 id: id.into(),
659 playing,
660 seek_to_ms: -1,
661 controls: true,
662 looping: false,
663 muted: false,
664 on_ended: Some(tok(on_ended)),
665 poster: None,
666 start_at_ms: -1,
667 captions: Vec::new(),
668 rate: 1.0,
669 volume: 1.0,
670 urls,
671 start_index,
672 seek_index: -1,
673 allow_pip: false,
674 }
675}
676fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
679 match widget {
680 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
681 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
682 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
683 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
684 f(&mut v);
685 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
686 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
687 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
688 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
689 allow_pip: v.allow_pip }
690 }
691 other => other,
692 }
693}
694struct VideoFields {
695 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
696 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
697 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
698 seek_index: i64, allow_pip: bool,
699}
700#[must_use]
702pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
703#[must_use]
705pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
706#[must_use]
708pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
709#[must_use]
711pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
712 let poster = poster.into();
713 map_video(widget, move |v| v.poster = Some(poster))
714}
715#[must_use]
717pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
718 map_video(widget, move |v| v.start_at_ms = start_at_ms)
719}
720#[must_use]
722pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
723 map_video(widget, move |v| v.captions = captions)
724}
725#[must_use]
727pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
728#[must_use]
730pub fn with_volume(widget: Widget, volume: f32) -> Widget {
731 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
732}
733#[must_use]
735pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
736 map_video(widget, move |v| v.seek_index = index)
737}
738#[must_use]
740pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
741#[must_use]
746pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
747
748#[must_use]
754pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
755 Widget::Map {
756 id: id.into(),
757 center_lat,
758 center_lng,
759 zoom,
760 markers: Vec::new(),
761 style_url: None,
762 interactive: true,
763 }
764}
765#[must_use]
767pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
768 match widget {
769 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
770 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
771 other => other,
772 }
773}
774#[must_use]
776pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
777 match widget {
778 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
779 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
780 other => other,
781 }
782}
783#[must_use]
785pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
786 MapMarker { id: id.into(), lat, lng, title: None }
787}
788#[must_use]
790pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
791 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
792}
793fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
795 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
796}
797
798#[must_use]
801pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
802 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
803}
804#[must_use]
807pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
808 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
809}
810#[must_use]
814pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
815 Widget::Chart { series, labels, style, axis, legend }
816}
817#[must_use]
819pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
820 chart(series, labels, ChartStyle::StackedBar, true, true)
821}
822#[must_use]
824pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
825 chart(series, labels, ChartStyle::StackedBar100, false, true)
826}
827#[must_use]
829pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
830 chart(series, vec![], ChartStyle::Pie, false, true)
831}
832#[must_use]
834pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
835 chart(series, vec![], ChartStyle::Donut, false, true)
836}
837#[must_use]
840pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
841 chart(series, vec![], ChartStyle::Rings, false, true)
842}
843#[must_use]
845pub fn gauge_chart(series: ChartSeries) -> Widget {
846 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
847}
848
849#[must_use]
854pub fn region_chart(
855 regions: Vec<ChartRegion>,
856 ticks: Vec<ChartTick>,
857 x_max: f32,
858 y_max: f32,
859 ref_lines: Vec<ChartRefLine>,
860 legend: Vec<ChartLegendItem>,
861) -> Widget {
862 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
863}
864
865#[must_use]
867pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
868 match widget {
869 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
870 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
871 }
872 other => other,
873 }
874}
875
876fn days_in_month(year: u32, month: u8) -> u8 {
878 match month {
879 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
880 4 | 6 | 9 | 11 => 30,
881 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
882 _ => 30,
883 }
884}
885
886fn weekday(year: u32, month: u8, day: u8) -> u8 {
888 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
889 let y = if month < 3 { year - 1 } else { year };
890 let m = month as usize - 1;
891 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
892}
893
894#[must_use]
898pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
899 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
900}
901
902#[must_use]
907pub fn calendar_in<E: Serialize>(
908 locale: Locale,
909 year: u32,
910 month: u8,
911 selected: Option<u8>,
912 markers: &[u8],
913 on_day: impl Fn(u8) -> E,
914) -> Widget {
915 let n = days_in_month(year, month);
916 let start = locale.week_start().sun0();
917 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
918 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
919 let markers = if markers.is_empty() {
920 Vec::new()
921 } else {
922 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
923 };
924 Widget::Calendar {
925 year,
926 month,
927 title: format::month_year(year, u32::from(month), locale),
928 weekday_labels,
929 leading_blanks,
930 selected,
931 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
932 markers,
933 }
934}
935
936#[must_use]
939pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
940 Widget::SwipeAction {
941 child: Box::new(child),
942 actions: actions
943 .into_iter()
944 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
945 .collect(),
946 }
947}
948#[must_use]
949pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
950
951#[must_use]
952pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
953#[must_use]
954pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
955#[must_use]
956pub fn card(child: Widget, style: CardStyle) -> Widget {
957 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
958}
959#[must_use]
961pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
962 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
963}
964#[must_use]
968pub fn with_icon(widget: Widget, icon: Icon) -> Widget {
969 match widget {
970 Widget::Badge { label, tone, .. } => Widget::Badge { label, tone, icon: Some(icon) },
971 other => other,
972 }
973}
974
975#[must_use]
979pub fn with_initials(widget: Widget, initials: impl Into<String>) -> Widget {
980 match widget {
981 Widget::Avatar { source, status, size, .. } => Widget::Avatar { source, status, initials: Some(initials.into()), size },
982 other => other,
983 }
984}
985
986#[must_use]
989pub fn with_avatar_size(widget: Widget, size: u8) -> Widget {
990 match widget {
991 Widget::Avatar { source, status, initials, .. } => Widget::Avatar { source, status, initials, size: Some(size) },
992 other => other,
993 }
994}
995
996#[must_use]
999pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
1000 match widget {
1001 Widget::Card { child, style, on_press, .. } => Widget::Card {
1002 child,
1003 style,
1004 on_press,
1005 on_long_press: Some(tok(on_long_press)),
1006 },
1007 other => other,
1008 }
1009}
1010#[must_use]
1013pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
1014 Widget::Box { children, align, scrim }
1015}
1016#[must_use]
1021pub fn steps(total: u8, current: u8) -> Widget {
1022 Widget::Steps { total, current: current.min(total), caption: false }
1023}
1024
1025#[must_use]
1028pub fn with_step_caption(widget: Widget) -> Widget {
1029 match widget {
1030 Widget::Steps { total, current, .. } => Widget::Steps { total, current, caption: true },
1031 other => other,
1032 }
1033}
1034
1035#[must_use]
1038pub fn step_text(template: Option<&str>, current: u8, total: u8) -> String {
1039 let t = template.filter(|t| !t.is_empty()).unwrap_or("Step {current} of {total}");
1040 t.replace("{current}", ¤t.to_string()).replace("{total}", &total.to_string())
1041}
1042
1043#[must_use]
1044pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children, columns: None } }
1045#[must_use]
1048pub fn with_columns(widget: Widget, columns: u8) -> Widget {
1049 match widget {
1050 Widget::Grid { children, .. } => Widget::Grid { children, columns: Some(columns.clamp(1, 4)) },
1051 other => other,
1052 }
1053}
1054#[must_use]
1059pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
1060 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
1061}
1062#[must_use]
1064pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
1065#[must_use]
1067pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
1068#[must_use]
1070pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None, initials: None, size: None } }
1071#[must_use]
1073pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
1074 Widget::Avatar { source: source.into(), status: Some(status), initials: None, size: None }
1075}
1076#[must_use]
1078pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
1079#[must_use]
1081pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
1082 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
1083}
1084
1085#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1093pub struct ButtonOpts {
1094 pub tone: Tone,
1095 pub icon: Option<Icon>,
1096 pub wide: bool,
1097}
1098
1099impl Default for ButtonOpts {
1100 fn default() -> Self {
1101 Self { tone: Tone::Neutral, icon: None, wide: false }
1102 }
1103}
1104
1105impl ButtonOpts {
1106 #[must_use]
1108 pub const fn tone(mut self, tone: Tone) -> Self {
1109 self.tone = tone;
1110 self
1111 }
1112 #[must_use]
1114 pub const fn icon(mut self, icon: Icon) -> Self {
1115 self.icon = Some(icon);
1116 self
1117 }
1118 #[must_use]
1120 pub const fn wide(mut self) -> Self {
1121 self.wide = true;
1122 self
1123 }
1124}
1125
1126#[must_use]
1127pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
1128 button_with(label, style, on_press, ButtonOpts::default())
1129}
1130
1131#[must_use]
1133pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
1134 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
1135}
1136#[must_use]
1137pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
1138 Widget::IconButton { icon, on_press: tok(on_press) }
1139}
1140#[must_use]
1141pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
1142 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1143}
1144#[must_use]
1145pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1146 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1147}
1148#[must_use]
1152pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1153 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1154}
1155#[must_use]
1157pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1158 field(id, placeholder, value, FieldKind::Secure, None)
1159}
1160#[must_use]
1162pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1163 field(id, placeholder, value, FieldKind::Email, None)
1164}
1165#[must_use]
1167pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1168 field(id, placeholder, value, FieldKind::Number, None)
1169}
1170#[must_use]
1172pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1173 field(id, placeholder, value, FieldKind::Decimal, None)
1174}
1175#[must_use]
1177pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1178 field(id, placeholder, value, FieldKind::Phone, None)
1179}
1180#[must_use]
1182pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1183 field(id, placeholder, value, FieldKind::Url, None)
1184}
1185#[must_use]
1187pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1188 field(id, placeholder, value, FieldKind::Multiline, None)
1189}
1190#[must_use]
1193pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1194 match widget {
1195 Widget::TextField { id, placeholder, value, kind, .. } =>
1196 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1197 other => other,
1198 }
1199}
1200
1201#[must_use]
1205pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1206 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1207}
1208#[must_use]
1211pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1212 match widget {
1213 Widget::A11y { child, label, role, .. } =>
1214 Widget::A11y { child, label, hint: Some(hint.into()), role },
1215 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1216 }
1217}
1218#[must_use]
1220pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1221 match widget {
1222 Widget::A11y { child, label, hint, .. } =>
1223 Widget::A11y { child, label, hint, role: Some(role) },
1224 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1225 }
1226}
1227#[must_use]
1229pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1230 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1231}
1232#[must_use]
1234pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1235 Segment { label: label.into(), selected, on_select: tok(on_select) }
1236}
1237#[must_use]
1239pub fn segmented(segments: Vec<Segment>) -> Widget {
1240 Widget::Segmented { segments }
1241}
1242#[must_use]
1243pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1244 Widget::Toggle { id: id.into(), label: label.into(), value }
1245}
1246#[must_use]
1247pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1248 Widget::Checkbox { id: id.into(), label: label.into(), value }
1249}
1250#[must_use]
1251pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1252 Widget::Slider { id: id.into(), value, max }
1253}
1254#[must_use]
1255pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1256 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1257}
1258
1259#[must_use]
1261pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1262 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1263}
1264
1265#[must_use]
1267pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1268 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1269}
1270
1271#[must_use]
1274pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1275 let title = title.into();
1276 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 }
1278}
1279
1280#[must_use]
1284pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1285 let title = title.into();
1286 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 }
1287}
1288
1289#[must_use]
1294pub fn nav_scaffold<R, E>(
1295 title: impl Into<String>,
1296 dark_mode: bool,
1297 tabs: Vec<Tab>,
1298 body: Widget,
1299 nav: &Nav<R>,
1300 on_back: E,
1301) -> Widget
1302where
1303 R: Clone + Serialize,
1304 E: Serialize,
1305{
1306 Widget::Scaffold {
1307 title: title.into(),
1308 body: Box::new(body),
1309 tabs,
1310 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1311 dark_mode,
1312 theme: None,
1313 fab: None,
1314 sheet: None,
1315 on_refresh: None,
1316 refreshing: false,
1317 route: nav.route_key(),
1318 depth: nav.depth(),
1319 labels: None,
1320 appearance: None,
1321 bottom_bar: None,
1322 }
1323}
1324
1325pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1329 match widget {
1330 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1331 title,
1332 body,
1333 tabs,
1334 back,
1335 dark_mode,
1336 theme: Some(theme),
1337 fab,
1338 sheet,
1339 on_refresh,
1340 refreshing,
1341 route,
1342 depth,
1343 labels,
1344 appearance,
1345 bottom_bar,
1346 },
1347 other => other,
1348 }
1349}
1350
1351pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1354 set_fab(widget, Fab { icon, on_press: tok(on_press), label: None })
1355}
1356
1357pub fn with_extended_fab<E: Serialize>(widget: Widget, icon: Icon, label: impl Into<String>, on_press: E) -> Widget {
1361 set_fab(widget, Fab { icon, on_press: tok(on_press), label: Some(label.into()) })
1362}
1363
1364#[must_use]
1371pub fn with_bottom_bar(widget: Widget, children: Vec<Widget>) -> Widget {
1372 match widget {
1373 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, .. } => {
1374 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar: Some(children) }
1375 }
1376 other => other,
1377 }
1378}
1379
1380fn set_fab(widget: Widget, fab: Fab) -> Widget {
1381 match widget {
1382 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1383 title,
1384 body,
1385 tabs,
1386 back,
1387 dark_mode,
1388 theme,
1389 fab: Some(fab),
1390 sheet,
1391 on_refresh,
1392 refreshing,
1393 route,
1394 depth,
1395 labels,
1396 appearance,
1397 bottom_bar,
1398 },
1399 other => other,
1400 }
1401}
1402
1403pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1406 match widget {
1407 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1408 title: t,
1409 body,
1410 tabs,
1411 back,
1412 dark_mode,
1413 theme,
1414 fab,
1415 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1416 on_refresh,
1417 refreshing,
1418 route,
1419 depth,
1420 labels,
1421 appearance,
1422 bottom_bar,
1423 },
1424 other => other,
1425 }
1426}
1427
1428pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1432 match widget {
1433 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, labels, appearance, bottom_bar, .. } => Widget::Scaffold {
1434 title,
1435 body,
1436 tabs,
1437 back,
1438 dark_mode,
1439 theme,
1440 fab,
1441 sheet,
1442 on_refresh: Some(tok(on_refresh)),
1443 refreshing,
1444 route,
1445 depth,
1446 labels,
1447 appearance,
1448 bottom_bar,
1449 },
1450 Widget::LazyList { children, on_load_more, loading, has_more, end_label, fill, .. } => Widget::LazyList {
1453 children,
1454 on_load_more,
1455 loading,
1456 has_more,
1457 on_refresh: Some(tok(on_refresh)),
1458 refreshing,
1459 end_label,
1460 fill,
1461 },
1462 other => other,
1463 }
1464}
1465
1466#[must_use]
1471pub fn with_labels(widget: Widget, labels: ShellLabels) -> Widget {
1472 match widget {
1473 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, appearance, bottom_bar, .. } => {
1474 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: Some(labels), appearance, bottom_bar }
1475 }
1476 other => other,
1477 }
1478}
1479
1480#[must_use]
1488pub fn with_appearance(widget: Widget, appearance: Appearance) -> Widget {
1489 match widget {
1490 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, bottom_bar, .. } => {
1491 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels, appearance: Some(appearance), bottom_bar }
1492 }
1493 other => other,
1494 }
1495}
1496
1497#[must_use]
1503pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1504 Widget::LazyList {
1505 children,
1506 on_load_more: Some(tok(on_load_more)),
1507 loading,
1508 has_more,
1509 on_refresh: None,
1510 refreshing: false,
1511 end_label: None,
1512 fill: false,
1513 }
1514}
1515
1516#[must_use]
1518pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1519 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: None, fill: false }
1520}
1521
1522#[must_use]
1526pub fn with_end_label(widget: Widget, label: impl Into<String>) -> Widget {
1527 match widget {
1528 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, fill, .. } => {
1529 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label: Some(label.into()), fill }
1530 }
1531 other => other,
1532 }
1533}
1534
1535#[must_use]
1540pub fn with_fill(widget: Widget) -> Widget {
1541 match widget {
1542 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, .. } => {
1543 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label, fill: true }
1544 }
1545 other => other,
1546 }
1547}
1548
1549#[cfg(test)]
1550mod tests {
1551 use super::*;
1552 use serde::Serialize;
1553
1554 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1555 enum Route {
1556 Home,
1557 Detail(u32),
1558 }
1559
1560 #[derive(Serialize)]
1561 enum Ev {
1562 Tap,
1563 Open(u32),
1564 }
1565
1566 #[test]
1569 fn plugin_response_carries_bytes_and_converts_text() {
1570 let r = PluginResponse::text(true, "hello");
1571 assert!(r.ok);
1572 assert_eq!(r.output, b"hello".to_vec());
1573 assert_eq!(r.as_text(), Some("hello"));
1574
1575 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1576 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1577 }
1578
1579 #[test]
1582 fn nav_push_pop_depth() {
1583 let mut nav = Nav::new(Route::Home);
1584 assert_eq!(nav.depth(), 1);
1585 assert!(!nav.can_go_back());
1586
1587 nav.push(Route::Detail(7));
1588 assert_eq!(nav.depth(), 2);
1589 assert!(nav.can_go_back());
1590 assert!(matches!(nav.current(), Route::Detail(7)));
1591
1592 nav.pop();
1593 assert_eq!(nav.depth(), 1);
1594 assert!(matches!(nav.current(), Route::Home));
1595
1596 nav.pop(); assert_eq!(nav.depth(), 1);
1598 }
1599
1600 #[test]
1601 fn nav_reset_replaces_stack() {
1602 let mut nav = Nav::new(Route::Home);
1603 nav.push(Route::Detail(1));
1604 nav.push(Route::Detail(2));
1605 nav.reset(Route::Detail(9));
1606 assert_eq!(nav.depth(), 1);
1607 assert!(matches!(nav.current(), Route::Detail(9)));
1608 }
1609
1610 #[test]
1611 fn nav_route_key_is_serialization() {
1612 let nav = Nav::new(Route::Detail(3));
1613 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1614 }
1615
1616 #[test]
1619 fn scaffold_sets_route_depth_and_no_back() {
1620 match scaffold("Home", false, vec![], text("x")) {
1621 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1622 assert_eq!(route, "Home");
1623 assert_eq!(depth, 1);
1624 assert!(back.is_none());
1625 assert!(!dark_mode);
1626 }
1627 other => panic!("expected Scaffold, got {other:?}"),
1628 }
1629 }
1630
1631 #[test]
1632 fn scaffold_back_is_depth_2_with_back() {
1633 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1634 Widget::Scaffold { depth, back, dark_mode, .. } => {
1635 assert_eq!(depth, 2);
1636 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1637 assert!(dark_mode);
1638 }
1639 other => panic!("expected Scaffold, got {other:?}"),
1640 }
1641 }
1642
1643 #[test]
1644 fn nav_scaffold_shows_back_only_when_poppable() {
1645 let mut nav = Nav::new(Route::Home);
1646 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1648 Widget::Scaffold { back, depth, route, .. } => {
1649 assert!(back.is_none());
1650 assert_eq!(depth, 1);
1651 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1652 }
1653 other => panic!("expected Scaffold, got {other:?}"),
1654 }
1655 nav.push(Route::Detail(2));
1657 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1658 Widget::Scaffold { back, depth, .. } => {
1659 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1660 assert_eq!(depth, 2);
1661 }
1662 other => panic!("expected Scaffold, got {other:?}"),
1663 }
1664 }
1665
1666 #[test]
1667 fn with_labels_sets_scaffold_labels_and_combinators_keep_them() {
1668 let l = ShellLabels::new().back("Nazad").ok("U redu");
1669 assert!(matches!(scaffold("T", false, vec![], text("b")), Widget::Scaffold { labels: None, .. }));
1670 let s = with_labels(scaffold("T", false, vec![], text("b")), l.clone());
1671 assert!(matches!(&s, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1672 let themed = with_theme(s.clone(), Theme { seed: Rgb::new(1, 2, 3), ..Default::default() });
1674 assert!(matches!(&themed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1675 let refreshed = with_refresh(s.clone(), false, Ev::Tap);
1676 assert!(matches!(&refreshed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1677 let fabbed = with_fab(s.clone(), Icon::Calendar, Ev::Tap);
1678 assert!(matches!(&fabbed, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1679 let sheeted = with_sheet(s, "Sheet", text("c"), Ev::Tap);
1680 assert!(matches!(&sheeted, Widget::Scaffold { labels: Some(x), .. } if *x == l));
1681 assert!(matches!(with_labels(text("x"), ShellLabels::new()), Widget::Text { .. }));
1683 assert_eq!(ShellLabels::new().done("Gotovo"), ShellLabels { done: Some("Gotovo".into()), ..ShellLabels::default() });
1685 let nav = Nav::new(Route::Home);
1687 assert!(matches!(nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap), Widget::Scaffold { labels: None, .. }));
1688 }
1689
1690 #[test]
1691 fn button_with_carries_tone_icon_and_width() {
1692 assert!(matches!(
1693 button("Go", ButtonStyle::Filled, Ev::Tap),
1694 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1695 ));
1696 assert!(matches!(
1697 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1698 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1699 ));
1700 }
1701
1702 #[test]
1703 fn buttons_carry_serialized_event_tokens() {
1704 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1705 Widget::Button { label, on_press, .. } => {
1706 assert_eq!(label, "Go");
1707 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1708 }
1709 other => panic!("expected Button, got {other:?}"),
1710 }
1711 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1712 Widget::Card { on_press, .. } => {
1713 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1714 }
1715 other => panic!("expected Card, got {other:?}"),
1716 }
1717 match card(text("c"), CardStyle::Elevated) {
1719 Widget::Card { on_press, on_long_press, .. } => {
1720 assert!(on_press.is_none());
1721 assert!(on_long_press.is_none());
1722 }
1723 other => panic!("expected Card, got {other:?}"),
1724 }
1725 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1727 Widget::Card { on_press, on_long_press, .. } => {
1728 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1729 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1730 }
1731 other => panic!("expected Card, got {other:?}"),
1732 }
1733 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1735 }
1736
1737 #[test]
1740 fn cx_notify_and_save_enqueue_notifications() {
1741 let mut cx = Cx::<Ev>::default();
1742 cx.notify("toast", "show", "hi");
1743 cx.save("blob");
1744 assert_eq!(cx.notifications.len(), 2);
1745 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1746 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1747 assert!(cx.requests.is_empty());
1748 }
1749
1750 #[test]
1751 fn cx_http_helpers_build_requests() {
1752 let mut cx = Cx::<Ev>::default();
1753 cx.get("http://h/x", |_| Ev::Tap);
1754 cx.post("http://h/y", "hello", |_| Ev::Tap);
1755 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1756 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1757 cx.delete("http://h/d", |_| Ev::Tap);
1758
1759 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1760 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1761 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1762
1763 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1764 assert_eq!(get_input["url"], "http://h/x");
1765 assert!(get_input["body"].is_null());
1766
1767 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1768 assert_eq!(put_input["url"], "http://h/p");
1769 assert_eq!(put_input["body"], "putbody");
1770 }
1771
1772 #[test]
1773 fn request_builder_emits_headers_in_order() {
1774 let mut cx = Cx::<Ev>::default();
1775 cx.request("PUT", "http://h/access-key")
1776 .bearer("tok123")
1777 .header("X-Trace-Id", "abc")
1778 .body("{}")
1779 .send(|_| Ev::Tap);
1780
1781 assert_eq!(cx.requests.len(), 1);
1782 let (call, _) = &cx.requests[0];
1783 assert_eq!(call.plugin, "http");
1784 assert_eq!(call.op, "PUT");
1785
1786 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1787 assert_eq!(input["url"], "http://h/access-key");
1788 assert_eq!(input["body"], "{}");
1789 assert_eq!(input["headers"][0]["name"], "Authorization");
1790 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1791 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1792 assert_eq!(input["headers"][1]["value"], "abc");
1793 }
1794
1795 #[test]
1796 fn helpers_emit_no_headers_field_content() {
1797 let mut cx = Cx::<Ev>::default();
1798 cx.get("http://h/x", |_| Ev::Tap);
1799 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1800 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1801 }
1802
1803 #[test]
1804 fn continuation_receives_decoded_outcome() {
1805 #[derive(Debug, PartialEq)]
1806 enum Got { Conflict, Offline, Other }
1807
1808 let classify = |r: PluginResponse| -> Got {
1809 match HttpOutcome::decode(&r.output).unwrap() {
1810 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1811 HttpOutcome::TransportError { .. } => Got::Offline,
1812 _ => Got::Other,
1813 }
1814 };
1815
1816 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1817 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1818
1819 let offline = HttpOutcome::TransportError { message: "refused".into() };
1820 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1821 }
1822
1823 #[test]
1824 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1825 let mut cx = Cx::<Ev>::default();
1830
1831 cx.request("GET", "http://h/x").send(|outcome| {
1832 match outcome {
1833 HttpOutcome::TransportError { message } => {
1834 assert!(
1835 message.contains("malformed http response"),
1836 "unexpected message: {message}"
1837 );
1838 }
1839 HttpOutcome::Response { .. } => {
1840 panic!("garbage bytes must not decode as a Response")
1841 }
1842 }
1843 Ev::Tap
1844 });
1845
1846 assert_eq!(cx.requests.len(), 1);
1847 let (_, continuation) = cx.requests.remove(0);
1848 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1851 }
1852
1853 #[test]
1854 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1855 let mut cx = Cx::<Ev>::default();
1856 cx.pick_photo(|_| Ev::Tap);
1857 cx.capture_photo(|_| Ev::Tap);
1858 assert_eq!(cx.requests.len(), 2);
1859 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", ""));
1862 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", ""));
1863 }
1864
1865 #[test]
1866 fn cx_capture_photo_routes_success_and_cancel() {
1867 let mut cx = Cx::<Ev>::default();
1869 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1870 let (_, then) = cx.requests.pop().unwrap();
1871 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1872
1873 let mut cx = Cx::<Ev>::default();
1875 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1876 let (_, then) = cx.requests.pop().unwrap();
1877 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1878 }
1879
1880 #[test]
1881 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1882 let mut cx = Cx::<Ev>::default();
1883 cx.copy("c");
1884 cx.share("s");
1885 cx.open_url("u");
1886 cx.toast("t");
1887 cx.haptic("heavy");
1888 let got: Vec<(&str, &str, &str)> = cx
1889 .notifications
1890 .iter()
1891 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1892 .collect();
1893 assert_eq!(
1894 got,
1895 vec![
1896 ("clipboard", "copy", "c"),
1897 ("share", "text", "s"),
1898 ("browser", "open", "u"),
1899 ("toast", "show", "t"),
1900 ("haptics", "heavy", ""), ]
1902 );
1903 assert!(cx.requests.is_empty());
1904 }
1905
1906 #[test]
1907 fn display_and_headline_builders() {
1908 assert!(matches!(display("x"), Widget::Text { style: TextStyle::Display, .. }));
1909 assert!(matches!(headline("x"), Widget::Text { style: TextStyle::Headline, .. }));
1910 let _ = (TypeScale::default(), TypeSpec::new(16, 400, FamilyRole::Body));
1911 }
1912
1913 #[test]
1914 fn with_appearance_sets_it_on_a_scaffold_and_ignores_other_roots() {
1915 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::System);
1916 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::System), .. }));
1917 assert!(matches!(scaffold("T", true, vec![], text("x")), Widget::Scaffold { appearance: None, .. }));
1918 assert!(matches!(with_appearance(text("x"), Appearance::Dark), Widget::Text { .. }));
1919 }
1920
1921 #[test]
1922 fn with_theme_and_labels_keep_the_appearance() {
1923 let s = with_appearance(scaffold("T", false, vec![], text("x")), Appearance::Light);
1924 let s = with_labels(with_theme(s, Theme::default()), ShellLabels::default());
1925 assert!(matches!(s, Widget::Scaffold { appearance: Some(Appearance::Light), .. }));
1926 }
1927
1928 #[test]
1929 fn appearance_query_and_stream_shapes() {
1930 let mut cx = Cx::<Ev>::default();
1931 cx.system_appearance(|_| Ev::Tap);
1932 let (call, _) = &cx.requests[0];
1933 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "appearance", ""));
1934 cx.subscribe_appearance("appr", |_| Ev::Tap);
1935 let (st, _) = &cx.streams[0];
1936 assert_eq!((st.key.as_str(), st.plugin.as_str(), st.op.as_str(), st.input.as_str()), ("appr", "appearance", "changes", ""));
1937 }
1938
1939 #[test]
1940 fn cx_device_model_is_a_request_not_a_notification() {
1941 let mut cx = Cx::<Ev>::default();
1942 cx.device_model(|_| Ev::Tap);
1943 assert!(cx.notifications.is_empty());
1944 assert_eq!(cx.requests.len(), 1);
1945 let (call, _) = &cx.requests[0];
1946 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1947 }
1948
1949 #[test]
1950 fn cx_device_locale_requests_the_device_locale_op() {
1951 let mut cx = Cx::<Ev>::default();
1952 cx.device_locale(|_| Ev::Tap);
1953 assert!(cx.notifications.is_empty());
1954 assert_eq!(cx.requests.len(), 1);
1955 let (call, _) = &cx.requests[0];
1956 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1957 }
1958
1959 #[test]
1960 fn cx_now_requests_the_datetime_now_op() {
1961 let mut cx = Cx::<Ev>::default();
1962 cx.now(|_| Ev::Tap);
1963 assert_eq!(cx.requests.len(), 1);
1964 let (call, _) = &cx.requests[0];
1965 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1966 }
1967
1968 #[test]
1969 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1970 let mut cx = Cx::<Ev>::default();
1971 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1972 assert!(cx.notifications.is_empty());
1974 assert!(cx.requests.is_empty());
1975 assert_eq!(cx.streams.len(), 1);
1976 let (call, on_event) = &cx.streams[0];
1977 assert_eq!(
1978 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1979 ("ws", "websocket", "stream", "wss://h/x")
1980 );
1981 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1983 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1984 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1985 }
1986
1987 #[test]
1988 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1989 let mut cx = Cx::<Ev>::default();
1990 cx.unsubscribe("ws");
1991 assert!(cx.streams.is_empty());
1992 assert_eq!(cx.notifications.len(), 1);
1993 assert_eq!(
1995 cx.notifications[0],
1996 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1997 );
1998 }
1999
2000 #[test]
2001 fn cx_confirm_serializes_title_message_and_routes_ok() {
2002 let mut cx = Cx::<Ev>::default();
2003 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2004 let (call, then) = cx.requests.pop().unwrap();
2005 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2006 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2007 assert_eq!(v["title"], "Delete?");
2008 assert_eq!(v["message"], "This cannot be undone.");
2009 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
2011 }
2012
2013 #[test]
2014 fn cx_confirm_stays_byte_identical_on_the_wire() {
2015 let mut cx = Cx::<Ev>::default();
2016 cx.confirm("Delete?", "This cannot be undone.", |_| Ev::Tap);
2017 let (call, _) = cx.requests.pop().unwrap();
2018 assert_eq!(call.input, r#"{"title":"Delete?","message":"This cannot be undone."}"#);
2019 }
2020
2021 #[test]
2022 fn cx_confirm_with_sends_labels_and_destructive() {
2023 let mut cx = Cx::<Ev>::default();
2024 cx.confirm_with(
2025 Confirm::new("Otkazati termin?", "Klijent dobija obaveštenje.")
2026 .confirm_label("Otkaži termin")
2027 .cancel_label("Ne, vrati se")
2028 .destructive(),
2029 |r| if r.ok { Ev::Tap } else { Ev::Open(0) },
2030 );
2031 let (call, then) = cx.requests.pop().unwrap();
2032 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
2033 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2034 assert_eq!(v["title"], "Otkazati termin?");
2035 assert_eq!(v["message"], "Klijent dobija obaveštenje.");
2036 assert_eq!(v["confirm_label"], "Otkaži termin");
2037 assert_eq!(v["cancel_label"], "Ne, vrati se");
2038 assert_eq!(v["destructive"], true);
2039 assert!(matches!(then(PluginResponse::text(true, "ok")), Ev::Tap));
2040 let mut cx = Cx::<Ev>::default();
2042 cx.confirm_with(Confirm::new("T", "M").confirm_label("Go"), |_| Ev::Tap);
2043 let v: serde_json::Value = serde_json::from_str(&cx.requests.pop().unwrap().0.input).unwrap();
2044 assert!(v.get("cancel_label").is_none() && v.get("destructive").is_none());
2045 }
2046
2047 #[test]
2048 fn with_step_caption_turns_the_caption_on() {
2049 assert!(matches!(steps(3, 2), Widget::Steps { caption: false, .. }));
2050 assert!(matches!(with_step_caption(steps(3, 2)), Widget::Steps { total: 3, current: 2, caption: true }));
2051 assert!(matches!(with_step_caption(text("x")), Widget::Text { .. }));
2052 }
2053
2054 #[test]
2055 fn open_url_then_is_a_request_and_open_url_stays_a_notification() {
2056 let mut cx = Cx::<Ev>::default();
2057 cx.open_url("https://x");
2058 assert!(cx.requests.is_empty() && cx.notifications.len() == 1);
2059 cx.open_url_then("tel:+381601234567", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2060 let (call, then) = cx.requests.pop().unwrap();
2061 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("browser", "open", "tel:+381601234567"));
2062 assert!(matches!(then(PluginResponse::text(false, "no app can open this link")), Ev::Open(0)));
2063 }
2064
2065 #[test]
2066 fn with_bottom_bar_sets_and_every_scaffold_builder_keeps_it() {
2067 let bar = vec![text("A"), text("B")];
2068 let s = with_bottom_bar(scaffold("T", false, vec![], text("x")), bar.clone());
2069 assert!(matches!(&s, Widget::Scaffold { bottom_bar: Some(b), .. } if b.len() == 2));
2070 assert!(matches!(with_bottom_bar(text("x"), bar.clone()), Widget::Text { .. }));
2071 assert!(matches!(scaffold("T", false, vec![], text("x")), Widget::Scaffold { bottom_bar: None, .. }));
2072 let keep = |w: Widget| matches!(w, Widget::Scaffold { bottom_bar: Some(_), .. });
2073 assert!(keep(with_fab(s.clone(), Icon::Add, Ev::Tap)));
2074 assert!(keep(with_extended_fab(s.clone(), Icon::Add, "x", Ev::Tap)));
2075 assert!(keep(with_sheet(s.clone(), "t", text("s"), Ev::Tap)));
2076 assert!(keep(with_refresh(s.clone(), false, Ev::Tap)));
2077 assert!(keep(with_theme(s.clone(), Theme::default())));
2078 assert!(keep(with_labels(s.clone(), ShellLabels::new())));
2079 assert!(keep(with_appearance(s.clone(), Appearance::System)));
2080 }
2081
2082 #[test]
2083 fn steps_builder_clamps_and_step_text_fills_the_template() {
2084 assert!(matches!(steps(3, 2), Widget::Steps { total: 3, current: 2, .. }));
2085 assert!(matches!(steps(3, 9), Widget::Steps { total: 3, current: 3, .. }));
2086 assert_eq!(step_text(None, 2, 3), "Step 2 of 3");
2087 assert_eq!(step_text(Some(""), 2, 3), "Step 2 of 3");
2088 assert_eq!(step_text(Some("Korak {current} od {total}"), 2, 3), "Korak 2 od 3");
2089 assert_eq!(ShellLabels::new().step_of("Korak {current} od {total}").step_of.as_deref(), Some("Korak {current} od {total}"));
2090 }
2091
2092 #[test]
2093 fn with_columns_sets_clamps_and_ignores_other_widgets() {
2094 assert!(matches!(with_columns(grid(vec![]), 3), Widget::Grid { columns: Some(3), .. }));
2095 assert!(matches!(with_columns(grid(vec![]), 0), Widget::Grid { columns: Some(1), .. }));
2096 assert!(matches!(with_columns(grid(vec![]), 9), Widget::Grid { columns: Some(4), .. }));
2097 assert!(matches!(grid(vec![]), Widget::Grid { columns: None, .. }));
2098 assert!(matches!(with_columns(text("x"), 3), Widget::Text { .. }));
2099 }
2100
2101 #[test]
2102 fn badge_icon_and_avatar_initials_modifiers() {
2103 assert!(matches!(with_icon(badge("ok", Tone::Success), Icon::Check), Widget::Badge { icon: Some(Icon::Check), .. }));
2104 assert!(matches!(badge("ok", Tone::Success), Widget::Badge { icon: None, .. }));
2105 let a = with_avatar_size(with_initials(avatar(""), "MJ"), 40);
2106 assert!(matches!(&a, Widget::Avatar { initials: Some(i), size: Some(40), .. } if i == "MJ"));
2107 assert!(matches!(avatar("u"), Widget::Avatar { initials: None, size: None, .. }));
2108 assert!(matches!(with_icon(text("x"), Icon::Check), Widget::Text { .. }));
2110 assert!(matches!(with_initials(badge("b", Tone::Info), "MJ"), Widget::Badge { .. }));
2111 assert!(matches!(with_avatar_size(text("x"), 40), Widget::Text { .. }));
2112 }
2113
2114 #[test]
2115 fn with_extended_fab_sets_the_label_and_with_fab_does_not() {
2116 let s = with_extended_fab(scaffold("T", false, vec![], text("x")), Icon::Add, "Novi termin", Ev::Tap);
2117 assert!(matches!(&s, Widget::Scaffold { fab: Some(Fab { label: Some(l), .. }), .. } if l == "Novi termin"));
2118 let r = with_fab(scaffold("T", false, vec![], text("x")), Icon::Add, Ev::Tap);
2119 assert!(matches!(&r, Widget::Scaffold { fab: Some(Fab { label: None, .. }), .. }));
2120 }
2121
2122 #[test]
2123 fn snackbar_input_is_the_wire_json() {
2124 assert_eq!(Snackbar::new("Saved").to_input(), r#"{"text":"Saved","duration":"short"}"#);
2125 assert_eq!(
2126 Snackbar::new("Cancelled").action("Undo").long().to_input(),
2127 r#"{"text":"Cancelled","action_label":"Undo","duration":"long"}"#
2128 );
2129 }
2130
2131 #[test]
2132 fn cx_snackbar_sends_a_snackbar_show_request() {
2133 let mut cx = Cx::<Ev>::default();
2134 cx.snackbar(Snackbar::new("Cancelled").action("Undo"), |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
2135 let (call, then) = cx.requests.pop().unwrap();
2136 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("snackbar", "show"));
2137 assert_eq!(call.input, Snackbar::new("Cancelled").action("Undo").to_input());
2138 assert!(matches!(then(PluginResponse::text(true, "action")), Ev::Tap));
2139 }
2140
2141 #[test]
2142 fn cx_pickers_keep_empty_input_and_with_variants_send_labels() {
2143 let mut cx = Cx::<Ev>::default();
2144 cx.pick_date(|_| Ev::Tap);
2145 cx.pick_time(|_| Ev::Tap);
2146 assert!(cx.requests.iter().all(|(c, _)| c.input.is_empty()));
2147
2148 let mut cx = Cx::<Ev>::default();
2149 cx.pick_date_with(Picker::new().title("Izaberi datum").confirm_label("Izaberi").cancel_label("Otkaži"), |_| Ev::Tap);
2150 cx.pick_time_with(Picker::new(), |_| Ev::Tap);
2151 let (date, _) = &cx.requests[0];
2152 assert_eq!((date.plugin.as_str(), date.op.as_str()), ("datetime", "date"));
2153 let v: serde_json::Value = serde_json::from_str(&date.input).unwrap();
2154 assert_eq!((v["title"].as_str(), v["confirm_label"].as_str(), v["cancel_label"].as_str()), (Some("Izaberi datum"), Some("Izaberi"), Some("Otkaži")));
2155 let (time, _) = &cx.requests[1];
2156 assert_eq!((time.op.as_str(), time.input.as_str()), ("time", "{}"));
2157 }
2158
2159 #[test]
2162 fn text_builders_carry_their_style() {
2163 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
2164 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
2165 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
2166 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
2167 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
2168 }
2169
2170 #[test]
2171 fn layout_and_content_builders_produce_their_variants() {
2172 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
2173 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
2174 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children, .. } if children.len() == 2));
2175 assert!(matches!(divider(), Widget::Divider));
2176 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
2177 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
2178 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
2179 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)));
2180 let rc = with_bracket(
2181 region_chart(
2182 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
2183 vec![ChartTick::new(3.0, "3 Mt.")],
2184 65.0, 80.0,
2185 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
2186 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
2187 ),
2188 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
2189 );
2190 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
2191 assert!(matches!(
2193 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
2194 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
2195 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
2196 ));
2197 assert!(matches!(
2198 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
2199 Widget::SwipeAction { actions, .. } if actions.len() == 1
2200 ));
2201 assert!(matches!(
2203 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
2204 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: false }
2205 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
2206 ));
2207 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
2208 assert!(matches!(
2210 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
2211 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
2212 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
2213 ));
2214 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { end_label: None, .. }));
2216 assert!(matches!(
2217 with_end_label(lazy_list(vec![text("a")], false, false, Ev::Tap), "Kraj liste"),
2218 Widget::LazyList { on_load_more: Some(_), has_more: false, end_label: Some(l), .. } if l == "Kraj liste"
2219 ));
2220 assert!(matches!(
2222 with_refresh(with_end_label(lazy_list(vec![], false, false, Ev::Tap), "End"), false, Ev::Open(1)),
2223 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2224 ));
2225 assert!(matches!(
2226 with_end_label(with_refresh(lazy_list(vec![], false, false, Ev::Tap), false, Ev::Open(1)), "End"),
2227 Widget::LazyList { on_refresh: Some(_), end_label: Some(l), .. } if l == "End"
2228 ));
2229 assert!(matches!(with_end_label(text("x"), "End"), Widget::Text { .. }));
2231 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
2232 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
2233 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
2234 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
2235 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
2236 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
2238 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
2240 Widget::Split { show_detail: true, on_back: Some(_), .. }));
2241 }
2242
2243 #[test]
2244 fn with_fill_marks_a_lazy_list_and_keeps_its_other_fields() {
2245 assert!(matches!(lazy_list(vec![], false, true, Ev::Tap), Widget::LazyList { fill: false, .. }));
2246 assert!(matches!(lazy_list_static(vec![]), Widget::LazyList { fill: false, .. }));
2247 let l = with_fill(with_end_label(with_refresh(lazy_list(vec![text("a")], false, true, Ev::Tap), false, Ev::Open(1)), "End"));
2248 assert!(matches!(&l, Widget::LazyList { fill: true, on_refresh: Some(_), end_label: Some(e), on_load_more: Some(_), .. } if e == "End"));
2249 let l2 = with_end_label(with_refresh(with_fill(lazy_list(vec![], false, true, Ev::Tap)), false, Ev::Tap), "E");
2251 assert!(matches!(l2, Widget::LazyList { fill: true, .. }));
2252 assert!(matches!(with_fill(text("x")), Widget::Text { .. }));
2253 assert_eq!(ShellLabels::new().pdf_error("x").pdf_error, Some("x".to_string()));
2254 }
2255
2256 #[test]
2257 fn input_builders_carry_ids_values_and_event_tokens() {
2258 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
2259 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
2260 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
2261 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
2263 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
2264 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
2265 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
2266 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
2268 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
2269 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
2270 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
2271 with_captions(video_player("v", "u", true, -1, Ev::Tap),
2272 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
2273 "p.jpg"), 9000), 1.5), 0.5));
2274 assert!(matches!(tuned,
2275 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
2276 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
2277 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
2279 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
2280 assert!(matches!(with_pip(divider()), Widget::Divider));
2282 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
2283 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
2284 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
2285 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
2286 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
2287 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
2288 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
2289 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
2290
2291 match chip("Latte", true, Ev::Open(2)) {
2292 Widget::Chip { selected, on_press, .. } => {
2293 assert!(selected);
2294 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
2295 }
2296 other => panic!("expected Chip, got {other:?}"),
2297 }
2298 match stepper(5, Ev::Tap, Ev::Open(1)) {
2299 Widget::Stepper { value, on_decrement, on_increment } => {
2300 assert_eq!(value, 5);
2301 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
2302 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
2303 }
2304 other => panic!("expected Stepper, got {other:?}"),
2305 }
2306 let t = tab("Home", true, Ev::Tap);
2307 assert_eq!(t.label, "Home");
2308 assert!(t.selected);
2309 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
2310 }
2311
2312 #[test]
2315 fn widget_tree_round_trips_through_serde() {
2316 let tree = scaffold(
2317 "Home",
2318 true,
2319 vec![tab("A", true, Ev::Tap)],
2320 column(vec![
2321 title("Hi"),
2322 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
2323 image("u", ImageShape::Rounded, ImageRatio::Wide),
2324 slider("s", 2, 5),
2325 ]),
2326 );
2327 let s = serde_json::to_string(&tree).unwrap();
2328 let back: Widget = serde_json::from_str(&s).unwrap();
2329 assert_eq!(s, serde_json::to_string(&back).unwrap());
2330 }
2331
2332 #[test]
2333 fn actions_and_input_values_round_trip() {
2334 let actions = vec![
2335 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
2336 Action::Input { id: "n".into(), value: InputValue::Int(7) },
2337 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
2338 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
2339 Action::Restore { data: "blob".into() },
2340 Action::Start,
2341 Action::AppInfo { version: "1.0".into(), build: "7".into(), platform: "android".into(), bundle_id: "rs.x".into() },
2342 ];
2343 for a in actions {
2344 let s = serde_json::to_string(&a).unwrap();
2345 let back: Action = serde_json::from_str(&s).unwrap();
2346 assert_eq!(s, serde_json::to_string(&back).unwrap());
2347 }
2348 }
2349
2350 #[derive(Default)]
2353 struct CounterModel {
2354 count: i32,
2355 restored: String,
2356 started: bool,
2357 last_input: String,
2358 app_build: String,
2359 }
2360
2361 #[derive(serde::Serialize, serde::Deserialize)]
2362 enum CounterEv {
2363 Inc,
2364 Add(i32),
2365 }
2366
2367 #[derive(Default)]
2368 struct CounterApp;
2369
2370 impl MobilerApp for CounterApp {
2371 type Event = CounterEv;
2372 type Model = CounterModel;
2373 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2374 match ev {
2375 CounterEv::Inc => model.count += 1,
2376 CounterEv::Add(n) => model.count += n,
2377 }
2378 }
2379 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
2380 if let InputValue::Text(t) = value {
2381 model.last_input = format!("{id}={t}");
2382 }
2383 }
2384 fn restore(&self, data: &str, model: &mut CounterModel) {
2385 model.restored = data.to_string();
2386 }
2387 fn init(&self, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2388 model.started = true;
2389 model.app_build = cx.app_info().build.clone();
2390 }
2391 fn view(&self, model: &CounterModel) -> Widget {
2392 text(format!("{}", model.count))
2393 }
2394 }
2395
2396 #[test]
2397 fn shell_dispatches_fired_input_restore_and_start() {
2398 use crux_core::App as _;
2399 let shell = MobilerShell::<CounterApp>::default();
2400 let mut m = CounterModel::default();
2401
2402 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
2404 assert_eq!(m.count, 5);
2405 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
2407 assert_eq!(m.last_input, "name=bob");
2408 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
2410 assert_eq!(m.restored, "saved");
2411 let _ = shell.update(Action::Start, &mut m);
2413 assert!(m.started);
2414 assert!(matches!(shell.view(&m), Widget::Text { .. }));
2416 }
2417
2418 fn info(build: &str) -> AppInfo {
2419 AppInfo { version: "1.0".into(), build: build.into(), platform: "android".into(), bundle_id: "rs.x".into() }
2420 }
2421
2422 fn app_info_action(build: &str) -> Action {
2423 let i = info(build);
2424 Action::AppInfo { version: i.version, build: i.build, platform: i.platform, bundle_id: i.bundle_id }
2425 }
2426
2427 static APP_INFO_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2430
2431 #[test]
2432 fn init_sees_app_info_sent_before_start() {
2433 use crux_core::App as _;
2434 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2435 let shell = MobilerShell::<CounterApp>::default();
2436 let mut m = CounterModel::default();
2437 let _ = shell.update(app_info_action("7"), &mut m);
2438 let _ = shell.update(Action::Start, &mut m);
2439 assert_eq!(m.app_build, "7");
2440 }
2441
2442 #[test]
2443 fn later_app_info_replaces_earlier() {
2444 use crux_core::App as _;
2445 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2446 let shell = MobilerShell::<CounterApp>::default();
2447 let mut m = CounterModel::default();
2448 let _ = shell.update(app_info_action("7"), &mut m);
2449 let _ = shell.update(app_info_action("8"), &mut m);
2450 let _ = shell.update(Action::Start, &mut m);
2451 assert_eq!(m.app_build, "8");
2452 }
2453
2454 #[test]
2455 fn app_info_action_does_not_touch_the_model() {
2456 use crux_core::App as _;
2457 let _g = APP_INFO_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
2458 let shell = MobilerShell::<CounterApp>::default();
2459 let mut m = CounterModel::default();
2460 let _ = shell.update(app_info_action("9"), &mut m);
2461 assert!(!m.started);
2462 assert_eq!(m.count, 0);
2463 assert!(m.restored.is_empty());
2464 assert!(m.last_input.is_empty());
2465 assert!(m.app_build.is_empty());
2466 }
2467
2468 #[test]
2469 fn cx_default_has_empty_app_info() {
2470 let cx = Cx::<Ev>::default();
2471 assert_eq!(cx.app_info(), &AppInfo::default());
2472 assert!(cx.app_info().platform.is_empty());
2473 }
2474
2475 #[test]
2476 fn cx_with_app_info_carries_it() {
2477 let cx = Cx::<Ev>::with_app_info(info("42"));
2478 assert_eq!(cx.app_info().build, "42");
2479 assert_eq!(cx.app_info().bundle_id, "rs.x");
2480 }
2481
2482 #[test]
2483 fn shell_ignores_a_malformed_fired_token() {
2484 use crux_core::App as _;
2485 let shell = MobilerShell::<CounterApp>::default();
2486 let mut m = CounterModel::default();
2487 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
2490 assert_eq!(m.count, 0);
2491 }
2492
2493 #[derive(Default)]
2496 struct EffectsApp;
2497
2498 impl MobilerApp for EffectsApp {
2499 type Event = CounterEv;
2500 type Model = CounterModel;
2501 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
2502 model.count += 1;
2503 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
2504 cx.notify("toast", "show", "hi");
2505 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
2506 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
2507 }
2508 fn view(&self, model: &CounterModel) -> Widget {
2509 text(format!("{}", model.count))
2510 }
2511 }
2512
2513 #[test]
2514 fn shell_renders_before_requests_notifications_and_streams() {
2515 use crux_core::App as _;
2516 let shell = MobilerShell::<EffectsApp>::default();
2517 let mut m = CounterModel::default();
2518 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
2519 let kinds: Vec<String> = cmd
2520 .effects()
2521 .map(|e| match e {
2522 Effect::Render(_) => "render".to_string(),
2523 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
2524 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
2525 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
2526 })
2527 .collect();
2528 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
2531 }
2532
2533 #[test]
2536 fn upload_builder_emits_transfer_stream_call() {
2537 let mut cx = Cx::<Ev>::default();
2538 let key = cx
2539 .upload("https://h/put", "file:///tmp/a.enc")
2540 .bearer("tok")
2541 .header("Content-Type", "application/octet-stream")
2542 .start("up-1", |_ev| Ev::Tap);
2543
2544 assert_eq!(key, "up-1");
2545 assert_eq!(cx.streams.len(), 1);
2546 let (call, _) = &cx.streams[0];
2547 assert_eq!(call.key, "up-1");
2548 assert_eq!(call.plugin, "transfer");
2549 assert_eq!(call.op, "upload");
2550
2551 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2552 assert_eq!(v["url"], "https://h/put");
2553 assert_eq!(v["source"], "file:///tmp/a.enc");
2554 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2556 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2557 assert_eq!(v["headers"][1]["name"], "Content-Type");
2558 }
2559
2560 #[test]
2561 fn download_builder_uses_dest_and_no_default_method() {
2562 let mut cx = Cx::<Ev>::default();
2563 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2564 let (call, _) = &cx.streams[0];
2565 assert_eq!(call.op, "download");
2566 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2567 assert_eq!(v["dest"], "/data/att-9.enc");
2568 assert!(v.get("source").is_none());
2569 }
2570
2571 #[test]
2572 fn start_continuation_decodes_progress_and_done() {
2573 use crate::http::HttpOutcome;
2574
2575 #[derive(Debug, PartialEq)]
2578 enum Got {
2579 Prog(u64),
2580 Done(u16),
2581 Bad,
2582 }
2583 #[derive(Debug, PartialEq)]
2584 struct GotEv(Got);
2585
2586 let mut cx = Cx::<GotEv>::default();
2587 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2588 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2589 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2590 Some(s) => Got::Done(s),
2591 None => Got::Bad,
2592 }),
2593 });
2594 let (_, cont) = &cx.streams[0];
2595
2596 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2597 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2598
2599 let done = TransferEvent::Done {
2600 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2601 handle: Some("/d".into()),
2602 };
2603 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2604 }
2605
2606 #[test]
2607 fn calendar_in_localizes_layout_and_clamps_markers() {
2608 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2610 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2611 assert_eq!(title, "Septembar 2026");
2612 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2613 assert_eq!(leading_blanks, 1);
2614 assert_eq!(on_day.len(), 30);
2615 assert_eq!(markers.len(), 30, "padded to one level per day");
2616 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2617 assert!(matches!(
2619 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2620 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2621 ));
2622 }
2623
2624 #[test]
2625 fn scroller_hint_is_opt_in() {
2626 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2627 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2628 }
2629}