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