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![render()];
408 for op in cx.notifications {
409 commands.push(Command::notify_shell(op).build());
410 }
411 for (op, then) in cx.requests {
412 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
413 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
414 }));
415 }
416 for (op, then) in cx.streams {
417 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
420 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
421 }));
422 }
423 Command::all(commands)
424 }
425
426 fn view(&self, model: &Self::Model) -> Widget {
427 A::default().view(model)
428 }
429}
430
431#[derive(Clone, Debug)]
450pub struct Nav<R> {
451 stack: Vec<R>,
452}
453
454impl<R: Clone + Serialize> Nav<R> {
455 #[must_use]
457 pub fn new(root: R) -> Self {
458 Self { stack: vec![root] }
459 }
460 pub fn push(&mut self, route: R) {
462 self.stack.push(route);
463 }
464 pub fn pop(&mut self) {
466 if self.stack.len() > 1 {
467 self.stack.pop();
468 }
469 }
470 pub fn reset(&mut self, root: R) {
472 self.stack = vec![root];
473 }
474 #[must_use]
476 pub fn current(&self) -> &R {
477 self.stack.last().expect("nav stack is never empty")
478 }
479 #[must_use]
481 pub fn depth(&self) -> u32 {
482 self.stack.len() as u32
483 }
484 #[must_use]
486 pub fn can_go_back(&self) -> bool {
487 self.stack.len() > 1
488 }
489 fn route_key(&self) -> String {
492 serde_json::to_string(self.current()).expect("serialize route")
493 }
494}
495
496fn tok<E: Serialize>(event: E) -> String {
500 serde_json::to_string(&event).expect("serialize event")
501}
502
503#[must_use]
504pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
505 Widget::Text { content: content.into(), style }
506}
507#[must_use]
508pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
509#[must_use]
510pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
511#[must_use]
512pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
513#[must_use]
514pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
515#[must_use]
516pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
517
518#[must_use]
519pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
520 Widget::Image { source: source.into(), shape, ratio }
521}
522#[must_use]
523pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
524 Widget::Badge { label: label.into(), tone }
525}
526#[must_use]
528pub fn color_dot(color: ProjectColor) -> Widget {
529 Widget::ColorDot { color }
530}
531#[must_use]
532pub fn divider() -> Widget { Widget::Divider }
533#[must_use]
535pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
536#[must_use]
538pub fn skeleton() -> Widget { Widget::Skeleton }
539#[must_use]
543pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
544#[must_use]
553pub fn video_player<E: Serialize>(id: impl Into<String>, url: impl Into<String>, playing: bool, seek_to_ms: i64, on_ended: E) -> Widget {
554 Widget::Video {
555 url: url.into(),
556 id: id.into(),
557 playing,
558 seek_to_ms,
559 controls: true,
560 looping: false,
561 muted: false,
562 on_ended: Some(tok(on_ended)),
563 poster: None,
564 start_at_ms: -1,
565 captions: Vec::new(),
566 rate: 1.0,
567 volume: 1.0,
568 urls: Vec::new(),
569 start_index: 0,
570 seek_index: -1,
571 allow_pip: false,
572 }
573}
574#[must_use]
580pub fn video_playlist<E: Serialize>(id: impl Into<String>, urls: Vec<String>, start_index: i64, playing: bool, on_ended: E) -> Widget {
581 Widget::Video {
582 url: urls.first().cloned().unwrap_or_default(),
583 id: id.into(),
584 playing,
585 seek_to_ms: -1,
586 controls: true,
587 looping: false,
588 muted: false,
589 on_ended: Some(tok(on_ended)),
590 poster: None,
591 start_at_ms: -1,
592 captions: Vec::new(),
593 rate: 1.0,
594 volume: 1.0,
595 urls,
596 start_index,
597 seek_index: -1,
598 allow_pip: false,
599 }
600}
601fn map_video(widget: Widget, f: impl FnOnce(&mut VideoFields)) -> Widget {
604 match widget {
605 Widget::Video { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
606 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip } => {
607 let mut v = VideoFields { url, id, playing, seek_to_ms, controls, looping, muted, on_ended,
608 poster, start_at_ms, captions, rate, volume, urls, start_index, seek_index, allow_pip };
609 f(&mut v);
610 Widget::Video { url: v.url, id: v.id, playing: v.playing, seek_to_ms: v.seek_to_ms,
611 controls: v.controls, looping: v.looping, muted: v.muted, on_ended: v.on_ended,
612 poster: v.poster, start_at_ms: v.start_at_ms, captions: v.captions, rate: v.rate,
613 volume: v.volume, urls: v.urls, start_index: v.start_index, seek_index: v.seek_index,
614 allow_pip: v.allow_pip }
615 }
616 other => other,
617 }
618}
619struct VideoFields {
620 url: String, id: String, playing: bool, seek_to_ms: i64, controls: bool, looping: bool,
621 muted: bool, on_ended: Option<String>, poster: Option<String>, start_at_ms: i64,
622 captions: Vec<Caption>, rate: f32, volume: f32, urls: Vec<String>, start_index: i64,
623 seek_index: i64, allow_pip: bool,
624}
625#[must_use]
627pub fn with_loop(widget: Widget) -> Widget { map_video(widget, |v| v.looping = true) }
628#[must_use]
630pub fn with_muted(widget: Widget) -> Widget { map_video(widget, |v| v.muted = true) }
631#[must_use]
633pub fn without_controls(widget: Widget) -> Widget { map_video(widget, |v| v.controls = false) }
634#[must_use]
636pub fn with_poster(widget: Widget, poster: impl Into<String>) -> Widget {
637 let poster = poster.into();
638 map_video(widget, move |v| v.poster = Some(poster))
639}
640#[must_use]
642pub fn with_start_at(widget: Widget, start_at_ms: i64) -> Widget {
643 map_video(widget, move |v| v.start_at_ms = start_at_ms)
644}
645#[must_use]
647pub fn with_captions(widget: Widget, captions: Vec<Caption>) -> Widget {
648 map_video(widget, move |v| v.captions = captions)
649}
650#[must_use]
652pub fn with_rate(widget: Widget, rate: f32) -> Widget { map_video(widget, move |v| v.rate = rate) }
653#[must_use]
655pub fn with_volume(widget: Widget, volume: f32) -> Widget {
656 map_video(widget, move |v| v.volume = volume.clamp(0.0, 1.0))
657}
658#[must_use]
660pub fn with_seek_index(widget: Widget, index: i64) -> Widget {
661 map_video(widget, move |v| v.seek_index = index)
662}
663#[must_use]
665pub fn with_pip(widget: Widget) -> Widget { map_video(widget, |v| v.allow_pip = true) }
666#[must_use]
671pub fn web_view(url: impl Into<String>) -> Widget { Widget::WebView { url: url.into() } }
672
673#[must_use]
679pub fn map(id: impl Into<String>, center_lat: f64, center_lng: f64, zoom: f64) -> Widget {
680 Widget::Map {
681 id: id.into(),
682 center_lat,
683 center_lng,
684 zoom,
685 markers: Vec::new(),
686 style_url: None,
687 interactive: true,
688 }
689}
690#[must_use]
692pub fn with_markers(widget: Widget, markers: Vec<MapMarker>) -> Widget {
693 match widget {
694 Widget::Map { id, center_lat, center_lng, zoom, style_url, interactive, .. } =>
695 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive },
696 other => other,
697 }
698}
699#[must_use]
701pub fn with_map_style(widget: Widget, url: impl Into<String>) -> Widget {
702 match widget {
703 Widget::Map { id, center_lat, center_lng, zoom, markers, interactive, .. } =>
704 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url: Some(url.into()), interactive },
705 other => other,
706 }
707}
708#[must_use]
710pub fn marker(id: impl Into<String>, lat: f64, lng: f64) -> MapMarker {
711 MapMarker { id: id.into(), lat, lng, title: None }
712}
713#[must_use]
715pub fn marker_titled(id: impl Into<String>, lat: f64, lng: f64, title: impl Into<String>) -> MapMarker {
716 MapMarker { id: id.into(), lat, lng, title: Some(title.into()) }
717}
718fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
720 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
721}
722
723#[must_use]
726pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
727 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
728}
729#[must_use]
732pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
733 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
734}
735#[must_use]
739pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
740 Widget::Chart { series, labels, style, axis, legend }
741}
742#[must_use]
744pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
745 chart(series, labels, ChartStyle::StackedBar, true, true)
746}
747#[must_use]
749pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
750 chart(series, labels, ChartStyle::StackedBar100, false, true)
751}
752#[must_use]
754pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
755 chart(series, vec![], ChartStyle::Pie, false, true)
756}
757#[must_use]
759pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
760 chart(series, vec![], ChartStyle::Donut, false, true)
761}
762#[must_use]
765pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
766 chart(series, vec![], ChartStyle::Rings, false, true)
767}
768#[must_use]
770pub fn gauge_chart(series: ChartSeries) -> Widget {
771 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
772}
773
774#[must_use]
779pub fn region_chart(
780 regions: Vec<ChartRegion>,
781 ticks: Vec<ChartTick>,
782 x_max: f32,
783 y_max: f32,
784 ref_lines: Vec<ChartRefLine>,
785 legend: Vec<ChartLegendItem>,
786) -> Widget {
787 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
788}
789
790#[must_use]
792pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
793 match widget {
794 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
795 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
796 }
797 other => other,
798 }
799}
800
801fn days_in_month(year: u32, month: u8) -> u8 {
803 match month {
804 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
805 4 | 6 | 9 | 11 => 30,
806 2 => if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) { 29 } else { 28 },
807 _ => 30,
808 }
809}
810
811fn weekday(year: u32, month: u8, day: u8) -> u8 {
813 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
814 let y = if month < 3 { year - 1 } else { year };
815 let m = month as usize - 1;
816 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
817}
818
819#[must_use]
823pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
824 calendar_in(Locale::EnUs, year, month, selected, &[], on_day)
825}
826
827#[must_use]
832pub fn calendar_in<E: Serialize>(
833 locale: Locale,
834 year: u32,
835 month: u8,
836 selected: Option<u8>,
837 markers: &[u8],
838 on_day: impl Fn(u8) -> E,
839) -> Widget {
840 let n = days_in_month(year, month);
841 let start = locale.week_start().sun0();
842 let weekday_labels = (0..7).map(|i| format::weekday_short(start + i, locale).to_string()).collect();
843 let leading_blanks = (weekday(year, month, 1) + 7 - start) % 7;
844 let markers = if markers.is_empty() {
845 Vec::new()
846 } else {
847 (0..usize::from(n)).map(|i| markers.get(i).copied().unwrap_or(0).min(3)).collect()
848 };
849 Widget::Calendar {
850 year,
851 month,
852 title: format::month_year(year, u32::from(month), locale),
853 weekday_labels,
854 leading_blanks,
855 selected,
856 on_day: (1..=n).map(|d| tok(on_day(d))).collect(),
857 markers,
858 }
859}
860
861#[must_use]
864pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
865 Widget::SwipeAction {
866 child: Box::new(child),
867 actions: actions
868 .into_iter()
869 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
870 .collect(),
871 }
872}
873#[must_use]
874pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
875
876#[must_use]
877pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
878#[must_use]
879pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
880#[must_use]
881pub fn card(child: Widget, style: CardStyle) -> Widget {
882 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
883}
884#[must_use]
886pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
887 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
888}
889#[must_use]
892pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
893 match widget {
894 Widget::Card { child, style, on_press, .. } => Widget::Card {
895 child,
896 style,
897 on_press,
898 on_long_press: Some(tok(on_long_press)),
899 },
900 other => other,
901 }
902}
903#[must_use]
906pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
907 Widget::Box { children, align, scrim }
908}
909#[must_use]
910pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
911#[must_use]
916pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
917 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
918}
919#[must_use]
921pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: false } }
922#[must_use]
924pub fn scroller_hinted(children: Vec<Widget>) -> Widget { Widget::Scroller { children, edge_fade: true } }
925#[must_use]
927pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
928#[must_use]
930pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
931 Widget::Avatar { source: source.into(), status: Some(status) }
932}
933#[must_use]
935pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
936#[must_use]
938pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
939 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
940}
941
942#[derive(Clone, Copy, Debug, PartialEq, Eq)]
950pub struct ButtonOpts {
951 pub tone: Tone,
952 pub icon: Option<Icon>,
953 pub wide: bool,
954}
955
956impl Default for ButtonOpts {
957 fn default() -> Self {
958 Self { tone: Tone::Neutral, icon: None, wide: false }
959 }
960}
961
962impl ButtonOpts {
963 #[must_use]
965 pub const fn tone(mut self, tone: Tone) -> Self {
966 self.tone = tone;
967 self
968 }
969 #[must_use]
971 pub const fn icon(mut self, icon: Icon) -> Self {
972 self.icon = Some(icon);
973 self
974 }
975 #[must_use]
977 pub const fn wide(mut self) -> Self {
978 self.wide = true;
979 self
980 }
981}
982
983#[must_use]
984pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
985 button_with(label, style, on_press, ButtonOpts::default())
986}
987
988#[must_use]
990pub fn button_with<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E, opts: ButtonOpts) -> Widget {
991 Widget::Button { label: label.into(), style, on_press: tok(on_press), tone: opts.tone, icon: opts.icon, wide: opts.wide }
992}
993#[must_use]
994pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
995 Widget::IconButton { icon, on_press: tok(on_press) }
996}
997#[must_use]
998pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
999 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
1000}
1001#[must_use]
1002pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1003 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
1004}
1005#[must_use]
1009pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
1010 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
1011}
1012#[must_use]
1014pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1015 field(id, placeholder, value, FieldKind::Secure, None)
1016}
1017#[must_use]
1019pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1020 field(id, placeholder, value, FieldKind::Email, None)
1021}
1022#[must_use]
1024pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1025 field(id, placeholder, value, FieldKind::Number, None)
1026}
1027#[must_use]
1029pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1030 field(id, placeholder, value, FieldKind::Decimal, None)
1031}
1032#[must_use]
1034pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1035 field(id, placeholder, value, FieldKind::Phone, None)
1036}
1037#[must_use]
1039pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1040 field(id, placeholder, value, FieldKind::Url, None)
1041}
1042#[must_use]
1044pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1045 field(id, placeholder, value, FieldKind::Multiline, None)
1046}
1047#[must_use]
1050pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
1051 match widget {
1052 Widget::TextField { id, placeholder, value, kind, .. } =>
1053 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
1054 other => other,
1055 }
1056}
1057
1058#[must_use]
1062pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
1063 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
1064}
1065#[must_use]
1068pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
1069 match widget {
1070 Widget::A11y { child, label, role, .. } =>
1071 Widget::A11y { child, label, hint: Some(hint.into()), role },
1072 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
1073 }
1074}
1075#[must_use]
1077pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
1078 match widget {
1079 Widget::A11y { child, label, hint, .. } =>
1080 Widget::A11y { child, label, hint, role: Some(role) },
1081 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
1082 }
1083}
1084#[must_use]
1086pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1087 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1088}
1089#[must_use]
1091pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1092 Segment { label: label.into(), selected, on_select: tok(on_select) }
1093}
1094#[must_use]
1096pub fn segmented(segments: Vec<Segment>) -> Widget {
1097 Widget::Segmented { segments }
1098}
1099#[must_use]
1100pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1101 Widget::Toggle { id: id.into(), label: label.into(), value }
1102}
1103#[must_use]
1104pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1105 Widget::Checkbox { id: id.into(), label: label.into(), value }
1106}
1107#[must_use]
1108pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1109 Widget::Slider { id: id.into(), value, max }
1110}
1111#[must_use]
1112pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1113 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1114}
1115
1116#[must_use]
1118pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1119 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1120}
1121
1122#[must_use]
1124pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1125 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1126}
1127
1128#[must_use]
1131pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1132 let title = title.into();
1133 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 }
1135}
1136
1137#[must_use]
1141pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1142 let title = title.into();
1143 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 }
1144}
1145
1146#[must_use]
1151pub fn nav_scaffold<R, E>(
1152 title: impl Into<String>,
1153 dark_mode: bool,
1154 tabs: Vec<Tab>,
1155 body: Widget,
1156 nav: &Nav<R>,
1157 on_back: E,
1158) -> Widget
1159where
1160 R: Clone + Serialize,
1161 E: Serialize,
1162{
1163 Widget::Scaffold {
1164 title: title.into(),
1165 body: Box::new(body),
1166 tabs,
1167 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1168 dark_mode,
1169 theme: None,
1170 fab: None,
1171 sheet: None,
1172 on_refresh: None,
1173 refreshing: false,
1174 route: nav.route_key(),
1175 depth: nav.depth(),
1176 }
1177}
1178
1179pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1183 match widget {
1184 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1185 title,
1186 body,
1187 tabs,
1188 back,
1189 dark_mode,
1190 theme: Some(theme),
1191 fab,
1192 sheet,
1193 on_refresh,
1194 refreshing,
1195 route,
1196 depth,
1197 },
1198 other => other,
1199 }
1200}
1201
1202pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1205 match widget {
1206 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1207 title,
1208 body,
1209 tabs,
1210 back,
1211 dark_mode,
1212 theme,
1213 fab: Some(Fab { icon, on_press: tok(on_press) }),
1214 sheet,
1215 on_refresh,
1216 refreshing,
1217 route,
1218 depth,
1219 },
1220 other => other,
1221 }
1222}
1223
1224pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1227 match widget {
1228 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1229 title: t,
1230 body,
1231 tabs,
1232 back,
1233 dark_mode,
1234 theme,
1235 fab,
1236 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1237 on_refresh,
1238 refreshing,
1239 route,
1240 depth,
1241 },
1242 other => other,
1243 }
1244}
1245
1246pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1250 match widget {
1251 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1252 title,
1253 body,
1254 tabs,
1255 back,
1256 dark_mode,
1257 theme,
1258 fab,
1259 sheet,
1260 on_refresh: Some(tok(on_refresh)),
1261 refreshing,
1262 route,
1263 depth,
1264 },
1265 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1268 children,
1269 on_load_more,
1270 loading,
1271 has_more,
1272 on_refresh: Some(tok(on_refresh)),
1273 refreshing,
1274 },
1275 other => other,
1276 }
1277}
1278
1279#[must_use]
1285pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1286 Widget::LazyList {
1287 children,
1288 on_load_more: Some(tok(on_load_more)),
1289 loading,
1290 has_more,
1291 on_refresh: None,
1292 refreshing: false,
1293 }
1294}
1295
1296#[must_use]
1298pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1299 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304 use super::*;
1305 use serde::Serialize;
1306
1307 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1308 enum Route {
1309 Home,
1310 Detail(u32),
1311 }
1312
1313 #[derive(Serialize)]
1314 enum Ev {
1315 Tap,
1316 Open(u32),
1317 }
1318
1319 #[test]
1322 fn plugin_response_carries_bytes_and_converts_text() {
1323 let r = PluginResponse::text(true, "hello");
1324 assert!(r.ok);
1325 assert_eq!(r.output, b"hello".to_vec());
1326 assert_eq!(r.as_text(), Some("hello"));
1327
1328 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1329 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1330 }
1331
1332 #[test]
1335 fn nav_push_pop_depth() {
1336 let mut nav = Nav::new(Route::Home);
1337 assert_eq!(nav.depth(), 1);
1338 assert!(!nav.can_go_back());
1339
1340 nav.push(Route::Detail(7));
1341 assert_eq!(nav.depth(), 2);
1342 assert!(nav.can_go_back());
1343 assert!(matches!(nav.current(), Route::Detail(7)));
1344
1345 nav.pop();
1346 assert_eq!(nav.depth(), 1);
1347 assert!(matches!(nav.current(), Route::Home));
1348
1349 nav.pop(); assert_eq!(nav.depth(), 1);
1351 }
1352
1353 #[test]
1354 fn nav_reset_replaces_stack() {
1355 let mut nav = Nav::new(Route::Home);
1356 nav.push(Route::Detail(1));
1357 nav.push(Route::Detail(2));
1358 nav.reset(Route::Detail(9));
1359 assert_eq!(nav.depth(), 1);
1360 assert!(matches!(nav.current(), Route::Detail(9)));
1361 }
1362
1363 #[test]
1364 fn nav_route_key_is_serialization() {
1365 let nav = Nav::new(Route::Detail(3));
1366 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1367 }
1368
1369 #[test]
1372 fn scaffold_sets_route_depth_and_no_back() {
1373 match scaffold("Home", false, vec![], text("x")) {
1374 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1375 assert_eq!(route, "Home");
1376 assert_eq!(depth, 1);
1377 assert!(back.is_none());
1378 assert!(!dark_mode);
1379 }
1380 other => panic!("expected Scaffold, got {other:?}"),
1381 }
1382 }
1383
1384 #[test]
1385 fn scaffold_back_is_depth_2_with_back() {
1386 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1387 Widget::Scaffold { depth, back, dark_mode, .. } => {
1388 assert_eq!(depth, 2);
1389 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1390 assert!(dark_mode);
1391 }
1392 other => panic!("expected Scaffold, got {other:?}"),
1393 }
1394 }
1395
1396 #[test]
1397 fn nav_scaffold_shows_back_only_when_poppable() {
1398 let mut nav = Nav::new(Route::Home);
1399 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1401 Widget::Scaffold { back, depth, route, .. } => {
1402 assert!(back.is_none());
1403 assert_eq!(depth, 1);
1404 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1405 }
1406 other => panic!("expected Scaffold, got {other:?}"),
1407 }
1408 nav.push(Route::Detail(2));
1410 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1411 Widget::Scaffold { back, depth, .. } => {
1412 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1413 assert_eq!(depth, 2);
1414 }
1415 other => panic!("expected Scaffold, got {other:?}"),
1416 }
1417 }
1418
1419 #[test]
1420 fn button_with_carries_tone_icon_and_width() {
1421 assert!(matches!(
1422 button("Go", ButtonStyle::Filled, Ev::Tap),
1423 Widget::Button { style: ButtonStyle::Filled, tone: Tone::Neutral, icon: None, wide: false, .. }
1424 ));
1425 assert!(matches!(
1426 button_with("Cancel", ButtonStyle::Tonal, Ev::Tap, ButtonOpts::default().tone(Tone::Danger).icon(Icon::Close).wide()),
1427 Widget::Button { style: ButtonStyle::Tonal, tone: Tone::Danger, icon: Some(Icon::Close), wide: true, .. }
1428 ));
1429 }
1430
1431 #[test]
1432 fn buttons_carry_serialized_event_tokens() {
1433 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1434 Widget::Button { label, on_press, .. } => {
1435 assert_eq!(label, "Go");
1436 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1437 }
1438 other => panic!("expected Button, got {other:?}"),
1439 }
1440 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1441 Widget::Card { on_press, .. } => {
1442 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1443 }
1444 other => panic!("expected Card, got {other:?}"),
1445 }
1446 match card(text("c"), CardStyle::Elevated) {
1448 Widget::Card { on_press, on_long_press, .. } => {
1449 assert!(on_press.is_none());
1450 assert!(on_long_press.is_none());
1451 }
1452 other => panic!("expected Card, got {other:?}"),
1453 }
1454 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1456 Widget::Card { on_press, on_long_press, .. } => {
1457 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1458 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1459 }
1460 other => panic!("expected Card, got {other:?}"),
1461 }
1462 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1464 }
1465
1466 #[test]
1469 fn cx_notify_and_save_enqueue_notifications() {
1470 let mut cx = Cx::<Ev>::default();
1471 cx.notify("toast", "show", "hi");
1472 cx.save("blob");
1473 assert_eq!(cx.notifications.len(), 2);
1474 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1475 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1476 assert!(cx.requests.is_empty());
1477 }
1478
1479 #[test]
1480 fn cx_http_helpers_build_requests() {
1481 let mut cx = Cx::<Ev>::default();
1482 cx.get("http://h/x", |_| Ev::Tap);
1483 cx.post("http://h/y", "hello", |_| Ev::Tap);
1484 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1485 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1486 cx.delete("http://h/d", |_| Ev::Tap);
1487
1488 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1489 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1490 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1491
1492 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1493 assert_eq!(get_input["url"], "http://h/x");
1494 assert!(get_input["body"].is_null());
1495
1496 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1497 assert_eq!(put_input["url"], "http://h/p");
1498 assert_eq!(put_input["body"], "putbody");
1499 }
1500
1501 #[test]
1502 fn request_builder_emits_headers_in_order() {
1503 let mut cx = Cx::<Ev>::default();
1504 cx.request("PUT", "http://h/access-key")
1505 .bearer("tok123")
1506 .header("X-Trace-Id", "abc")
1507 .body("{}")
1508 .send(|_| Ev::Tap);
1509
1510 assert_eq!(cx.requests.len(), 1);
1511 let (call, _) = &cx.requests[0];
1512 assert_eq!(call.plugin, "http");
1513 assert_eq!(call.op, "PUT");
1514
1515 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1516 assert_eq!(input["url"], "http://h/access-key");
1517 assert_eq!(input["body"], "{}");
1518 assert_eq!(input["headers"][0]["name"], "Authorization");
1519 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1520 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1521 assert_eq!(input["headers"][1]["value"], "abc");
1522 }
1523
1524 #[test]
1525 fn helpers_emit_no_headers_field_content() {
1526 let mut cx = Cx::<Ev>::default();
1527 cx.get("http://h/x", |_| Ev::Tap);
1528 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1529 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1530 }
1531
1532 #[test]
1533 fn continuation_receives_decoded_outcome() {
1534 #[derive(Debug, PartialEq)]
1535 enum Got { Conflict, Offline, Other }
1536
1537 let classify = |r: PluginResponse| -> Got {
1538 match HttpOutcome::decode(&r.output).unwrap() {
1539 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1540 HttpOutcome::TransportError { .. } => Got::Offline,
1541 _ => Got::Other,
1542 }
1543 };
1544
1545 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1546 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1547
1548 let offline = HttpOutcome::TransportError { message: "refused".into() };
1549 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1550 }
1551
1552 #[test]
1553 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1554 let mut cx = Cx::<Ev>::default();
1559
1560 cx.request("GET", "http://h/x").send(|outcome| {
1561 match outcome {
1562 HttpOutcome::TransportError { message } => {
1563 assert!(
1564 message.contains("malformed http response"),
1565 "unexpected message: {message}"
1566 );
1567 }
1568 HttpOutcome::Response { .. } => {
1569 panic!("garbage bytes must not decode as a Response")
1570 }
1571 }
1572 Ev::Tap
1573 });
1574
1575 assert_eq!(cx.requests.len(), 1);
1576 let (_, continuation) = cx.requests.remove(0);
1577 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1580 }
1581
1582 #[test]
1583 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1584 let mut cx = Cx::<Ev>::default();
1585 cx.pick_photo(|_| Ev::Tap);
1586 cx.capture_photo(|_| Ev::Tap);
1587 assert_eq!(cx.requests.len(), 2);
1588 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", ""));
1591 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", ""));
1592 }
1593
1594 #[test]
1595 fn cx_capture_photo_routes_success_and_cancel() {
1596 let mut cx = Cx::<Ev>::default();
1598 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1599 let (_, then) = cx.requests.pop().unwrap();
1600 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1601
1602 let mut cx = Cx::<Ev>::default();
1604 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1605 let (_, then) = cx.requests.pop().unwrap();
1606 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1607 }
1608
1609 #[test]
1610 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1611 let mut cx = Cx::<Ev>::default();
1612 cx.copy("c");
1613 cx.share("s");
1614 cx.open_url("u");
1615 cx.toast("t");
1616 cx.haptic("heavy");
1617 let got: Vec<(&str, &str, &str)> = cx
1618 .notifications
1619 .iter()
1620 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1621 .collect();
1622 assert_eq!(
1623 got,
1624 vec![
1625 ("clipboard", "copy", "c"),
1626 ("share", "text", "s"),
1627 ("browser", "open", "u"),
1628 ("toast", "show", "t"),
1629 ("haptics", "heavy", ""), ]
1631 );
1632 assert!(cx.requests.is_empty());
1633 }
1634
1635 #[test]
1636 fn cx_device_model_is_a_request_not_a_notification() {
1637 let mut cx = Cx::<Ev>::default();
1638 cx.device_model(|_| Ev::Tap);
1639 assert!(cx.notifications.is_empty());
1640 assert_eq!(cx.requests.len(), 1);
1641 let (call, _) = &cx.requests[0];
1642 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1643 }
1644
1645 #[test]
1646 fn cx_device_locale_requests_the_device_locale_op() {
1647 let mut cx = Cx::<Ev>::default();
1648 cx.device_locale(|_| Ev::Tap);
1649 assert!(cx.notifications.is_empty());
1650 assert_eq!(cx.requests.len(), 1);
1651 let (call, _) = &cx.requests[0];
1652 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1653 }
1654
1655 #[test]
1656 fn cx_now_requests_the_datetime_now_op() {
1657 let mut cx = Cx::<Ev>::default();
1658 cx.now(|_| Ev::Tap);
1659 assert_eq!(cx.requests.len(), 1);
1660 let (call, _) = &cx.requests[0];
1661 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1662 }
1663
1664 #[test]
1665 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1666 let mut cx = Cx::<Ev>::default();
1667 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1668 assert!(cx.notifications.is_empty());
1670 assert!(cx.requests.is_empty());
1671 assert_eq!(cx.streams.len(), 1);
1672 let (call, on_event) = &cx.streams[0];
1673 assert_eq!(
1674 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1675 ("ws", "websocket", "stream", "wss://h/x")
1676 );
1677 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1679 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1680 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1681 }
1682
1683 #[test]
1684 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1685 let mut cx = Cx::<Ev>::default();
1686 cx.unsubscribe("ws");
1687 assert!(cx.streams.is_empty());
1688 assert_eq!(cx.notifications.len(), 1);
1689 assert_eq!(
1691 cx.notifications[0],
1692 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1693 );
1694 }
1695
1696 #[test]
1697 fn cx_confirm_serializes_title_message_and_routes_ok() {
1698 let mut cx = Cx::<Ev>::default();
1699 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1700 let (call, then) = cx.requests.pop().unwrap();
1701 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1702 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1703 assert_eq!(v["title"], "Delete?");
1704 assert_eq!(v["message"], "This cannot be undone.");
1705 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1707 }
1708
1709 #[test]
1712 fn text_builders_carry_their_style() {
1713 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1714 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1715 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1716 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1717 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1718 }
1719
1720 #[test]
1721 fn layout_and_content_builders_produce_their_variants() {
1722 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1723 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1724 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1725 assert!(matches!(divider(), Widget::Divider));
1726 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1727 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1728 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1729 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)));
1730 let rc = with_bracket(
1731 region_chart(
1732 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1733 vec![ChartTick::new(3.0, "3 Mt.")],
1734 65.0, 80.0,
1735 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1736 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1737 ),
1738 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1739 );
1740 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1741 assert!(matches!(
1743 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1744 Widget::Calendar { leading_blanks: 1, selected: Some(3), ref on_day, ref title, ref markers, .. }
1745 if on_day.len() == 30 && title == "June 2026" && markers.is_empty()
1746 ));
1747 assert!(matches!(
1748 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1749 Widget::SwipeAction { actions, .. } if actions.len() == 1
1750 ));
1751 assert!(matches!(
1753 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1754 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1755 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1756 ));
1757 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1758 assert!(matches!(
1760 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1761 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1762 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1763 ));
1764 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1765 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1766 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1767 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1768 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1769 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1771 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1773 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1774 }
1775
1776 #[test]
1777 fn input_builders_carry_ids_values_and_event_tokens() {
1778 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1779 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1780 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1781 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1783 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1784 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1785 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1786 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1788 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1789 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1790 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1791 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1792 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1793 "p.jpg"), 9000), 1.5), 0.5));
1794 assert!(matches!(tuned,
1795 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1796 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1797 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1799 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1800 assert!(matches!(with_pip(divider()), Widget::Divider));
1802 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1803 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1804 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1805 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1806 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1807 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1808 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1809 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1810
1811 match chip("Latte", true, Ev::Open(2)) {
1812 Widget::Chip { selected, on_press, .. } => {
1813 assert!(selected);
1814 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1815 }
1816 other => panic!("expected Chip, got {other:?}"),
1817 }
1818 match stepper(5, Ev::Tap, Ev::Open(1)) {
1819 Widget::Stepper { value, on_decrement, on_increment } => {
1820 assert_eq!(value, 5);
1821 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1822 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1823 }
1824 other => panic!("expected Stepper, got {other:?}"),
1825 }
1826 let t = tab("Home", true, Ev::Tap);
1827 assert_eq!(t.label, "Home");
1828 assert!(t.selected);
1829 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1830 }
1831
1832 #[test]
1835 fn widget_tree_round_trips_through_serde() {
1836 let tree = scaffold(
1837 "Home",
1838 true,
1839 vec![tab("A", true, Ev::Tap)],
1840 column(vec![
1841 title("Hi"),
1842 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1843 image("u", ImageShape::Rounded, ImageRatio::Wide),
1844 slider("s", 2, 5),
1845 ]),
1846 );
1847 let s = serde_json::to_string(&tree).unwrap();
1848 let back: Widget = serde_json::from_str(&s).unwrap();
1849 assert_eq!(s, serde_json::to_string(&back).unwrap());
1850 }
1851
1852 #[test]
1853 fn actions_and_input_values_round_trip() {
1854 let actions = vec![
1855 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1856 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1857 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1858 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1859 Action::Restore { data: "blob".into() },
1860 Action::Start,
1861 ];
1862 for a in actions {
1863 let s = serde_json::to_string(&a).unwrap();
1864 let back: Action = serde_json::from_str(&s).unwrap();
1865 assert_eq!(s, serde_json::to_string(&back).unwrap());
1866 }
1867 }
1868
1869 #[derive(Default)]
1872 struct CounterModel {
1873 count: i32,
1874 restored: String,
1875 started: bool,
1876 last_input: String,
1877 }
1878
1879 #[derive(serde::Serialize, serde::Deserialize)]
1880 enum CounterEv {
1881 Inc,
1882 Add(i32),
1883 }
1884
1885 #[derive(Default)]
1886 struct CounterApp;
1887
1888 impl MobilerApp for CounterApp {
1889 type Event = CounterEv;
1890 type Model = CounterModel;
1891 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1892 match ev {
1893 CounterEv::Inc => model.count += 1,
1894 CounterEv::Add(n) => model.count += n,
1895 }
1896 }
1897 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1898 if let InputValue::Text(t) = value {
1899 model.last_input = format!("{id}={t}");
1900 }
1901 }
1902 fn restore(&self, data: &str, model: &mut CounterModel) {
1903 model.restored = data.to_string();
1904 }
1905 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1906 model.started = true;
1907 }
1908 fn view(&self, model: &CounterModel) -> Widget {
1909 text(format!("{}", model.count))
1910 }
1911 }
1912
1913 #[test]
1914 fn shell_dispatches_fired_input_restore_and_start() {
1915 use crux_core::App as _;
1916 let shell = MobilerShell::<CounterApp>::default();
1917 let mut m = CounterModel::default();
1918
1919 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1921 assert_eq!(m.count, 5);
1922 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1924 assert_eq!(m.last_input, "name=bob");
1925 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1927 assert_eq!(m.restored, "saved");
1928 let _ = shell.update(Action::Start, &mut m);
1930 assert!(m.started);
1931 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1933 }
1934
1935 #[test]
1936 fn shell_ignores_a_malformed_fired_token() {
1937 use crux_core::App as _;
1938 let shell = MobilerShell::<CounterApp>::default();
1939 let mut m = CounterModel::default();
1940 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1943 assert_eq!(m.count, 0);
1944 }
1945
1946 #[derive(Default)]
1949 struct EffectsApp;
1950
1951 impl MobilerApp for EffectsApp {
1952 type Event = CounterEv;
1953 type Model = CounterModel;
1954 fn update(&self, _ev: CounterEv, model: &mut CounterModel, cx: &mut Cx<CounterEv>) {
1955 model.count += 1;
1956 cx.plugin("http", "get", "{}", |_r| CounterEv::Inc);
1957 cx.notify("toast", "show", "hi");
1958 cx.subscribe("tick", "ticker", "start", "", |_r| CounterEv::Inc);
1959 cx.plugin("device", "model", "", |_r| CounterEv::Inc);
1960 }
1961 fn view(&self, model: &CounterModel) -> Widget {
1962 text(format!("{}", model.count))
1963 }
1964 }
1965
1966 #[test]
1967 fn shell_renders_before_requests_notifications_and_streams() {
1968 use crux_core::App as _;
1969 let shell = MobilerShell::<EffectsApp>::default();
1970 let mut m = CounterModel::default();
1971 let mut cmd = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Inc).unwrap() }, &mut m);
1972 let kinds: Vec<String> = cmd
1973 .effects()
1974 .map(|e| match e {
1975 Effect::Render(_) => "render".to_string(),
1976 Effect::PluginNotify(r) => format!("notify:{}", r.operation.plugin),
1977 Effect::Plugin(r) => format!("plugin:{}", r.operation.plugin),
1978 Effect::PluginStream(r) => format!("stream:{}", r.operation.plugin),
1979 })
1980 .collect();
1981 assert_eq!(kinds, ["render", "notify:toast", "plugin:http", "plugin:device", "stream:ticker"]);
1984 }
1985
1986 #[test]
1989 fn upload_builder_emits_transfer_stream_call() {
1990 let mut cx = Cx::<Ev>::default();
1991 let key = cx
1992 .upload("https://h/put", "file:///tmp/a.enc")
1993 .bearer("tok")
1994 .header("Content-Type", "application/octet-stream")
1995 .start("up-1", |_ev| Ev::Tap);
1996
1997 assert_eq!(key, "up-1");
1998 assert_eq!(cx.streams.len(), 1);
1999 let (call, _) = &cx.streams[0];
2000 assert_eq!(call.key, "up-1");
2001 assert_eq!(call.plugin, "transfer");
2002 assert_eq!(call.op, "upload");
2003
2004 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2005 assert_eq!(v["url"], "https://h/put");
2006 assert_eq!(v["source"], "file:///tmp/a.enc");
2007 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
2009 assert_eq!(v["headers"][0]["value"], "Bearer tok");
2010 assert_eq!(v["headers"][1]["name"], "Content-Type");
2011 }
2012
2013 #[test]
2014 fn download_builder_uses_dest_and_no_default_method() {
2015 let mut cx = Cx::<Ev>::default();
2016 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
2017 let (call, _) = &cx.streams[0];
2018 assert_eq!(call.op, "download");
2019 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
2020 assert_eq!(v["dest"], "/data/att-9.enc");
2021 assert!(v.get("source").is_none());
2022 }
2023
2024 #[test]
2025 fn start_continuation_decodes_progress_and_done() {
2026 use crate::http::HttpOutcome;
2027
2028 #[derive(Debug, PartialEq)]
2031 enum Got {
2032 Prog(u64),
2033 Done(u16),
2034 Bad,
2035 }
2036 #[derive(Debug, PartialEq)]
2037 struct GotEv(Got);
2038
2039 let mut cx = Cx::<GotEv>::default();
2040 cx.download("https://h/get", "/d").start("k", |ev| match ev {
2041 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
2042 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
2043 Some(s) => Got::Done(s),
2044 None => Got::Bad,
2045 }),
2046 });
2047 let (_, cont) = &cx.streams[0];
2048
2049 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
2050 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
2051
2052 let done = TransferEvent::Done {
2053 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
2054 handle: Some("/d".into()),
2055 };
2056 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
2057 }
2058
2059 #[test]
2060 fn calendar_in_localizes_layout_and_clamps_markers() {
2061 let w = calendar_in(Locale::SrLatn, 2026, 9, None, &[1, 2, 3, 9], |d| Ev::Open(u32::from(d)));
2063 let Widget::Calendar { title, weekday_labels, leading_blanks, on_day, markers, .. } = w else { panic!("not a calendar") };
2064 assert_eq!(title, "Septembar 2026");
2065 assert_eq!(weekday_labels, ["P", "U", "S", "Č", "P", "S", "N"]);
2066 assert_eq!(leading_blanks, 1);
2067 assert_eq!(on_day.len(), 30);
2068 assert_eq!(markers.len(), 30, "padded to one level per day");
2069 assert_eq!(&markers[..5], &[1, 2, 3, 3, 0], "clamped to 3, missing days = 0");
2070 assert!(matches!(
2072 calendar_in(Locale::EnUs, 2026, 9, None, &[], |_| Ev::Tap),
2073 Widget::Calendar { leading_blanks: 2, ref markers, .. } if markers.is_empty()
2074 ));
2075 }
2076
2077 #[test]
2078 fn scroller_hint_is_opt_in() {
2079 assert!(matches!(scroller(vec![text("a")]), Widget::Scroller { edge_fade: false, .. }));
2080 assert!(matches!(scroller_hinted(vec![text("a")]), Widget::Scroller { edge_fade: true, ref children } if children.len() == 1));
2081 }
2082}