1use std::marker::PhantomData;
9
10pub mod bunny;
11pub mod format;
12pub mod http;
13pub mod i18n;
14pub mod transfer;
15pub use format::{Currency, Locale, Weekday};
16pub use http::{HttpHeader, HttpOutcome};
17pub use i18n::{Catalog, negotiate};
18pub use transfer::TransferEvent;
19
20use crux_core::{
21 App, Command,
22 capability::Operation,
23 macros::effect,
24 render::{RenderOperation, render},
25};
26use facet::Facet;
27use serde::{Deserialize, Serialize, de::DeserializeOwned};
28
29pub use mobiler_ui::{
30 A11yRole, Action, BoxAlign, ButtonStyle, Caption, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
31 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
32 ImageRatio, ImageShape, InputValue, MapMarker, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
33 TextStyle, Theme, Tone, Widget,
34};
35
36#[effect(facet_typegen)]
40#[derive(Debug)]
41pub enum Effect {
42 Render(RenderOperation),
43 PluginNotify(PluginNotify),
45 Plugin(PluginCall),
47 PluginStream(PluginStreamCall),
52}
53
54#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
55pub struct PluginNotify {
56 pub plugin: String,
57 pub op: String,
58 pub input: String,
59}
60impl Operation for PluginNotify {
61 type Output = ();
62}
63
64#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
65pub struct PluginCall {
66 pub plugin: String,
67 pub op: String,
68 pub input: String,
69}
70impl Operation for PluginCall {
71 type Output = PluginResponse;
72}
73
74#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
78pub struct PluginStreamCall {
79 pub key: String,
80 pub plugin: String,
81 pub op: String,
82 pub input: String,
83}
84impl Operation for PluginStreamCall {
85 type Output = PluginResponse;
86}
87
88#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
97pub struct PluginResponse {
98 pub ok: bool,
99 pub output: Vec<u8>,
100}
101
102impl PluginResponse {
103 pub fn text(ok: bool, s: impl Into<String>) -> Self {
105 Self { ok, output: s.into().into_bytes() }
106 }
107
108 pub fn as_text(&self) -> Option<&str> {
110 std::str::from_utf8(&self.output).ok()
111 }
112}
113
114type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
115type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
117
118pub struct Cx<E> {
121 notifications: Vec<PluginNotify>,
122 requests: Vec<(PluginCall, Continuation<E>)>,
123 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
124}
125
126impl<E> Default for Cx<E> {
127 fn default() -> Self {
128 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
129 }
130}
131
132impl<E> Cx<E> {
133 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
135 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
136 }
137
138 pub fn plugin(
141 &mut self,
142 plugin: impl Into<String>,
143 op: impl Into<String>,
144 input: impl Into<String>,
145 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
146 ) {
147 self.requests
148 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
149 }
150
151 pub fn subscribe(
159 &mut self,
160 key: impl Into<String>,
161 plugin: impl Into<String>,
162 op: impl Into<String>,
163 input: impl Into<String>,
164 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
165 ) {
166 self.streams.push((
167 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
168 Box::new(on_event),
169 ));
170 }
171
172 pub fn unsubscribe(&mut self, key: impl Into<String>) {
176 self.notify("stream", "unsubscribe", key);
177 }
178
179 pub fn upload(&mut self, url: impl Into<String>, source: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
182 crate::transfer::TransferBuilder::upload(self, url.into(), source.into())
183 }
184
185 pub fn download(&mut self, url: impl Into<String>, dest: impl Into<String>) -> crate::transfer::TransferBuilder<'_, E> {
188 crate::transfer::TransferBuilder::download(self, url.into(), dest.into())
189 }
190
191 pub fn save(&mut self, data: impl Into<String>) {
193 self.notify("storage", "save", data);
194 }
195
196 pub fn copy(&mut self, text: impl Into<String>) {
198 self.notify("clipboard", "copy", text);
199 }
200
201 pub fn share(&mut self, text: impl Into<String>) {
203 self.notify("share", "text", text);
204 }
205
206 pub fn open_url(&mut self, url: impl Into<String>) {
209 self.notify("browser", "open", url);
210 }
211
212 pub fn toast(&mut self, text: impl Into<String>) {
214 self.notify("toast", "show", text);
215 }
216
217 pub fn haptic(&mut self, style: impl Into<String>) {
220 self.notify("haptics", style, "");
221 }
222
223 pub fn request(
238 &mut self,
239 method: impl Into<String>,
240 url: impl Into<String>,
241 ) -> crate::http::RequestBuilder<'_, E> {
242 crate::http::RequestBuilder::new(self, method.into(), url.into())
243 }
244
245 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
247 self.request("GET", url).send(then);
248 }
249 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
251 self.request("POST", url).body(body).send(then);
252 }
253 pub fn put(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
255 self.request("PUT", url).body(body).send(then);
256 }
257 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
259 self.request("PATCH", url).body(body).send(then);
260 }
261 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(HttpOutcome) -> E + Send + 'static) {
263 self.request("DELETE", url).send(then);
264 }
265
266 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
270 self.plugin("device", "model", "", then);
271 }
272
273 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
278 self.plugin("device", "locale", "", then);
279 }
280
281 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
286 self.plugin("photo", "pick", "", then);
287 }
288
289 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
296 self.plugin("camera", "capture", "", then);
297 }
298
299 pub fn confirm(
303 &mut self,
304 title: impl Into<String>,
305 message: impl Into<String>,
306 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
307 ) {
308 #[derive(Serialize)]
309 struct Confirm {
310 title: String,
311 message: String,
312 }
313 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
314 .expect("serialize confirm");
315 self.plugin("dialog", "confirm", input, then);
316 }
317
318 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
323 self.plugin("datetime", "date", "", then);
324 }
325
326 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
331 self.plugin("datetime", "time", "", then);
332 }
333
334 pub fn now(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
341 self.plugin("datetime", "now", "", then);
342 }
343}
344
345pub trait MobilerApp: Default {
350 type Event: Serialize + DeserializeOwned + Send + 'static;
351 type Model: Default;
352
353 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
354
355 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
356 let _ = (id, value, model, cx);
357 }
358
359 fn restore(&self, data: &str, model: &mut Self::Model) {
362 let _ = (data, model);
363 }
364
365 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
368 let _ = (model, cx);
369 }
370
371 fn view(&self, model: &Self::Model) -> Widget;
372}
373
374pub struct MobilerShell<A>(PhantomData<fn() -> A>);
376
377impl<A> Default for MobilerShell<A> {
378 fn default() -> Self {
379 Self(PhantomData)
380 }
381}
382
383impl<A: MobilerApp> App for MobilerShell<A> {
384 type Event = Action;
385 type Model = A::Model;
386 type ViewModel = Widget;
387 type Effect = Effect;
388
389 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
390 let app = A::default();
391 let mut cx = Cx::<A::Event>::default();
392 match action {
393 Action::Fired { token } => {
394 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
395 app.update(event, model, &mut cx);
396 }
397 }
398 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
399 Action::Restore { data } => app.restore(&data, model),
400 Action::Start => app.init(model, &mut cx),
401 }
402 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
403 for op in cx.notifications {
404 commands.push(Command::notify_shell(op).build());
405 }
406 for (op, then) in cx.requests {
407 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
408 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
409 }));
410 }
411 for (op, then) in cx.streams {
412 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
415 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
416 }));
417 }
418 commands.push(render());
419 Command::all(commands)
420 }
421
422 fn view(&self, model: &Self::Model) -> Widget {
423 A::default().view(model)
424 }
425}
426
427#[derive(Clone, Debug)]
446pub struct Nav<R> {
447 stack: Vec<R>,
448}
449
450impl<R: Clone + Serialize> Nav<R> {
451 #[must_use]
453 pub fn new(root: R) -> Self {
454 Self { stack: vec![root] }
455 }
456 pub fn push(&mut self, route: R) {
458 self.stack.push(route);
459 }
460 pub fn pop(&mut self) {
462 if self.stack.len() > 1 {
463 self.stack.pop();
464 }
465 }
466 pub fn reset(&mut self, root: R) {
468 self.stack = vec![root];
469 }
470 #[must_use]
472 pub fn current(&self) -> &R {
473 self.stack.last().expect("nav stack is never empty")
474 }
475 #[must_use]
477 pub fn depth(&self) -> u32 {
478 self.stack.len() as u32
479 }
480 #[must_use]
482 pub fn can_go_back(&self) -> bool {
483 self.stack.len() > 1
484 }
485 fn route_key(&self) -> String {
488 serde_json::to_string(self.current()).expect("serialize route")
489 }
490}
491
492fn tok<E: Serialize>(event: E) -> String {
496 serde_json::to_string(&event).expect("serialize event")
497}
498
499#[must_use]
500pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
501 Widget::Text { content: content.into(), style }
502}
503#[must_use]
504pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
505#[must_use]
506pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
507#[must_use]
508pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
509#[must_use]
510pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
511#[must_use]
512pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
513
514#[must_use]
515pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
516 Widget::Image { source: source.into(), shape, ratio }
517}
518#[must_use]
519pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
520 Widget::Badge { label: label.into(), tone }
521}
522#[must_use]
524pub fn color_dot(color: ProjectColor) -> Widget {
525 Widget::ColorDot { color }
526}
527#[must_use]
528pub fn divider() -> Widget { Widget::Divider }
529#[must_use]
531pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
532#[must_use]
534pub fn skeleton() -> Widget { Widget::Skeleton }
535#[must_use]
539pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
540#[must_use]
549pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
550 Widget::Video {
551 url: url.into(),
552 id: id.into(),
553 playing,
554 seek_to_ms,
555 controls: true,
556 looping: false,
557 muted: false,
558 on_ended: Some(tok(on_ended)),
559 poster: None,
560 start_at_ms: -1,
561 captions: Vec::new(),
562 rate: 1.0,
563 volume: 1.0,
564 urls: Vec::new(),
565 start_index: 0,
566 seek_index: -1,
567 allow_pip: false,
568 }
569}
570#[must_use]
576pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
577 Widget::Video {
578 url: urls.first().cloned().unwrap_or_default(),
579 id: id.into(),
580 playing,
581 seek_to_ms: -1,
582 controls: true,
583 looping: false,
584 muted: false,
585 on_ended: Some(tok(on_ended)),
586 poster: None,
587 start_at_ms: -1,
588 captions: Vec::new(),
589 rate: 1.0,
590 volume: 1.0,
591 urls,
592 start_index,
593 seek_index: -1,
594 allow_pip: false,
595 }
596}
597fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
600 match widget {
601 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
602 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
603 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
604 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
605 f(&mut v);
606 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
607 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
608 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
609 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
610 allow_pip: v.allow_pip }
611 }
612 other => other,
613 }
614}
615struct VideoFields {
616 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
617 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
618 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
619 seek_index: i64, allow_pip: bool,
620}
621#[must_use]
623pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
624#[must_use]
626pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
627#[must_use]
629pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
630#[must_use]
632pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
633 let poster = poster.into();
634 map_video(widget, move |v| v.poster = Some(poster))
635}
636#[must_use]
638pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
639 map_video(widget, move |v| v.start_at_ms = start_at_ms)
640}
641#[must_use]
643pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
644 map_video(widget, move |v| v.captions = captions)
645}
646#[must_use]
648pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
649#[must_use]
651pub fn with_volume(widget: Widget, volume: f32) -> Widget {
652 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
653}
654#[must_use]
656pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
657 map_video(widget, move |v| v.seek_index = index)
658}
659#[must_use]
661pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
662#[must_use]
667pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
668
669#[must_use]
675pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
676 Widget::Map {
677 id: id.into(),
678 center_lat,
679 center_lng,
680 zoom,
681 markers: Vec::new(),
682 style_url: None,
683 interactive: true,
684 }
685}
686#[must_use]
688pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
689 match widget {
690 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
691 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
692 other => other,
693 }
694}
695#[must_use]
697pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
698 match widget {
699 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
700 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
701 other => other,
702 }
703}
704#[must_use]
706pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
707 MapMarker { id: id.into(), lat, lng, title: None }
708}
709#[must_use]
711pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
712 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
713}
714fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
716 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
717}
718
719#[must_use]
722pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
723 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
724}
725#[must_use]
728pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
729 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
730}
731#[must_use]
735pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
736 Widget::Chart { series, labels, style, axis, legend }
737}
738#[must_use]
740pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
741 chart(series, labels, ChartStyle::StackedBar, true, true)
742}
743#[must_use]
745pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
746 chart(series, labels, ChartStyle::StackedBar100, false, true)
747}
748#[must_use]
750pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
751 chart(series, vec![], ChartStyle::Pie, false, true)
752}
753#[must_use]
755pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
756 chart(series, vec![], ChartStyle::Donut, false, true)
757}
758#[must_use]
761pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
762 chart(series, vec![], ChartStyle::Rings, false, true)
763}
764#[must_use]
766pub fn gauge_chart(series: ChartSeries) -> Widget {
767 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
768}
769
770#[must_use]
775pub fn region_chart(
776 regions: Vec<ChartRegion>,
777 ticks: Vec<ChartTick>,
778 x_max: f32,
779 y_max: f32,
780 ref_lines: Vec<ChartRefLine>,
781 legend: Vec<ChartLegendItem>,
782) -> Widget {
783 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
784}
785
786#[must_use]
788pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
789 match widget {
790 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
791 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
792 }
793 other => other,
794 }
795}
796
797fn days_in_month(year: u32, month: u8) -> u8 {
799 match month {
800 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
801 4 | 6 | 9 | 11 => 30,
802 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
803 _ => 30,
804 }
805}
806
807fn weekday(year: u32, month: u8, day: u8) -> u8 {
809 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
810 let y = if month < 3 { year - 1 } else { year };
811 let m = month as usize - 1;
812 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
813}
814
815#[must_use]
819pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
820 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
821}
822
823#[must_use]
828pub fn calendar_in<E: Serialize>(
829 locale: Locale,
830 year: u32,
831 month: u8,
832 selected: Option<u8>,
833 markers: &[u8],
834 on_day: impl Fn(u8) -> E,
835) -> Widget {
836 let n = days_in_month(year, month);
837 let start = locale.week_start().sun0();
838 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
839 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
840 let markers = if markers.is_empty() {
841 Vec::new()
842 } else {
843 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
844 };
845 Widget::Calendar {
846 year,
847 month,
848 title: format::month_year(year, u32::from(month), locale),
849 weekday_labels,
850 leading_blanks,
851 selected,
852 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
853 markers,
854 }
855}
856
857#[must_use]
860pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
861 Widget::SwipeAction {
862 child: Box::new(child),
863 actions: actions
864 .into_iter()
865 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
866 .collect(),
867 }
868}
869#[must_use]
870pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
871
872#[must_use]
873pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
874#[must_use]
875pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
876#[must_use]
877pub fn card(child: Widget, style: CardStyle) -> Widget {
878 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
879}
880#[must_use]
882pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
883 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
884}
885#[must_use]
888pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
889 match widget {
890 Widget::Card { child, style, on_press, .. } => Widget::Card {
891 child,
892 style,
893 on_press,
894 on_long_press: Some(tok(on_long_press)),
895 },
896 other => other,
897 }
898}
899#[must_use]
902pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
903 Widget::Box { children, align, scrim }
904}
905#[must_use]
906pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
907#[must_use]
912pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
913 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
914}
915#[must_use]
917pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
918#[must_use]
920pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
921#[must_use]
923pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
924#[must_use]
926pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
927 Widget::Avatar { source: source.into(), status: Some(status) }
928}
929#[must_use]
931pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
932#[must_use]
934pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
935 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
936}
937
938#[derive(Clone, Copy, Debug, PartialEq, Eq)]
946pub struct ButtonOpts {
947 pub tone: Tone,
948 pub icon: Option<Icon>,
949 pub wide: bool,
950}
951
952impl Default for ButtonOpts {
953 fn default() -> Self {
954 Self { tone: Tone::Neutral, icon: None, wide: false }
955 }
956}
957
958impl ButtonOpts {
959 #[must_use]
961 pub const fn tone(mut self, tone: Tone) -> Self {
962 self.tone = tone;
963 self
964 }
965 #[must_use]
967 pub const fn icon(mut self, icon: Icon) -> Self {
968 self.icon = Some(icon);
969 self
970 }
971 #[must_use]
973 pub const fn wide(mut self) -> Self {
974 self.wide = true;
975 self
976 }
977}
978
979#[must_use]
980pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
981 button_with(label, style, on_press, ButtonOpts::default())
982}
983
984#[must_use]
986pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
987 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
988}
989#[must_use]
990pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
991 Widget::IconButton { icon, on_press: tok(on_press) }
992}
993#[must_use]
994pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
995 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
996}
997#[must_use]
998pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
999 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1000}
1001#[must_use]
1005pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1006 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1007}
1008#[must_use]
1010pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1011 field(id, placeholder, value, FieldKind::Secure, None)
1012}
1013#[must_use]
1015pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1016 field(id, placeholder, value, FieldKind::Email, None)
1017}
1018#[must_use]
1020pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1021 field(id, placeholder, value, FieldKind::Number, None)
1022}
1023#[must_use]
1025pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1026 field(id, placeholder, value, FieldKind::Decimal, None)
1027}
1028#[must_use]
1030pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1031 field(id, placeholder, value, FieldKind::Phone, None)
1032}
1033#[must_use]
1035pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1036 field(id, placeholder, value, FieldKind::Url, None)
1037}
1038#[must_use]
1040pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1041 field(id, placeholder, value, FieldKind::Multiline, None)
1042}
1043#[must_use]
1046pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1047 match widget {
1048 Widget::TextField { id, placeholder, value, kind, .. } =>
1049 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1050 other => other,
1051 }
1052}
1053
1054#[must_use]
1058pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1059 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1060}
1061#[must_use]
1064pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1065 match widget {
1066 Widget::A11y { child, label, role, .. } =>
1067 Widget::A11y { child, label, hint: Some(hint.into()), role },
1068 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1069 }
1070}
1071#[must_use]
1073pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1074 match widget {
1075 Widget::A11y { child, label, hint, .. } =>
1076 Widget::A11y { child, label, hint, role: Some(role) },
1077 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1078 }
1079}
1080#[must_use]
1082pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1083 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1084}
1085#[must_use]
1087pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1088 Segment { label: label.into(), selected, on_select: tok(on_select) }
1089}
1090#[must_use]
1092pub fn segmented(segments: Vec<Segment>) -> Widget {
1093 Widget::Segmented { segments }
1094}
1095#[must_use]
1096pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1097 Widget::Toggle { id: id.into(), label: label.into(), value }
1098}
1099#[must_use]
1100pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1101 Widget::Checkbox { id: id.into(), label: label.into(), value }
1102}
1103#[must_use]
1104pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1105 Widget::Slider { id: id.into(), value, max }
1106}
1107#[must_use]
1108pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1109 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1110}
1111
1112#[must_use]
1114pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1115 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1116}
1117
1118#[must_use]
1120pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1121 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1122}
1123
1124#[must_use]
1127pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1128 let title = title.into();
1129 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 }
1131}
1132
1133#[must_use]
1137pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1138 let title = title.into();
1139 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 }
1140}
1141
1142#[must_use]
1147pub fn nav_scaffold<R, E>(
1148 title: impl Into<String>,
1149 dark_mode: bool,
1150 tabs: Vec<Tab>,
1151 body: Widget,
1152 nav: &Nav<R>,
1153 on_back: E,
1154) -> Widget
1155where
1156 R: Clone + Serialize,
1157 E: Serialize,
1158{
1159 Widget::Scaffold {
1160 title: title.into(),
1161 body: Box::new(body),
1162 tabs,
1163 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1164 dark_mode,
1165 theme: None,
1166 fab: None,
1167 sheet: None,
1168 on_refresh: None,
1169 refreshing: false,
1170 route: nav.route_key(),
1171 depth: nav.depth(),
1172 }
1173}
1174
1175pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1179 match widget {
1180 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1181 title,
1182 body,
1183 tabs,
1184 back,
1185 dark_mode,
1186 theme: Some(theme),
1187 fab,
1188 sheet,
1189 on_refresh,
1190 refreshing,
1191 route,
1192 depth,
1193 },
1194 other => other,
1195 }
1196}
1197
1198pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1201 match widget {
1202 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1203 title,
1204 body,
1205 tabs,
1206 back,
1207 dark_mode,
1208 theme,
1209 fab: Some(Fab { icon, on_press: tok(on_press) }),
1210 sheet,
1211 on_refresh,
1212 refreshing,
1213 route,
1214 depth,
1215 },
1216 other => other,
1217 }
1218}
1219
1220pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1223 match widget {
1224 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1225 title: t,
1226 body,
1227 tabs,
1228 back,
1229 dark_mode,
1230 theme,
1231 fab,
1232 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1233 on_refresh,
1234 refreshing,
1235 route,
1236 depth,
1237 },
1238 other => other,
1239 }
1240}
1241
1242pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1246 match widget {
1247 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1248 title,
1249 body,
1250 tabs,
1251 back,
1252 dark_mode,
1253 theme,
1254 fab,
1255 sheet,
1256 on_refresh: Some(tok(on_refresh)),
1257 refreshing,
1258 route,
1259 depth,
1260 },
1261 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1264 children,
1265 on_load_more,
1266 loading,
1267 has_more,
1268 on_refresh: Some(tok(on_refresh)),
1269 refreshing,
1270 },
1271 other => other,
1272 }
1273}
1274
1275#[must_use]
1281pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1282 Widget::LazyList {
1283 children,
1284 on_load_more: Some(tok(on_load_more)),
1285 loading,
1286 has_more,
1287 on_refresh: None,
1288 refreshing: false,
1289 }
1290}
1291
1292#[must_use]
1294pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1295 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300 use super::*;
1301 use serde::Serialize;
1302
1303 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1304 enum Route {
1305 Home,
1306 Detail(u32),
1307 }
1308
1309 #[derive(Serialize)]
1310 enum Ev {
1311 Tap,
1312 Open(u32),
1313 }
1314
1315 #[test]
1318 fn plugin_response_carries_bytes_and_converts_text() {
1319 let r = PluginResponse::text(true, "hello");
1320 assert!(r.ok);
1321 assert_eq!(r.output, b"hello".to_vec());
1322 assert_eq!(r.as_text(), Some("hello"));
1323
1324 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1325 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1326 }
1327
1328 #[test]
1331 fn nav_push_pop_depth() {
1332 let mut nav = Nav::new(Route::Home);
1333 assert_eq!(nav.depth(), 1);
1334 assert!(!nav.can_go_back());
1335
1336 nav.push(Route::Detail(7));
1337 assert_eq!(nav.depth(), 2);
1338 assert!(nav.can_go_back());
1339 assert!(matches!(nav.current(), Route::Detail(7)));
1340
1341 nav.pop();
1342 assert_eq!(nav.depth(), 1);
1343 assert!(matches!(nav.current(), Route::Home));
1344
1345 nav.pop(); assert_eq!(nav.depth(), 1);
1347 }
1348
1349 #[test]
1350 fn nav_reset_replaces_stack() {
1351 let mut nav = Nav::new(Route::Home);
1352 nav.push(Route::Detail(1));
1353 nav.push(Route::Detail(2));
1354 nav.reset(Route::Detail(9));
1355 assert_eq!(nav.depth(), 1);
1356 assert!(matches!(nav.current(), Route::Detail(9)));
1357 }
1358
1359 #[test]
1360 fn nav_route_key_is_serialization() {
1361 let nav = Nav::new(Route::Detail(3));
1362 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1363 }
1364
1365 #[test]
1368 fn scaffold_sets_route_depth_and_no_back() {
1369 match scaffold("Home", false, vec![], text("x")) {
1370 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1371 assert_eq!(route, "Home");
1372 assert_eq!(depth, 1);
1373 assert!(back.is_none());
1374 assert!(!dark_mode);
1375 }
1376 other => panic!("expected Scaffold, got {other:?}"),
1377 }
1378 }
1379
1380 #[test]
1381 fn scaffold_back_is_depth_2_with_back() {
1382 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1383 Widget::Scaffold { depth, back, dark_mode, .. } => {
1384 assert_eq!(depth, 2);
1385 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1386 assert!(dark_mode);
1387 }
1388 other => panic!("expected Scaffold, got {other:?}"),
1389 }
1390 }
1391
1392 #[test]
1393 fn nav_scaffold_shows_back_only_when_poppable() {
1394 let mut nav = Nav::new(Route::Home);
1395 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1397 Widget::Scaffold { back, depth, route, .. } => {
1398 assert!(back.is_none());
1399 assert_eq!(depth, 1);
1400 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1401 }
1402 other => panic!("expected Scaffold, got {other:?}"),
1403 }
1404 nav.push(Route::Detail(2));
1406 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1407 Widget::Scaffold { back, depth, .. } => {
1408 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1409 assert_eq!(depth, 2);
1410 }
1411 other => panic!("expected Scaffold, got {other:?}"),
1412 }
1413 }
1414
1415 #[test]
1416 fn button_with_carries_tone_icon_and_width() {
1417 assert!(matches!(
1418 button("Go", ButtonStyle::Filled, Ev::Tap),
1419 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1420 ));
1421 assert!(matches!(
1422 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1423 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1424 ));
1425 }
1426
1427 #[test]
1428 fn buttons_carry_serialized_event_tokens() {
1429 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1430 Widget::Button { label, on_press, .. } => {
1431 assert_eq!(label, "Go");
1432 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1433 }
1434 other => panic!("expected Button, got {other:?}"),
1435 }
1436 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1437 Widget::Card { on_press, .. } => {
1438 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1439 }
1440 other => panic!("expected Card, got {other:?}"),
1441 }
1442 match card(text("c"), CardStyle::Elevated) {
1444 Widget::Card { on_press, on_long_press, .. } => {
1445 assert!(on_press.is_none());
1446 assert!(on_long_press.is_none());
1447 }
1448 other => panic!("expected Card, got {other:?}"),
1449 }
1450 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1452 Widget::Card { on_press, on_long_press, .. } => {
1453 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1454 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1455 }
1456 other => panic!("expected Card, got {other:?}"),
1457 }
1458 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1460 }
1461
1462 #[test]
1465 fn cx_notify_and_save_enqueue_notifications() {
1466 let mut cx = Cx::<Ev>::default();
1467 cx.notify("toast", "show", "hi");
1468 cx.save("blob");
1469 assert_eq!(cx.notifications.len(), 2);
1470 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1471 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1472 assert!(cx.requests.is_empty());
1473 }
1474
1475 #[test]
1476 fn cx_http_helpers_build_requests() {
1477 let mut cx = Cx::<Ev>::default();
1478 cx.get("http://h/x", |_| Ev::Tap);
1479 cx.post("http://h/y", "hello", |_| Ev::Tap);
1480 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1481 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1482 cx.delete("http://h/d", |_| Ev::Tap);
1483
1484 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1485 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1486 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1487
1488 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1489 assert_eq!(get_input["url"], "http://h/x");
1490 assert!(get_input["body"].is_null());
1491
1492 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1493 assert_eq!(put_input["url"], "http://h/p");
1494 assert_eq!(put_input["body"], "putbody");
1495 }
1496
1497 #[test]
1498 fn request_builder_emits_headers_in_order() {
1499 let mut cx = Cx::<Ev>::default();
1500 cx.request("PUT", "http://h/access-key")
1501 .bearer("tok123")
1502 .header("X-Trace-Id", "abc")
1503 .body("{}")
1504 .send(|_| Ev::Tap);
1505
1506 assert_eq!(cx.requests.len(), 1);
1507 let (call, _) = &cx.requests[0];
1508 assert_eq!(call.plugin, "http");
1509 assert_eq!(call.op, "PUT");
1510
1511 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1512 assert_eq!(input["url"], "http://h/access-key");
1513 assert_eq!(input["body"], "{}");
1514 assert_eq!(input["headers"][0]["name"], "Authorization");
1515 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1516 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1517 assert_eq!(input["headers"][1]["value"], "abc");
1518 }
1519
1520 #[test]
1521 fn helpers_emit_no_headers_field_content() {
1522 let mut cx = Cx::<Ev>::default();
1523 cx.get("http://h/x", |_| Ev::Tap);
1524 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1525 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1526 }
1527
1528 #[test]
1529 fn continuation_receives_decoded_outcome() {
1530 #[derive(Debug, PartialEq)]
1531 enum Got { Conflict, Offline, Other }
1532
1533 let classify = |r: PluginResponse| -> Got {
1534 match HttpOutcome::decode(&r.output).unwrap() {
1535 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1536 HttpOutcome::TransportError { .. } => Got::Offline,
1537 _ => Got::Other,
1538 }
1539 };
1540
1541 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1542 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1543
1544 let offline = HttpOutcome::TransportError { message: "refused".into() };
1545 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1546 }
1547
1548 #[test]
1549 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1550 let mut cx = Cx::<Ev>::default();
1555
1556 cx.request("GET", "http://h/x").send(|outcome| {
1557 match outcome {
1558 HttpOutcome::TransportError { message } => {
1559 assert!(
1560 message.contains("malformed http response"),
1561 "unexpected message: {message}"
1562 );
1563 }
1564 HttpOutcome::Response { .. } => {
1565 panic!("garbage bytes must not decode as a Response")
1566 }
1567 }
1568 Ev::Tap
1569 });
1570
1571 assert_eq!(cx.requests.len(), 1);
1572 let (_, continuation) = cx.requests.remove(0);
1573 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1576 }
1577
1578 #[test]
1579 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1580 let mut cx = Cx::<Ev>::default();
1581 cx.pick_photo(|_| Ev::Tap);
1582 cx.capture_photo(|_| Ev::Tap);
1583 assert_eq!(cx.requests.len(), 2);
1584 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", ""));
1587 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", ""));
1588 }
1589
1590 #[test]
1591 fn cx_capture_photo_routes_success_and_cancel() {
1592 let mut cx = Cx::<Ev>::default();
1594 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1595 let (_, then) = cx.requests.pop().unwrap();
1596 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1597
1598 let mut cx = Cx::<Ev>::default();
1600 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1601 let (_, then) = cx.requests.pop().unwrap();
1602 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1603 }
1604
1605 #[test]
1606 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1607 let mut cx = Cx::<Ev>::default();
1608 cx.copy("c");
1609 cx.share("s");
1610 cx.open_url("u");
1611 cx.toast("t");
1612 cx.haptic("heavy");
1613 let got: Vec<(&str, &str, &str)> = cx
1614 .notifications
1615 .iter()
1616 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1617 .collect();
1618 assert_eq!(
1619 got,
1620 vec![
1621 ("clipboard", "copy", "c"),
1622 ("share", "text", "s"),
1623 ("browser", "open", "u"),
1624 ("toast", "show", "t"),
1625 ("haptics", "heavy", ""), ]
1627 );
1628 assert!(cx.requests.is_empty());
1629 }
1630
1631 #[test]
1632 fn cx_device_model_is_a_request_not_a_notification() {
1633 let mut cx = Cx::<Ev>::default();
1634 cx.device_model(|_| Ev::Tap);
1635 assert!(cx.notifications.is_empty());
1636 assert_eq!(cx.requests.len(), 1);
1637 let (call, _) = &cx.requests[0];
1638 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1639 }
1640
1641 #[test]
1642 fn cx_device_locale_requests_the_device_locale_op() {
1643 let mut cx = Cx::<Ev>::default();
1644 cx.device_locale(|_| Ev::Tap);
1645 assert!(cx.notifications.is_empty());
1646 assert_eq!(cx.requests.len(), 1);
1647 let (call, _) = &cx.requests[0];
1648 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1649 }
1650
1651 #[test]
1652 fn cx_now_requests_the_datetime_now_op() {
1653 let mut cx = Cx::<Ev>::default();
1654 cx.now(|_| Ev::Tap);
1655 assert_eq!(cx.requests.len(), 1);
1656 let (call, _) = &cx.requests[0];
1657 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1658 }
1659
1660 #[test]
1661 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1662 let mut cx = Cx::<Ev>::default();
1663 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1664 assert!(cx.notifications.is_empty());
1666 assert!(cx.requests.is_empty());
1667 assert_eq!(cx.streams.len(), 1);
1668 let (call, on_event) = &cx.streams[0];
1669 assert_eq!(
1670 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1671 ("ws", "websocket", "stream", "wss://h/x")
1672 );
1673 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1675 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1676 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1677 }
1678
1679 #[test]
1680 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1681 let mut cx = Cx::<Ev>::default();
1682 cx.unsubscribe("ws");
1683 assert!(cx.streams.is_empty());
1684 assert_eq!(cx.notifications.len(), 1);
1685 assert_eq!(
1687 cx.notifications[0],
1688 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1689 );
1690 }
1691
1692 #[test]
1693 fn cx_confirm_serializes_title_message_and_routes_ok() {
1694 let mut cx = Cx::<Ev>::default();
1695 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1696 let (call, then) = cx.requests.pop().unwrap();
1697 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1698 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1699 assert_eq!(v["title"], "Delete?");
1700 assert_eq!(v["message"], "This cannot be undone.");
1701 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1703 }
1704
1705 #[test]
1708 fn text_builders_carry_their_style() {
1709 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1710 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1711 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1712 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1713 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1714 }
1715
1716 #[test]
1717 fn layout_and_content_builders_produce_their_variants() {
1718 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1719 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1720 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1721 assert!(matches!(divider(), Widget::Divider));
1722 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1723 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1724 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1725 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)));
1726 let rc = with_bracket(
1727 region_chart(
1728 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1729 vec![ChartTick::new(3.0, "3 Mt.")],
1730 65.0, 80.0,
1731 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1732 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1733 ),
1734 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1735 );
1736 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1737 assert!(matches!(
1739 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1740 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
1741 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
1742 ));
1743 assert!(matches!(
1744 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1745 Widget::SwipeAction { actions, .. } if actions.len() == 1
1746 ));
1747 assert!(matches!(
1749 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1750 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1751 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1752 ));
1753 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1754 assert!(matches!(
1756 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1757 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1758 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1759 ));
1760 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1761 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1762 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1763 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1764 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1765 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1767 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1769 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1770 }
1771
1772 #[test]
1773 fn input_builders_carry_ids_values_and_event_tokens() {
1774 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1775 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1776 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1777 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1779 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1780 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1781 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1782 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1784 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1785 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1786 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1787 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1788 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1789 "p.jpg"), 9000), 1.5), 0.5));
1790 assert!(matches!(tuned,
1791 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1792 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1793 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1795 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1796 assert!(matches!(with_pip(divider()), Widget::Divider));
1798 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1799 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1800 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1801 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1802 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1803 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1804 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1805 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1806
1807 match chip("Latte", true, Ev::Open(2)) {
1808 Widget::Chip { selected, on_press, .. } => {
1809 assert!(selected);
1810 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1811 }
1812 other => panic!("expected Chip, got {other:?}"),
1813 }
1814 match stepper(5, Ev::Tap, Ev::Open(1)) {
1815 Widget::Stepper { value, on_decrement, on_increment } => {
1816 assert_eq!(value, 5);
1817 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1818 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1819 }
1820 other => panic!("expected Stepper, got {other:?}"),
1821 }
1822 let t = tab("Home", true, Ev::Tap);
1823 assert_eq!(t.label, "Home");
1824 assert!(t.selected);
1825 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1826 }
1827
1828 #[test]
1831 fn widget_tree_round_trips_through_serde() {
1832 let tree = scaffold(
1833 "Home",
1834 true,
1835 vec![tab("A", true, Ev::Tap)],
1836 column(vec![
1837 title("Hi"),
1838 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1839 image("u", ImageShape::Rounded, ImageRatio::Wide),
1840 slider("s", 2, 5),
1841 ]),
1842 );
1843 let s = serde_json::to_string(&tree).unwrap();
1844 let back: Widget = serde_json::from_str(&s).unwrap();
1845 assert_eq!(s, serde_json::to_string(&back).unwrap());
1846 }
1847
1848 #[test]
1849 fn actions_and_input_values_round_trip() {
1850 let actions = vec![
1851 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1852 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1853 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1854 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1855 Action::Restore { data: "blob".into() },
1856 Action::Start,
1857 ];
1858 for a in actions {
1859 let s = serde_json::to_string(&a).unwrap();
1860 let back: Action = serde_json::from_str(&s).unwrap();
1861 assert_eq!(s, serde_json::to_string(&back).unwrap());
1862 }
1863 }
1864
1865 #[derive(Default)]
1868 struct CounterModel {
1869 count: i32,
1870 restored: String,
1871 started: bool,
1872 last_input: String,
1873 }
1874
1875 #[derive(serde::Serialize, serde::Deserialize)]
1876 enum CounterEv {
1877 Inc,
1878 Add(i32),
1879 }
1880
1881 #[derive(Default)]
1882 struct CounterApp;
1883
1884 impl MobilerApp for CounterApp {
1885 type Event = CounterEv;
1886 type Model = CounterModel;
1887 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1888 match ev {
1889 CounterEv::Inc => model.count += 1,
1890 CounterEv::Add(n) => model.count += n,
1891 }
1892 }
1893 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1894 if let InputValue::Text(t) = value {
1895 model.last_input = format!("{id}={t}");
1896 }
1897 }
1898 fn restore(&self, data: &str, model: &mut CounterModel) {
1899 model.restored = data.to_string();
1900 }
1901 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1902 model.started = true;
1903 }
1904 fn view(&self, model: &CounterModel) -> Widget {
1905 text(format!("{}", model.count))
1906 }
1907 }
1908
1909 #[test]
1910 fn shell_dispatches_fired_input_restore_and_start() {
1911 use crux_core::App as _;
1912 let shell = MobilerShell::<CounterApp>::default();
1913 let mut m = CounterModel::default();
1914
1915 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1917 assert_eq!(m.count, 5);
1918 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1920 assert_eq!(m.last_input, "name=bob");
1921 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1923 assert_eq!(m.restored, "saved");
1924 let _ = shell.update(Action::Start, &mut m);
1926 assert!(m.started);
1927 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1929 }
1930
1931 #[test]
1932 fn shell_ignores_a_malformed_fired_token() {
1933 use crux_core::App as _;
1934 let shell = MobilerShell::<CounterApp>::default();
1935 let mut m = CounterModel::default();
1936 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1939 assert_eq!(m.count, 0);
1940 }
1941
1942 #[test]
1945 fn upload_builder_emits_transfer_stream_call() {
1946 let mut cx = Cx::<Ev>::default();
1947 let key = cx
1948 .upload("https://h/put", "file:///tmp/a.enc")
1949 .bearer("tok")
1950 .header("Content-Type", "application/octet-stream")
1951 .start("up-1", |_ev| Ev::Tap);
1952
1953 assert_eq!(key, "up-1");
1954 assert_eq!(cx.streams.len(), 1);
1955 let (call, _) = &cx.streams[0];
1956 assert_eq!(call.key, "up-1");
1957 assert_eq!(call.plugin, "transfer");
1958 assert_eq!(call.op, "upload");
1959
1960 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1961 assert_eq!(v["url"], "https://h/put");
1962 assert_eq!(v["source"], "file:///tmp/a.enc");
1963 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
1965 assert_eq!(v["headers"][0]["value"], "Bearer tok");
1966 assert_eq!(v["headers"][1]["name"], "Content-Type");
1967 }
1968
1969 #[test]
1970 fn download_builder_uses_dest_and_no_default_method() {
1971 let mut cx = Cx::<Ev>::default();
1972 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
1973 let (call, _) = &cx.streams[0];
1974 assert_eq!(call.op, "download");
1975 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1976 assert_eq!(v["dest"], "/data/att-9.enc");
1977 assert!(v.get("source").is_none());
1978 }
1979
1980 #[test]
1981 fn start_continuation_decodes_progress_and_done() {
1982 use crate::http::HttpOutcome;
1983
1984 #[derive(Debug, PartialEq)]
1987 enum Got {
1988 Prog(u64),
1989 Done(u16),
1990 Bad,
1991 }
1992 #[derive(Debug, PartialEq)]
1993 struct GotEv(Got);
1994
1995 let mut cx = Cx::<GotEv>::default();
1996 cx.download("https://h/get", "/d").start("k", |ev| match ev {
1997 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
1998 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
1999 Some(s) => Got::Done(s),
2000 None => Got::Bad,
2001 }),
2002 });
2003 let (_, cont) = &cx.streams[0];
2004
2005 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2006 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2007
2008 let done = TransferEvent::Done {
2009 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2010 handle: Some("/d".into()),
2011 };
2012 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2013 }
2014
2015 #[test]
2016 fn calendar_in_localizes_layout_and_clamps_markers() {
2017 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2019 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2020 assert_eq!(title, "Septembar 2026");
2021 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2022 assert_eq!(leading_blanks, 1);
2023 assert_eq!(on_day.len(), 30);
2024 assert_eq!(markers.len(), 30, "padded to one level per day");
2025 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2026 assert!(matches!(
2028 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2029 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2030 ));
2031 }
2032
2033 #[test]
2034 fn scroller_hint_is_opt_in() {
2035 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2036 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2037 }
2038}