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};
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 let n = days_in_month(year, month);
821 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
822 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
823}
824
825#[must_use]
828pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
829 Widget::SwipeAction {
830 child: Box::new(child),
831 actions: actions
832 .into_iter()
833 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
834 .collect(),
835 }
836}
837#[must_use]
838pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
839
840#[must_use]
841pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
842#[must_use]
843pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
844#[must_use]
845pub fn card(child: Widget, style: CardStyle) -> Widget {
846 Widget::Card { child: Box::new(child), style, on_press: None, on_long_press: None }
847}
848#[must_use]
850pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
851 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)), on_long_press: None }
852}
853#[must_use]
856pub fn with_long_press<E: Serialize>(widget: Widget, on_long_press: E) -> Widget {
857 match widget {
858 Widget::Card { child, style, on_press, .. } => Widget::Card {
859 child,
860 style,
861 on_press,
862 on_long_press: Some(tok(on_long_press)),
863 },
864 other => other,
865 }
866}
867#[must_use]
870pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
871 Widget::Box { children, align, scrim }
872}
873#[must_use]
874pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
875#[must_use]
880pub fn split<E: Serialize>(primary: Widget, detail: Widget, show_detail: bool, on_back: E) -> Widget {
881 Widget::Split { primary: Box::new(primary), detail: Box::new(detail), show_detail, on_back: Some(tok(on_back)) }
882}
883#[must_use]
885pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
886#[must_use]
888pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
889#[must_use]
891pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
892 Widget::Avatar { source: source.into(), status: Some(status) }
893}
894#[must_use]
896pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
897#[must_use]
899pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
900 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
901}
902
903#[must_use]
904pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
905 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
906}
907#[must_use]
908pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
909 Widget::IconButton { icon, on_press: tok(on_press) }
910}
911#[must_use]
912pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
913 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
914}
915#[must_use]
916pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
917 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
918}
919#[must_use]
923pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
924 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
925}
926#[must_use]
928pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
929 field(id, placeholder, value, FieldKind::Secure, None)
930}
931#[must_use]
933pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
934 field(id, placeholder, value, FieldKind::Email, None)
935}
936#[must_use]
938pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
939 field(id, placeholder, value, FieldKind::Number, None)
940}
941#[must_use]
943pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
944 field(id, placeholder, value, FieldKind::Decimal, None)
945}
946#[must_use]
948pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
949 field(id, placeholder, value, FieldKind::Phone, None)
950}
951#[must_use]
953pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
954 field(id, placeholder, value, FieldKind::Url, None)
955}
956#[must_use]
958pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
959 field(id, placeholder, value, FieldKind::Multiline, None)
960}
961#[must_use]
964pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
965 match widget {
966 Widget::TextField { id, placeholder, value, kind, .. } =>
967 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
968 other => other,
969 }
970}
971
972#[must_use]
976pub fn a11y(child: Widget, label: impl Into<String>) -> Widget {
977 Widget::A11y { child: Box::new(child), label: label.into(), hint: None, role: None }
978}
979#[must_use]
982pub fn with_a11y_hint(widget: Widget, hint: impl Into<String>) -> Widget {
983 match widget {
984 Widget::A11y { child, label, role, .. } =>
985 Widget::A11y { child, label, hint: Some(hint.into()), role },
986 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: Some(hint.into()), role: None },
987 }
988}
989#[must_use]
991pub fn with_a11y_role(widget: Widget, role: A11yRole) -> Widget {
992 match widget {
993 Widget::A11y { child, label, hint, .. } =>
994 Widget::A11y { child, label, hint, role: Some(role) },
995 other => Widget::A11y { child: Box::new(other), label: String::new(), hint: None, role: Some(role) },
996 }
997}
998#[must_use]
1000pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
1001 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
1002}
1003#[must_use]
1005pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
1006 Segment { label: label.into(), selected, on_select: tok(on_select) }
1007}
1008#[must_use]
1010pub fn segmented(segments: Vec<Segment>) -> Widget {
1011 Widget::Segmented { segments }
1012}
1013#[must_use]
1014pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1015 Widget::Toggle { id: id.into(), label: label.into(), value }
1016}
1017#[must_use]
1018pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
1019 Widget::Checkbox { id: id.into(), label: label.into(), value }
1020}
1021#[must_use]
1022pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
1023 Widget::Slider { id: id.into(), value, max }
1024}
1025#[must_use]
1026pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
1027 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
1028}
1029
1030#[must_use]
1032pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
1033 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
1034}
1035
1036#[must_use]
1038pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
1039 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
1040}
1041
1042#[must_use]
1045pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
1046 let title = title.into();
1047 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 }
1049}
1050
1051#[must_use]
1055pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
1056 let title = title.into();
1057 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 }
1058}
1059
1060#[must_use]
1065pub fn nav_scaffold<R, E>(
1066 title: impl Into<String>,
1067 dark_mode: bool,
1068 tabs: Vec<Tab>,
1069 body: Widget,
1070 nav: &Nav<R>,
1071 on_back: E,
1072) -> Widget
1073where
1074 R: Clone + Serialize,
1075 E: Serialize,
1076{
1077 Widget::Scaffold {
1078 title: title.into(),
1079 body: Box::new(body),
1080 tabs,
1081 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
1082 dark_mode,
1083 theme: None,
1084 fab: None,
1085 sheet: None,
1086 on_refresh: None,
1087 refreshing: false,
1088 route: nav.route_key(),
1089 depth: nav.depth(),
1090 }
1091}
1092
1093pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
1097 match widget {
1098 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1099 title,
1100 body,
1101 tabs,
1102 back,
1103 dark_mode,
1104 theme: Some(theme),
1105 fab,
1106 sheet,
1107 on_refresh,
1108 refreshing,
1109 route,
1110 depth,
1111 },
1112 other => other,
1113 }
1114}
1115
1116pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
1119 match widget {
1120 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1121 title,
1122 body,
1123 tabs,
1124 back,
1125 dark_mode,
1126 theme,
1127 fab: Some(Fab { icon, on_press: tok(on_press) }),
1128 sheet,
1129 on_refresh,
1130 refreshing,
1131 route,
1132 depth,
1133 },
1134 other => other,
1135 }
1136}
1137
1138pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
1141 match widget {
1142 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
1143 title: t,
1144 body,
1145 tabs,
1146 back,
1147 dark_mode,
1148 theme,
1149 fab,
1150 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
1151 on_refresh,
1152 refreshing,
1153 route,
1154 depth,
1155 },
1156 other => other,
1157 }
1158}
1159
1160pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
1164 match widget {
1165 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
1166 title,
1167 body,
1168 tabs,
1169 back,
1170 dark_mode,
1171 theme,
1172 fab,
1173 sheet,
1174 on_refresh: Some(tok(on_refresh)),
1175 refreshing,
1176 route,
1177 depth,
1178 },
1179 Widget::LazyList { children, on_load_more, loading, has_more, .. } => Widget::LazyList {
1182 children,
1183 on_load_more,
1184 loading,
1185 has_more,
1186 on_refresh: Some(tok(on_refresh)),
1187 refreshing,
1188 },
1189 other => other,
1190 }
1191}
1192
1193#[must_use]
1199pub fn lazy_list<E: Serialize>(children: Vec<Widget>, loading: bool, has_more: bool, on_load_more: E) -> Widget {
1200 Widget::LazyList {
1201 children,
1202 on_load_more: Some(tok(on_load_more)),
1203 loading,
1204 has_more,
1205 on_refresh: None,
1206 refreshing: false,
1207 }
1208}
1209
1210#[must_use]
1212pub fn lazy_list_static(children: Vec<Widget>) -> Widget {
1213 Widget::LazyList { children, on_load_more: None, loading: false, has_more: false, on_refresh: None, refreshing: false }
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218 use super::*;
1219 use serde::Serialize;
1220
1221 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
1222 enum Route {
1223 Home,
1224 Detail(u32),
1225 }
1226
1227 #[derive(Serialize)]
1228 enum Ev {
1229 Tap,
1230 Open(u32),
1231 }
1232
1233 #[test]
1236 fn plugin_response_carries_bytes_and_converts_text() {
1237 let r = PluginResponse::text(true, "hello");
1238 assert!(r.ok);
1239 assert_eq!(r.output, b"hello".to_vec());
1240 assert_eq!(r.as_text(), Some("hello"));
1241
1242 let binary = PluginResponse { ok: true, output: vec![0xff, 0xfe] };
1243 assert_eq!(binary.as_text(), None, "invalid UTF-8 must not panic");
1244 }
1245
1246 #[test]
1249 fn nav_push_pop_depth() {
1250 let mut nav = Nav::new(Route::Home);
1251 assert_eq!(nav.depth(), 1);
1252 assert!(!nav.can_go_back());
1253
1254 nav.push(Route::Detail(7));
1255 assert_eq!(nav.depth(), 2);
1256 assert!(nav.can_go_back());
1257 assert!(matches!(nav.current(), Route::Detail(7)));
1258
1259 nav.pop();
1260 assert_eq!(nav.depth(), 1);
1261 assert!(matches!(nav.current(), Route::Home));
1262
1263 nav.pop(); assert_eq!(nav.depth(), 1);
1265 }
1266
1267 #[test]
1268 fn nav_reset_replaces_stack() {
1269 let mut nav = Nav::new(Route::Home);
1270 nav.push(Route::Detail(1));
1271 nav.push(Route::Detail(2));
1272 nav.reset(Route::Detail(9));
1273 assert_eq!(nav.depth(), 1);
1274 assert!(matches!(nav.current(), Route::Detail(9)));
1275 }
1276
1277 #[test]
1278 fn nav_route_key_is_serialization() {
1279 let nav = Nav::new(Route::Detail(3));
1280 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
1281 }
1282
1283 #[test]
1286 fn scaffold_sets_route_depth_and_no_back() {
1287 match scaffold("Home", false, vec![], text("x")) {
1288 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
1289 assert_eq!(route, "Home");
1290 assert_eq!(depth, 1);
1291 assert!(back.is_none());
1292 assert!(!dark_mode);
1293 }
1294 other => panic!("expected Scaffold, got {other:?}"),
1295 }
1296 }
1297
1298 #[test]
1299 fn scaffold_back_is_depth_2_with_back() {
1300 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
1301 Widget::Scaffold { depth, back, dark_mode, .. } => {
1302 assert_eq!(depth, 2);
1303 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1304 assert!(dark_mode);
1305 }
1306 other => panic!("expected Scaffold, got {other:?}"),
1307 }
1308 }
1309
1310 #[test]
1311 fn nav_scaffold_shows_back_only_when_poppable() {
1312 let mut nav = Nav::new(Route::Home);
1313 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1315 Widget::Scaffold { back, depth, route, .. } => {
1316 assert!(back.is_none());
1317 assert_eq!(depth, 1);
1318 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
1319 }
1320 other => panic!("expected Scaffold, got {other:?}"),
1321 }
1322 nav.push(Route::Detail(2));
1324 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1325 Widget::Scaffold { back, depth, .. } => {
1326 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1327 assert_eq!(depth, 2);
1328 }
1329 other => panic!("expected Scaffold, got {other:?}"),
1330 }
1331 }
1332
1333 #[test]
1334 fn buttons_carry_serialized_event_tokens() {
1335 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1336 Widget::Button { label, on_press, .. } => {
1337 assert_eq!(label, "Go");
1338 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1339 }
1340 other => panic!("expected Button, got {other:?}"),
1341 }
1342 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1343 Widget::Card { on_press, .. } => {
1344 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1345 }
1346 other => panic!("expected Card, got {other:?}"),
1347 }
1348 match card(text("c"), CardStyle::Elevated) {
1350 Widget::Card { on_press, on_long_press, .. } => {
1351 assert!(on_press.is_none());
1352 assert!(on_long_press.is_none());
1353 }
1354 other => panic!("expected Card, got {other:?}"),
1355 }
1356 match with_long_press(card_button(text("c"), CardStyle::Filled, Ev::Tap), Ev::Open(7)) {
1358 Widget::Card { on_press, on_long_press, .. } => {
1359 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1360 assert_eq!(on_long_press, Some(serde_json::to_string(&Ev::Open(7)).unwrap()));
1361 }
1362 other => panic!("expected Card, got {other:?}"),
1363 }
1364 assert!(matches!(with_long_press(text("x"), Ev::Tap), Widget::Text { .. }));
1366 }
1367
1368 #[test]
1371 fn cx_notify_and_save_enqueue_notifications() {
1372 let mut cx = Cx::<Ev>::default();
1373 cx.notify("toast", "show", "hi");
1374 cx.save("blob");
1375 assert_eq!(cx.notifications.len(), 2);
1376 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1377 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1378 assert!(cx.requests.is_empty());
1379 }
1380
1381 #[test]
1382 fn cx_http_helpers_build_requests() {
1383 let mut cx = Cx::<Ev>::default();
1384 cx.get("http://h/x", |_| Ev::Tap);
1385 cx.post("http://h/y", "hello", |_| Ev::Tap);
1386 cx.put("http://h/p", "putbody", |_| Ev::Tap);
1387 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1388 cx.delete("http://h/d", |_| Ev::Tap);
1389
1390 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1391 assert_eq!(methods, ["GET", "POST", "PUT", "PATCH", "DELETE"]);
1392 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1393
1394 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1395 assert_eq!(get_input["url"], "http://h/x");
1396 assert!(get_input["body"].is_null());
1397
1398 let put_input: serde_json::Value = serde_json::from_str(&cx.requests[2].0.input).unwrap();
1399 assert_eq!(put_input["url"], "http://h/p");
1400 assert_eq!(put_input["body"], "putbody");
1401 }
1402
1403 #[test]
1404 fn request_builder_emits_headers_in_order() {
1405 let mut cx = Cx::<Ev>::default();
1406 cx.request("PUT", "http://h/access-key")
1407 .bearer("tok123")
1408 .header("X-Trace-Id", "abc")
1409 .body("{}")
1410 .send(|_| Ev::Tap);
1411
1412 assert_eq!(cx.requests.len(), 1);
1413 let (call, _) = &cx.requests[0];
1414 assert_eq!(call.plugin, "http");
1415 assert_eq!(call.op, "PUT");
1416
1417 let input: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1418 assert_eq!(input["url"], "http://h/access-key");
1419 assert_eq!(input["body"], "{}");
1420 assert_eq!(input["headers"][0]["name"], "Authorization");
1421 assert_eq!(input["headers"][0]["value"], "Bearer tok123");
1422 assert_eq!(input["headers"][1]["name"], "X-Trace-Id");
1423 assert_eq!(input["headers"][1]["value"], "abc");
1424 }
1425
1426 #[test]
1427 fn helpers_emit_no_headers_field_content() {
1428 let mut cx = Cx::<Ev>::default();
1429 cx.get("http://h/x", |_| Ev::Tap);
1430 let input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1431 assert_eq!(input["headers"].as_array().unwrap().len(), 0);
1432 }
1433
1434 #[test]
1435 fn continuation_receives_decoded_outcome() {
1436 #[derive(Debug, PartialEq)]
1437 enum Got { Conflict, Offline, Other }
1438
1439 let classify = |r: PluginResponse| -> Got {
1440 match HttpOutcome::decode(&r.output).unwrap() {
1441 HttpOutcome::Response { status: 409, .. } => Got::Conflict,
1442 HttpOutcome::TransportError { .. } => Got::Offline,
1443 _ => Got::Other,
1444 }
1445 };
1446
1447 let conflict = HttpOutcome::Response { status: 409, headers: vec![], body: b"c".to_vec() };
1448 assert_eq!(classify(PluginResponse { ok: false, output: conflict.encode() }), Got::Conflict);
1449
1450 let offline = HttpOutcome::TransportError { message: "refused".into() };
1451 assert_eq!(classify(PluginResponse { ok: false, output: offline.encode() }), Got::Offline);
1452 }
1453
1454 #[test]
1455 fn decode_failure_in_continuation_surfaces_as_transport_error() {
1456 let mut cx = Cx::<Ev>::default();
1461
1462 cx.request("GET", "http://h/x").send(|outcome| {
1463 match outcome {
1464 HttpOutcome::TransportError { message } => {
1465 assert!(
1466 message.contains("malformed http response"),
1467 "unexpected message: {message}"
1468 );
1469 }
1470 HttpOutcome::Response { .. } => {
1471 panic!("garbage bytes must not decode as a Response")
1472 }
1473 }
1474 Ev::Tap
1475 });
1476
1477 assert_eq!(cx.requests.len(), 1);
1478 let (_, continuation) = cx.requests.remove(0);
1479 continuation(PluginResponse { ok: true, output: vec![0xff, 0xff, 0xff] });
1482 }
1483
1484 #[test]
1485 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1486 let mut cx = Cx::<Ev>::default();
1487 cx.pick_photo(|_| Ev::Tap);
1488 cx.capture_photo(|_| Ev::Tap);
1489 assert_eq!(cx.requests.len(), 2);
1490 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", ""));
1493 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", ""));
1494 }
1495
1496 #[test]
1497 fn cx_capture_photo_routes_success_and_cancel() {
1498 let mut cx = Cx::<Ev>::default();
1500 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1501 let (_, then) = cx.requests.pop().unwrap();
1502 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1503
1504 let mut cx = Cx::<Ev>::default();
1506 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1507 let (_, then) = cx.requests.pop().unwrap();
1508 assert!(matches!(then(PluginResponse { ok: false, output: Vec::new() }), Ev::Tap));
1509 }
1510
1511 #[test]
1512 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1513 let mut cx = Cx::<Ev>::default();
1514 cx.copy("c");
1515 cx.share("s");
1516 cx.open_url("u");
1517 cx.toast("t");
1518 cx.haptic("heavy");
1519 let got: Vec<(&str, &str, &str)> = cx
1520 .notifications
1521 .iter()
1522 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1523 .collect();
1524 assert_eq!(
1525 got,
1526 vec![
1527 ("clipboard", "copy", "c"),
1528 ("share", "text", "s"),
1529 ("browser", "open", "u"),
1530 ("toast", "show", "t"),
1531 ("haptics", "heavy", ""), ]
1533 );
1534 assert!(cx.requests.is_empty());
1535 }
1536
1537 #[test]
1538 fn cx_device_model_is_a_request_not_a_notification() {
1539 let mut cx = Cx::<Ev>::default();
1540 cx.device_model(|_| Ev::Tap);
1541 assert!(cx.notifications.is_empty());
1542 assert_eq!(cx.requests.len(), 1);
1543 let (call, _) = &cx.requests[0];
1544 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1545 }
1546
1547 #[test]
1548 fn cx_device_locale_requests_the_device_locale_op() {
1549 let mut cx = Cx::<Ev>::default();
1550 cx.device_locale(|_| Ev::Tap);
1551 assert!(cx.notifications.is_empty());
1552 assert_eq!(cx.requests.len(), 1);
1553 let (call, _) = &cx.requests[0];
1554 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1555 }
1556
1557 #[test]
1558 fn cx_now_requests_the_datetime_now_op() {
1559 let mut cx = Cx::<Ev>::default();
1560 cx.now(|_| Ev::Tap);
1561 assert_eq!(cx.requests.len(), 1);
1562 let (call, _) = &cx.requests[0];
1563 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("datetime", "now", ""));
1564 }
1565
1566 #[test]
1567 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1568 let mut cx = Cx::<Ev>::default();
1569 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1570 assert!(cx.notifications.is_empty());
1572 assert!(cx.requests.is_empty());
1573 assert_eq!(cx.streams.len(), 1);
1574 let (call, on_event) = &cx.streams[0];
1575 assert_eq!(
1576 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1577 ("ws", "websocket", "stream", "wss://h/x")
1578 );
1579 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1581 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1582 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1583 }
1584
1585 #[test]
1586 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1587 let mut cx = Cx::<Ev>::default();
1588 cx.unsubscribe("ws");
1589 assert!(cx.streams.is_empty());
1590 assert_eq!(cx.notifications.len(), 1);
1591 assert_eq!(
1593 cx.notifications[0],
1594 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1595 );
1596 }
1597
1598 #[test]
1599 fn cx_confirm_serializes_title_message_and_routes_ok() {
1600 let mut cx = Cx::<Ev>::default();
1601 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1602 let (call, then) = cx.requests.pop().unwrap();
1603 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1604 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1605 assert_eq!(v["title"], "Delete?");
1606 assert_eq!(v["message"], "This cannot be undone.");
1607 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1609 }
1610
1611 #[test]
1614 fn text_builders_carry_their_style() {
1615 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1616 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1617 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1618 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1619 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1620 }
1621
1622 #[test]
1623 fn layout_and_content_builders_produce_their_variants() {
1624 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1625 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1626 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1627 assert!(matches!(divider(), Widget::Divider));
1628 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1629 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1630 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1631 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)));
1632 let rc = with_bracket(
1633 region_chart(
1634 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1635 vec![ChartTick::new(3.0, "3 Mt.")],
1636 65.0, 80.0,
1637 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1638 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1639 ),
1640 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1641 );
1642 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1643 assert!(matches!(
1645 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1646 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1647 ));
1648 assert!(matches!(
1649 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1650 Widget::SwipeAction { actions, .. } if actions.len() == 1
1651 ));
1652 assert!(matches!(
1654 lazy_list(vec![text("a"), text("b")], false, true, Ev::Tap),
1655 Widget::LazyList { children, on_load_more: Some(t), loading: false, has_more: true, on_refresh: None, refreshing: false }
1656 if children.len() == 2 && t == serde_json::to_string(&Ev::Tap).unwrap()
1657 ));
1658 assert!(matches!(lazy_list_static(vec![text("a")]), Widget::LazyList { on_load_more: None, on_refresh: None, .. }));
1659 assert!(matches!(
1661 with_refresh(lazy_list(vec![text("a")], true, false, Ev::Tap), true, Ev::Open(9)),
1662 Widget::LazyList { on_load_more: Some(_), loading: true, has_more: false, on_refresh: Some(r), refreshing: true, .. }
1663 if r == serde_json::to_string(&Ev::Open(9)).unwrap()
1664 ));
1665 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1666 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1667 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1668 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1669 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1670 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1672 assert!(matches!(split(text("list"), text("detail"), true, Ev::Tap),
1674 Widget::Split { show_detail: true, on_back: Some(_), .. }));
1675 }
1676
1677 #[test]
1678 fn input_builders_carry_ids_values_and_event_tokens() {
1679 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1680 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1681 assert!(matches!(web_view("https://iframe.mediadelivery.net/embed/1/abc"), Widget::WebView { url } if url == "https://iframe.mediadelivery.net/embed/1/abc"));
1682 assert!(matches!(video_player("v", "https://x/c.mp4", false, -1, Ev::Tap),
1684 Widget::Video { id, playing: false, seek_to_ms: -1, controls: true, looping: false, muted: false, on_ended: Some(_), .. } if id == "v"));
1685 assert!(matches!(without_controls(with_muted(with_loop(video_player("v", "u", true, 0, Ev::Tap)))),
1686 Widget::Video { playing: true, controls: false, looping: true, muted: true, .. }));
1687 assert!(matches!(video_player("v", "u", false, -1, Ev::Tap),
1689 Widget::Video { poster: None, start_at_ms: -1, rate, volume, allow_pip: false, .. }
1690 if (rate - 1.0).abs() < f32::EPSILON && (volume - 1.0).abs() < f32::EPSILON));
1691 let tuned = with_pip(with_volume(with_rate(with_start_at(with_poster(
1692 with_captions(video_player("v", "u", true, -1, Ev::Tap),
1693 vec![Caption { url: "e.vtt".into(), label: "EN".into(), language: "en".into(), default_on: true }]),
1694 "p.jpg"), 9000), 1.5), 0.5));
1695 assert!(matches!(tuned,
1696 Widget::Video { poster: Some(p), start_at_ms: 9000, rate, volume, allow_pip: true, captions, .. }
1697 if p == "p.jpg" && (rate - 1.5).abs() < f32::EPSILON && (volume - 0.5).abs() < f32::EPSILON && captions.len() == 1));
1698 assert!(matches!(with_seek_index(video_playlist("pl", vec!["a.mp4".into(), "b.mp4".into()], 1, true, Ev::Tap), 0),
1700 Widget::Video { url, urls, start_index: 1, seek_index: 0, .. } if url == "a.mp4" && urls.len() == 2));
1701 assert!(matches!(with_pip(divider()), Widget::Divider));
1703 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1704 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1705 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1706 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1707 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1708 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1709 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1710 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1711
1712 match chip("Latte", true, Ev::Open(2)) {
1713 Widget::Chip { selected, on_press, .. } => {
1714 assert!(selected);
1715 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1716 }
1717 other => panic!("expected Chip, got {other:?}"),
1718 }
1719 match stepper(5, Ev::Tap, Ev::Open(1)) {
1720 Widget::Stepper { value, on_decrement, on_increment } => {
1721 assert_eq!(value, 5);
1722 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1723 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1724 }
1725 other => panic!("expected Stepper, got {other:?}"),
1726 }
1727 let t = tab("Home", true, Ev::Tap);
1728 assert_eq!(t.label, "Home");
1729 assert!(t.selected);
1730 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1731 }
1732
1733 #[test]
1736 fn widget_tree_round_trips_through_serde() {
1737 let tree = scaffold(
1738 "Home",
1739 true,
1740 vec![tab("A", true, Ev::Tap)],
1741 column(vec![
1742 title("Hi"),
1743 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1744 image("u", ImageShape::Rounded, ImageRatio::Wide),
1745 slider("s", 2, 5),
1746 ]),
1747 );
1748 let s = serde_json::to_string(&tree).unwrap();
1749 let back: Widget = serde_json::from_str(&s).unwrap();
1750 assert_eq!(s, serde_json::to_string(&back).unwrap());
1751 }
1752
1753 #[test]
1754 fn actions_and_input_values_round_trip() {
1755 let actions = vec![
1756 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1757 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1758 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1759 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1760 Action::Restore { data: "blob".into() },
1761 Action::Start,
1762 ];
1763 for a in actions {
1764 let s = serde_json::to_string(&a).unwrap();
1765 let back: Action = serde_json::from_str(&s).unwrap();
1766 assert_eq!(s, serde_json::to_string(&back).unwrap());
1767 }
1768 }
1769
1770 #[derive(Default)]
1773 struct CounterModel {
1774 count: i32,
1775 restored: String,
1776 started: bool,
1777 last_input: String,
1778 }
1779
1780 #[derive(serde::Serialize, serde::Deserialize)]
1781 enum CounterEv {
1782 Inc,
1783 Add(i32),
1784 }
1785
1786 #[derive(Default)]
1787 struct CounterApp;
1788
1789 impl MobilerApp for CounterApp {
1790 type Event = CounterEv;
1791 type Model = CounterModel;
1792 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1793 match ev {
1794 CounterEv::Inc => model.count += 1,
1795 CounterEv::Add(n) => model.count += n,
1796 }
1797 }
1798 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1799 if let InputValue::Text(t) = value {
1800 model.last_input = format!("{id}={t}");
1801 }
1802 }
1803 fn restore(&self, data: &str, model: &mut CounterModel) {
1804 model.restored = data.to_string();
1805 }
1806 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1807 model.started = true;
1808 }
1809 fn view(&self, model: &CounterModel) -> Widget {
1810 text(format!("{}", model.count))
1811 }
1812 }
1813
1814 #[test]
1815 fn shell_dispatches_fired_input_restore_and_start() {
1816 use crux_core::App as _;
1817 let shell = MobilerShell::<CounterApp>::default();
1818 let mut m = CounterModel::default();
1819
1820 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1822 assert_eq!(m.count, 5);
1823 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1825 assert_eq!(m.last_input, "name=bob");
1826 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1828 assert_eq!(m.restored, "saved");
1829 let _ = shell.update(Action::Start, &mut m);
1831 assert!(m.started);
1832 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1834 }
1835
1836 #[test]
1837 fn shell_ignores_a_malformed_fired_token() {
1838 use crux_core::App as _;
1839 let shell = MobilerShell::<CounterApp>::default();
1840 let mut m = CounterModel::default();
1841 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1844 assert_eq!(m.count, 0);
1845 }
1846
1847 #[test]
1850 fn upload_builder_emits_transfer_stream_call() {
1851 let mut cx = Cx::<Ev>::default();
1852 let key = cx
1853 .upload("https://h/put", "file:///tmp/a.enc")
1854 .bearer("tok")
1855 .header("Content-Type", "application/octet-stream")
1856 .start("up-1", |_ev| Ev::Tap);
1857
1858 assert_eq!(key, "up-1");
1859 assert_eq!(cx.streams.len(), 1);
1860 let (call, _) = &cx.streams[0];
1861 assert_eq!(call.key, "up-1");
1862 assert_eq!(call.plugin, "transfer");
1863 assert_eq!(call.op, "upload");
1864
1865 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1866 assert_eq!(v["url"], "https://h/put");
1867 assert_eq!(v["source"], "file:///tmp/a.enc");
1868 assert_eq!(v["method"], "PUT"); assert_eq!(v["headers"][0]["name"], "Authorization");
1870 assert_eq!(v["headers"][0]["value"], "Bearer tok");
1871 assert_eq!(v["headers"][1]["name"], "Content-Type");
1872 }
1873
1874 #[test]
1875 fn download_builder_uses_dest_and_no_default_method() {
1876 let mut cx = Cx::<Ev>::default();
1877 cx.download("https://h/get", "/data/att-9.enc").start("dl-1", |_| Ev::Tap);
1878 let (call, _) = &cx.streams[0];
1879 assert_eq!(call.op, "download");
1880 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1881 assert_eq!(v["dest"], "/data/att-9.enc");
1882 assert!(v.get("source").is_none());
1883 }
1884
1885 #[test]
1886 fn start_continuation_decodes_progress_and_done() {
1887 use crate::http::HttpOutcome;
1888
1889 #[derive(Debug, PartialEq)]
1892 enum Got {
1893 Prog(u64),
1894 Done(u16),
1895 Bad,
1896 }
1897 #[derive(Debug, PartialEq)]
1898 struct GotEv(Got);
1899
1900 let mut cx = Cx::<GotEv>::default();
1901 cx.download("https://h/get", "/d").start("k", |ev| match ev {
1902 TransferEvent::Progress { transferred, .. } => GotEv(Got::Prog(transferred)),
1903 TransferEvent::Done { outcome, .. } => GotEv(match outcome.status() {
1904 Some(s) => Got::Done(s),
1905 None => Got::Bad,
1906 }),
1907 });
1908 let (_, cont) = &cx.streams[0];
1909
1910 let prog = TransferEvent::Progress { transferred: 512, total: Some(1024) };
1911 assert_eq!(cont(PluginResponse { ok: true, output: prog.encode() }), GotEv(Got::Prog(512)));
1912
1913 let done = TransferEvent::Done {
1914 outcome: HttpOutcome::Response { status: 201, headers: vec![], body: vec![] },
1915 handle: Some("/d".into()),
1916 };
1917 assert_eq!(cont(PluginResponse { ok: true, output: done.encode() }), GotEv(Got::Done(201)));
1918 }
1919}