1use std::marker::PhantomData;
9
10pub mod format;
11pub use format::{Currency, Locale};
12
13use crux_core::{
14 App, Command,
15 capability::Operation,
16 macros::effect,
17 render::{RenderOperation, render},
18};
19use facet::Facet;
20use serde::{Deserialize, Serialize, de::DeserializeOwned};
21
22pub use mobiler_ui::{
23 Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
24 ChartSeries, ChartStyle, ChartTick, Corner, Density, Fab, FieldKind, FontFamily, Icon,
25 ImageRatio, ImageShape, InputValue, ProjectColor, Rgb, Segment, Sheet, Spacing, SwipeButton, Tab,
26 TextStyle, Theme, Tone, Widget,
27};
28
29#[effect(facet_typegen)]
33#[derive(Debug)]
34pub enum Effect {
35 Render(RenderOperation),
36 PluginNotify(PluginNotify),
38 Plugin(PluginCall),
40 PluginStream(PluginStreamCall),
45}
46
47#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct PluginNotify {
49 pub plugin: String,
50 pub op: String,
51 pub input: String,
52}
53impl Operation for PluginNotify {
54 type Output = ();
55}
56
57#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
58pub struct PluginCall {
59 pub plugin: String,
60 pub op: String,
61 pub input: String,
62}
63impl Operation for PluginCall {
64 type Output = PluginResponse;
65}
66
67#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
71pub struct PluginStreamCall {
72 pub key: String,
73 pub plugin: String,
74 pub op: String,
75 pub input: String,
76}
77impl Operation for PluginStreamCall {
78 type Output = PluginResponse;
79}
80
81#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
82pub struct PluginResponse {
83 pub ok: bool,
84 pub output: String,
85}
86
87type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
88type StreamContinuation<E> = Box<dyn Fn(PluginResponse) -> E + Send>;
90
91pub struct Cx<E> {
94 notifications: Vec<PluginNotify>,
95 requests: Vec<(PluginCall, Continuation<E>)>,
96 streams: Vec<(PluginStreamCall, StreamContinuation<E>)>,
97}
98
99impl<E> Default for Cx<E> {
100 fn default() -> Self {
101 Self { notifications: Vec::new(), requests: Vec::new(), streams: Vec::new() }
102 }
103}
104
105impl<E> Cx<E> {
106 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
108 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
109 }
110
111 pub fn plugin(
114 &mut self,
115 plugin: impl Into<String>,
116 op: impl Into<String>,
117 input: impl Into<String>,
118 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
119 ) {
120 self.requests
121 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
122 }
123
124 pub fn subscribe(
132 &mut self,
133 key: impl Into<String>,
134 plugin: impl Into<String>,
135 op: impl Into<String>,
136 input: impl Into<String>,
137 on_event: impl Fn(PluginResponse) -> E + Send + 'static,
138 ) {
139 self.streams.push((
140 PluginStreamCall { key: key.into(), plugin: plugin.into(), op: op.into(), input: input.into() },
141 Box::new(on_event),
142 ));
143 }
144
145 pub fn unsubscribe(&mut self, key: impl Into<String>) {
149 self.notify("stream", "unsubscribe", key);
150 }
151
152 pub fn save(&mut self, data: impl Into<String>) {
154 self.notify("storage", "save", data);
155 }
156
157 pub fn copy(&mut self, text: impl Into<String>) {
159 self.notify("clipboard", "copy", text);
160 }
161
162 pub fn share(&mut self, text: impl Into<String>) {
164 self.notify("share", "text", text);
165 }
166
167 pub fn open_url(&mut self, url: impl Into<String>) {
170 self.notify("browser", "open", url);
171 }
172
173 pub fn toast(&mut self, text: impl Into<String>) {
175 self.notify("toast", "show", text);
176 }
177
178 pub fn haptic(&mut self, style: impl Into<String>) {
181 self.notify("haptics", style, "");
182 }
183
184 pub fn http(
189 &mut self,
190 method: impl Into<String>,
191 url: impl Into<String>,
192 body: Option<String>,
193 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
194 ) {
195 #[derive(Serialize)]
196 struct HttpReq {
197 url: String,
198 body: Option<String>,
199 }
200 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
201 .expect("serialize http request");
202 self.plugin("http", method, input, then);
203 }
204
205 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
207 self.http("GET", url, None, then);
208 }
209 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
211 self.http("POST", url, Some(body.into()), then);
212 }
213 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
215 self.http("PATCH", url, Some(body.into()), then);
216 }
217 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
219 self.http("DELETE", url, None, then);
220 }
221
222 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
226 self.plugin("device", "model", "", then);
227 }
228
229 pub fn device_locale(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
234 self.plugin("device", "locale", "", then);
235 }
236
237 pub fn pick_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
242 self.plugin("photo", "pick", "", then);
243 }
244
245 pub fn capture_photo(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
252 self.plugin("camera", "capture", "", then);
253 }
254
255 pub fn confirm(
259 &mut self,
260 title: impl Into<String>,
261 message: impl Into<String>,
262 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
263 ) {
264 #[derive(Serialize)]
265 struct Confirm {
266 title: String,
267 message: String,
268 }
269 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
270 .expect("serialize confirm");
271 self.plugin("dialog", "confirm", input, then);
272 }
273
274 pub fn pick_date(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
279 self.plugin("datetime", "date", "", then);
280 }
281
282 pub fn pick_time(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
287 self.plugin("datetime", "time", "", then);
288 }
289}
290
291pub trait MobilerApp: Default {
296 type Event: Serialize + DeserializeOwned + Send + 'static;
297 type Model: Default;
298
299 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
300
301 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
302 let _ = (id, value, model, cx);
303 }
304
305 fn restore(&self, data: &str, model: &mut Self::Model) {
308 let _ = (data, model);
309 }
310
311 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
314 let _ = (model, cx);
315 }
316
317 fn view(&self, model: &Self::Model) -> Widget;
318}
319
320pub struct MobilerShell<A>(PhantomData<fn() -> A>);
322
323impl<A> Default for MobilerShell<A> {
324 fn default() -> Self {
325 Self(PhantomData)
326 }
327}
328
329impl<A: MobilerApp> App for MobilerShell<A> {
330 type Event = Action;
331 type Model = A::Model;
332 type ViewModel = Widget;
333 type Effect = Effect;
334
335 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
336 let app = A::default();
337 let mut cx = Cx::<A::Event>::default();
338 match action {
339 Action::Fired { token } => {
340 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
341 app.update(event, model, &mut cx);
342 }
343 }
344 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
345 Action::Restore { data } => app.restore(&data, model),
346 Action::Start => app.init(model, &mut cx),
347 }
348 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
349 for op in cx.notifications {
350 commands.push(Command::notify_shell(op).build());
351 }
352 for (op, then) in cx.requests {
353 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
354 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
355 }));
356 }
357 for (op, then) in cx.streams {
358 commands.push(Command::stream_from_shell(op).then_send(move |response: PluginResponse| {
361 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
362 }));
363 }
364 commands.push(render());
365 Command::all(commands)
366 }
367
368 fn view(&self, model: &Self::Model) -> Widget {
369 A::default().view(model)
370 }
371}
372
373#[derive(Clone, Debug)]
392pub struct Nav<R> {
393 stack: Vec<R>,
394}
395
396impl<R: Clone + Serialize> Nav<R> {
397 #[must_use]
399 pub fn new(root: R) -> Self {
400 Self { stack: vec![root] }
401 }
402 pub fn push(&mut self, route: R) {
404 self.stack.push(route);
405 }
406 pub fn pop(&mut self) {
408 if self.stack.len() > 1 {
409 self.stack.pop();
410 }
411 }
412 pub fn reset(&mut self, root: R) {
414 self.stack = vec![root];
415 }
416 #[must_use]
418 pub fn current(&self) -> &R {
419 self.stack.last().expect("nav stack is never empty")
420 }
421 #[must_use]
423 pub fn depth(&self) -> u32 {
424 self.stack.len() as u32
425 }
426 #[must_use]
428 pub fn can_go_back(&self) -> bool {
429 self.stack.len() > 1
430 }
431 fn route_key(&self) -> String {
434 serde_json::to_string(self.current()).expect("serialize route")
435 }
436}
437
438fn tok<E: Serialize>(event: E) -> String {
442 serde_json::to_string(&event).expect("serialize event")
443}
444
445#[must_use]
446pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
447 Widget::Text { content: content.into(), style }
448}
449#[must_use]
450pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
451#[must_use]
452pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
453#[must_use]
454pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
455#[must_use]
456pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
457#[must_use]
458pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
459
460#[must_use]
461pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
462 Widget::Image { source: source.into(), shape, ratio }
463}
464#[must_use]
465pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
466 Widget::Badge { label: label.into(), tone }
467}
468#[must_use]
470pub fn color_dot(color: ProjectColor) -> Widget {
471 Widget::ColorDot { color }
472}
473#[must_use]
474pub fn divider() -> Widget { Widget::Divider }
475#[must_use]
477pub fn progress(value: Option<f32>) -> Widget { Widget::Progress { value } }
478#[must_use]
480pub fn skeleton() -> Widget { Widget::Skeleton }
481#[must_use]
485pub fn pdf_view(url: impl Into<String>) -> Widget { Widget::PdfView { url: url.into() } }
486fn one_series(values: Vec<f32>) -> Vec<ChartSeries> {
488 vec![ChartSeries { name: String::new(), values, color: None, goal: None }]
489}
490
491#[must_use]
494pub fn bar_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
495 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Bar, axis: false, legend: false }
496}
497#[must_use]
500pub fn line_chart(values: Vec<f32>, labels: Vec<String>) -> Widget {
501 Widget::Chart { series: one_series(values), labels, style: ChartStyle::Line, axis: false, legend: false }
502}
503#[must_use]
507pub fn chart(series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool) -> Widget {
508 Widget::Chart { series, labels, style, axis, legend }
509}
510#[must_use]
512pub fn stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
513 chart(series, labels, ChartStyle::StackedBar, true, true)
514}
515#[must_use]
517pub fn pct_stacked_bar_chart(series: Vec<ChartSeries>, labels: Vec<String>) -> Widget {
518 chart(series, labels, ChartStyle::StackedBar100, false, true)
519}
520#[must_use]
522pub fn pie_chart(series: Vec<ChartSeries>) -> Widget {
523 chart(series, vec![], ChartStyle::Pie, false, true)
524}
525#[must_use]
527pub fn donut_chart(series: Vec<ChartSeries>) -> Widget {
528 chart(series, vec![], ChartStyle::Donut, false, true)
529}
530#[must_use]
533pub fn rings_chart(series: Vec<ChartSeries>) -> Widget {
534 chart(series, vec![], ChartStyle::Rings, false, true)
535}
536#[must_use]
538pub fn gauge_chart(series: ChartSeries) -> Widget {
539 chart(vec![series], vec![], ChartStyle::Gauge, false, false)
540}
541
542#[must_use]
547pub fn region_chart(
548 regions: Vec<ChartRegion>,
549 ticks: Vec<ChartTick>,
550 x_max: f32,
551 y_max: f32,
552 ref_lines: Vec<ChartRefLine>,
553 legend: Vec<ChartLegendItem>,
554) -> Widget {
555 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: None, legend }
556}
557
558#[must_use]
560pub fn with_bracket(widget: Widget, bracket: ChartBracket) -> Widget {
561 match widget {
562 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, legend, .. } => {
563 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket: Some(bracket), legend }
564 }
565 other => other,
566 }
567}
568
569fn days_in_month(year: u32, month: u8) -> u8 {
571 match month {
572 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
573 4 | 6 | 9 | 11 => 30,
574 2 => if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 { 29 } else { 28 },
575 _ => 30,
576 }
577}
578
579fn weekday(year: u32, month: u8, day: u8) -> u8 {
581 const T: [u32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
582 let y = if month < 3 { year - 1 } else { year };
583 let m = month as usize - 1;
584 ((y + y / 4 - y / 100 + y / 400 + T[m] + u32::from(day)) % 7) as u8
585}
586
587#[must_use]
591pub fn calendar<E: Serialize>(year: u32, month: u8, selected: Option<u8>, on_day: impl Fn(u8) -> E) -> Widget {
592 let n = days_in_month(year, month);
593 let on_day = (1..=n).map(|d| tok(on_day(d))).collect();
594 Widget::Calendar { year, month, first_weekday: weekday(year, month, 1), selected, on_day }
595}
596
597#[must_use]
600pub fn swipe_action<S: Into<String>, E: Serialize>(child: Widget, actions: Vec<(S, Tone, E)>) -> Widget {
601 Widget::SwipeAction {
602 child: Box::new(child),
603 actions: actions
604 .into_iter()
605 .map(|(label, tone, ev)| SwipeButton { label: label.into(), tone, on_tap: tok(ev) })
606 .collect(),
607 }
608}
609#[must_use]
610pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
611
612#[must_use]
613pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
614#[must_use]
615pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
616#[must_use]
617pub fn card(child: Widget, style: CardStyle) -> Widget {
618 Widget::Card { child: Box::new(child), style, on_press: None }
619}
620#[must_use]
622pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
623 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
624}
625#[must_use]
628pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
629 Widget::Box { children, align, scrim }
630}
631#[must_use]
632pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
633#[must_use]
635pub fn scroller(children: Vec<Widget>) -> Widget { Widget::Scroller { children } }
636#[must_use]
638pub fn avatar(source: impl Into<String>) -> Widget { Widget::Avatar { source: source.into(), status: None } }
639#[must_use]
641pub fn avatar_status(source: impl Into<String>, status: Tone) -> Widget {
642 Widget::Avatar { source: source.into(), status: Some(status) }
643}
644#[must_use]
646pub fn rating(value: u32, max: u8) -> Widget { Widget::Rating { value, max, on_rate: None } }
647#[must_use]
649pub fn rating_input<E: Serialize>(value: u32, max: u8, on_rate: Vec<E>) -> Widget {
650 Widget::Rating { value, max, on_rate: Some(on_rate.into_iter().map(tok).collect()) }
651}
652
653#[must_use]
654pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
655 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
656}
657#[must_use]
658pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
659 Widget::IconButton { icon, on_press: tok(on_press) }
660}
661#[must_use]
662pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
663 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
664}
665#[must_use]
666pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
667 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind: FieldKind::Text, error: None }
668}
669#[must_use]
673pub fn field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>, kind: FieldKind, error: Option<String>) -> Widget {
674 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into(), kind, error }
675}
676#[must_use]
678pub fn secure_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
679 field(id, placeholder, value, FieldKind::Secure, None)
680}
681#[must_use]
683pub fn email_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
684 field(id, placeholder, value, FieldKind::Email, None)
685}
686#[must_use]
688pub fn number_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
689 field(id, placeholder, value, FieldKind::Number, None)
690}
691#[must_use]
693pub fn decimal_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
694 field(id, placeholder, value, FieldKind::Decimal, None)
695}
696#[must_use]
698pub fn phone_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
699 field(id, placeholder, value, FieldKind::Phone, None)
700}
701#[must_use]
703pub fn url_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
704 field(id, placeholder, value, FieldKind::Url, None)
705}
706#[must_use]
708pub fn multiline_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
709 field(id, placeholder, value, FieldKind::Multiline, None)
710}
711#[must_use]
714pub fn with_error(widget: Widget, message: impl Into<String>) -> Widget {
715 match widget {
716 Widget::TextField { id, placeholder, value, kind, .. } =>
717 Widget::TextField { id, placeholder, value, kind, error: Some(message.into()) },
718 other => other,
719 }
720}
721#[must_use]
723pub fn search_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
724 Widget::SearchField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
725}
726#[must_use]
728pub fn segment<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Segment {
729 Segment { label: label.into(), selected, on_select: tok(on_select) }
730}
731#[must_use]
733pub fn segmented(segments: Vec<Segment>) -> Widget {
734 Widget::Segmented { segments }
735}
736#[must_use]
737pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
738 Widget::Toggle { id: id.into(), label: label.into(), value }
739}
740#[must_use]
741pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
742 Widget::Checkbox { id: id.into(), label: label.into(), value }
743}
744#[must_use]
745pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
746 Widget::Slider { id: id.into(), value, max }
747}
748#[must_use]
749pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
750 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
751}
752
753#[must_use]
755pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
756 Tab { label: label.into(), selected, on_select: tok(on_select), icon: None }
757}
758
759#[must_use]
761pub fn tab_icon<E: Serialize>(label: impl Into<String>, icon: Icon, selected: bool, on_select: E) -> Tab {
762 Tab { label: label.into(), selected, on_select: tok(on_select), icon: Some(icon) }
763}
764
765#[must_use]
768pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
769 let title = title.into();
770 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 }
772}
773
774#[must_use]
778pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
779 let title = title.into();
780 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 }
781}
782
783#[must_use]
788pub fn nav_scaffold<R, E>(
789 title: impl Into<String>,
790 dark_mode: bool,
791 tabs: Vec<Tab>,
792 body: Widget,
793 nav: &Nav<R>,
794 on_back: E,
795) -> Widget
796where
797 R: Clone + Serialize,
798 E: Serialize,
799{
800 Widget::Scaffold {
801 title: title.into(),
802 body: Box::new(body),
803 tabs,
804 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
805 dark_mode,
806 theme: None,
807 fab: None,
808 sheet: None,
809 on_refresh: None,
810 refreshing: false,
811 route: nav.route_key(),
812 depth: nav.depth(),
813 }
814}
815
816pub fn with_theme(widget: Widget, theme: Theme) -> Widget {
820 match widget {
821 Widget::Scaffold { title, body, tabs, back, dark_mode, fab, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
822 title,
823 body,
824 tabs,
825 back,
826 dark_mode,
827 theme: Some(theme),
828 fab,
829 sheet,
830 on_refresh,
831 refreshing,
832 route,
833 depth,
834 },
835 other => other,
836 }
837}
838
839pub fn with_fab<E: Serialize>(widget: Widget, icon: Icon, on_press: E) -> Widget {
842 match widget {
843 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, sheet, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
844 title,
845 body,
846 tabs,
847 back,
848 dark_mode,
849 theme,
850 fab: Some(Fab { icon, on_press: tok(on_press) }),
851 sheet,
852 on_refresh,
853 refreshing,
854 route,
855 depth,
856 },
857 other => other,
858 }
859}
860
861pub fn with_sheet<E: Serialize>(widget: Widget, title: impl Into<String>, child: Widget, on_dismiss: E) -> Widget {
864 match widget {
865 Widget::Scaffold { title: t, body, tabs, back, dark_mode, theme, fab, on_refresh, refreshing, route, depth, .. } => Widget::Scaffold {
866 title: t,
867 body,
868 tabs,
869 back,
870 dark_mode,
871 theme,
872 fab,
873 sheet: Some(Sheet { title: title.into(), child: Box::new(child), on_dismiss: tok(on_dismiss) }),
874 on_refresh,
875 refreshing,
876 route,
877 depth,
878 },
879 other => other,
880 }
881}
882
883pub fn with_refresh<E: Serialize>(widget: Widget, refreshing: bool, on_refresh: E) -> Widget {
887 match widget {
888 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, route, depth, .. } => Widget::Scaffold {
889 title,
890 body,
891 tabs,
892 back,
893 dark_mode,
894 theme,
895 fab,
896 sheet,
897 on_refresh: Some(tok(on_refresh)),
898 refreshing,
899 route,
900 depth,
901 },
902 other => other,
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use super::*;
909 use serde::Serialize;
910
911 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
912 enum Route {
913 Home,
914 Detail(u32),
915 }
916
917 #[derive(Serialize)]
918 enum Ev {
919 Tap,
920 Open(u32),
921 }
922
923 #[test]
926 fn nav_push_pop_depth() {
927 let mut nav = Nav::new(Route::Home);
928 assert_eq!(nav.depth(), 1);
929 assert!(!nav.can_go_back());
930
931 nav.push(Route::Detail(7));
932 assert_eq!(nav.depth(), 2);
933 assert!(nav.can_go_back());
934 assert!(matches!(nav.current(), Route::Detail(7)));
935
936 nav.pop();
937 assert_eq!(nav.depth(), 1);
938 assert!(matches!(nav.current(), Route::Home));
939
940 nav.pop(); assert_eq!(nav.depth(), 1);
942 }
943
944 #[test]
945 fn nav_reset_replaces_stack() {
946 let mut nav = Nav::new(Route::Home);
947 nav.push(Route::Detail(1));
948 nav.push(Route::Detail(2));
949 nav.reset(Route::Detail(9));
950 assert_eq!(nav.depth(), 1);
951 assert!(matches!(nav.current(), Route::Detail(9)));
952 }
953
954 #[test]
955 fn nav_route_key_is_serialization() {
956 let nav = Nav::new(Route::Detail(3));
957 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
958 }
959
960 #[test]
963 fn scaffold_sets_route_depth_and_no_back() {
964 match scaffold("Home", false, vec![], text("x")) {
965 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
966 assert_eq!(route, "Home");
967 assert_eq!(depth, 1);
968 assert!(back.is_none());
969 assert!(!dark_mode);
970 }
971 other => panic!("expected Scaffold, got {other:?}"),
972 }
973 }
974
975 #[test]
976 fn scaffold_back_is_depth_2_with_back() {
977 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
978 Widget::Scaffold { depth, back, dark_mode, .. } => {
979 assert_eq!(depth, 2);
980 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
981 assert!(dark_mode);
982 }
983 other => panic!("expected Scaffold, got {other:?}"),
984 }
985 }
986
987 #[test]
988 fn nav_scaffold_shows_back_only_when_poppable() {
989 let mut nav = Nav::new(Route::Home);
990 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
992 Widget::Scaffold { back, depth, route, .. } => {
993 assert!(back.is_none());
994 assert_eq!(depth, 1);
995 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
996 }
997 other => panic!("expected Scaffold, got {other:?}"),
998 }
999 nav.push(Route::Detail(2));
1001 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
1002 Widget::Scaffold { back, depth, .. } => {
1003 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1004 assert_eq!(depth, 2);
1005 }
1006 other => panic!("expected Scaffold, got {other:?}"),
1007 }
1008 }
1009
1010 #[test]
1011 fn buttons_carry_serialized_event_tokens() {
1012 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
1013 Widget::Button { label, on_press, .. } => {
1014 assert_eq!(label, "Go");
1015 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
1016 }
1017 other => panic!("expected Button, got {other:?}"),
1018 }
1019 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
1020 Widget::Card { on_press, .. } => {
1021 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
1022 }
1023 other => panic!("expected Card, got {other:?}"),
1024 }
1025 match card(text("c"), CardStyle::Elevated) {
1027 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
1028 other => panic!("expected Card, got {other:?}"),
1029 }
1030 }
1031
1032 #[test]
1035 fn cx_notify_and_save_enqueue_notifications() {
1036 let mut cx = Cx::<Ev>::default();
1037 cx.notify("toast", "show", "hi");
1038 cx.save("blob");
1039 assert_eq!(cx.notifications.len(), 2);
1040 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
1041 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
1042 assert!(cx.requests.is_empty());
1043 }
1044
1045 #[test]
1046 fn cx_http_helpers_build_requests() {
1047 let mut cx = Cx::<Ev>::default();
1048 cx.get("http://h/x", |_| Ev::Tap);
1049 cx.post("http://h/y", "hello", |_| Ev::Tap);
1050 cx.patch("http://h/z", "patch", |_| Ev::Tap);
1051 cx.delete("http://h/d", |_| Ev::Tap);
1052
1053 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
1054 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
1055 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
1056
1057 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
1058 assert_eq!(get_input["url"], "http://h/x");
1059 assert!(get_input["body"].is_null());
1060
1061 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
1062 assert_eq!(post_input["url"], "http://h/y");
1063 assert_eq!(post_input["body"], "hello");
1064 }
1065
1066 #[test]
1067 fn cx_pick_and_capture_photo_request_the_right_plugin() {
1068 let mut cx = Cx::<Ev>::default();
1069 cx.pick_photo(|_| Ev::Tap);
1070 cx.capture_photo(|_| Ev::Tap);
1071 assert_eq!(cx.requests.len(), 2);
1072 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", ""));
1075 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", ""));
1076 }
1077
1078 #[test]
1079 fn cx_capture_photo_routes_success_and_cancel() {
1080 let mut cx = Cx::<Ev>::default();
1082 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1083 let (_, then) = cx.requests.pop().unwrap();
1084 assert!(matches!(then(PluginResponse { ok: true, output: "file:///tmp/shot.jpg".into() }), Ev::Open(7)));
1085
1086 let mut cx = Cx::<Ev>::default();
1088 cx.capture_photo(|r| if r.ok { Ev::Open(7) } else { Ev::Tap });
1089 let (_, then) = cx.requests.pop().unwrap();
1090 assert!(matches!(then(PluginResponse { ok: false, output: String::new() }), Ev::Tap));
1091 }
1092
1093 #[test]
1094 fn cx_notify_capabilities_map_to_the_right_plugin_and_op() {
1095 let mut cx = Cx::<Ev>::default();
1096 cx.copy("c");
1097 cx.share("s");
1098 cx.open_url("u");
1099 cx.toast("t");
1100 cx.haptic("heavy");
1101 let got: Vec<(&str, &str, &str)> = cx
1102 .notifications
1103 .iter()
1104 .map(|n| (n.plugin.as_str(), n.op.as_str(), n.input.as_str()))
1105 .collect();
1106 assert_eq!(
1107 got,
1108 vec![
1109 ("clipboard", "copy", "c"),
1110 ("share", "text", "s"),
1111 ("browser", "open", "u"),
1112 ("toast", "show", "t"),
1113 ("haptics", "heavy", ""), ]
1115 );
1116 assert!(cx.requests.is_empty());
1117 }
1118
1119 #[test]
1120 fn cx_device_model_is_a_request_not_a_notification() {
1121 let mut cx = Cx::<Ev>::default();
1122 cx.device_model(|_| Ev::Tap);
1123 assert!(cx.notifications.is_empty());
1124 assert_eq!(cx.requests.len(), 1);
1125 let (call, _) = &cx.requests[0];
1126 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "model", ""));
1127 }
1128
1129 #[test]
1130 fn cx_device_locale_requests_the_device_locale_op() {
1131 let mut cx = Cx::<Ev>::default();
1132 cx.device_locale(|_| Ev::Tap);
1133 assert!(cx.notifications.is_empty());
1134 assert_eq!(cx.requests.len(), 1);
1135 let (call, _) = &cx.requests[0];
1136 assert_eq!((call.plugin.as_str(), call.op.as_str(), call.input.as_str()), ("device", "locale", ""));
1137 }
1138
1139 #[test]
1140 fn cx_subscribe_enqueues_a_keyed_stream_and_maps_each_event() {
1141 let mut cx = Cx::<Ev>::default();
1142 cx.subscribe("ws", "websocket", "stream", "wss://h/x", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1143 assert!(cx.notifications.is_empty());
1145 assert!(cx.requests.is_empty());
1146 assert_eq!(cx.streams.len(), 1);
1147 let (call, on_event) = &cx.streams[0];
1148 assert_eq!(
1149 (call.key.as_str(), call.plugin.as_str(), call.op.as_str(), call.input.as_str()),
1150 ("ws", "websocket", "stream", "wss://h/x")
1151 );
1152 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame1".into() }), Ev::Tap));
1154 assert!(matches!(on_event(PluginResponse { ok: true, output: "frame2".into() }), Ev::Tap));
1155 assert!(matches!(on_event(PluginResponse { ok: false, output: "closed".into() }), Ev::Open(0)));
1156 }
1157
1158 #[test]
1159 fn cx_unsubscribe_enqueues_the_teardown_notify_keyed_by_subscription() {
1160 let mut cx = Cx::<Ev>::default();
1161 cx.unsubscribe("ws");
1162 assert!(cx.streams.is_empty());
1163 assert_eq!(cx.notifications.len(), 1);
1164 assert_eq!(
1166 cx.notifications[0],
1167 PluginNotify { plugin: "stream".into(), op: "unsubscribe".into(), input: "ws".into() }
1168 );
1169 }
1170
1171 #[test]
1172 fn cx_confirm_serializes_title_message_and_routes_ok() {
1173 let mut cx = Cx::<Ev>::default();
1174 cx.confirm("Delete?", "This cannot be undone.", |r| if r.ok { Ev::Tap } else { Ev::Open(0) });
1175 let (call, then) = cx.requests.pop().unwrap();
1176 assert_eq!((call.plugin.as_str(), call.op.as_str()), ("dialog", "confirm"));
1177 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap();
1178 assert_eq!(v["title"], "Delete?");
1179 assert_eq!(v["message"], "This cannot be undone.");
1180 assert!(matches!(then(PluginResponse { ok: true, output: "ok".into() }), Ev::Tap));
1182 }
1183
1184 #[test]
1187 fn text_builders_carry_their_style() {
1188 assert!(matches!(text("b"), Widget::Text { style: TextStyle::Body, .. }));
1189 assert!(matches!(title("t"), Widget::Text { style: TextStyle::Title, .. }));
1190 assert!(matches!(subtitle("s"), Widget::Text { style: TextStyle::Subtitle, .. }));
1191 assert!(matches!(caption("c"), Widget::Text { style: TextStyle::Caption, .. }));
1192 assert!(matches!(emphasis("e"), Widget::Text { style: TextStyle::Emphasis, .. }));
1193 }
1194
1195 #[test]
1196 fn layout_and_content_builders_produce_their_variants() {
1197 assert!(matches!(row(vec![text("a")]), Widget::Row { children } if children.len() == 1));
1198 assert!(matches!(column(vec![]), Widget::Column { children } if children.is_empty()));
1199 assert!(matches!(grid(vec![text("a"), text("b")]), Widget::Grid { children } if children.len() == 2));
1200 assert!(matches!(divider(), Widget::Divider));
1201 assert!(matches!(bar_chart(vec![1.0, 2.0], vec![]), Widget::Chart { style: ChartStyle::Bar, series, .. } if series[0].values.len() == 2));
1202 assert!(matches!(line_chart(vec![1.0], vec![]), Widget::Chart { style: ChartStyle::Line, .. }));
1203 assert!(matches!(donut_chart(vec![ChartSeries::new("a", vec![1.0])]), Widget::Chart { style: ChartStyle::Donut, legend: true, .. }));
1204 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)));
1205 let rc = with_bracket(
1206 region_chart(
1207 vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical()],
1208 vec![ChartTick::new(3.0, "3 Mt.")],
1209 65.0, 80.0,
1210 vec![ChartRefLine::target(80.0, "CHF 80'000"), ChartRefLine::max(90.0, "CHF 90'000")],
1211 vec![ChartLegendItem::new("Gap", Rgb::new(0x5A, 0x7D, 0x9A))],
1212 ),
1213 ChartBracket::new(60.0, 80.0, "Ceiling").with_info(),
1214 );
1215 assert!(matches!(rc, Widget::RegionChart { bracket: Some(b), regions, ref_lines, .. } if regions[0].vertical && ref_lines[1].dashed && b.info));
1216 assert!(matches!(
1218 calendar(2026, 6, Some(3), |d| Ev::Open(u32::from(d))),
1219 Widget::Calendar { first_weekday: 1, selected: Some(3), on_day, .. } if on_day.len() == 30
1220 ));
1221 assert!(matches!(
1222 swipe_action(text("row"), vec![("Delete", Tone::Danger, Ev::Tap)]),
1223 Widget::SwipeAction { actions, .. } if actions.len() == 1
1224 ));
1225 assert!(matches!(spacer(Spacing::Lg), Widget::Spacer { .. }));
1226 assert!(matches!(image("u", ImageShape::Circle, ImageRatio::Square), Widget::Image { .. }));
1227 assert!(matches!(badge("new", Tone::Success), Widget::Badge { .. }));
1228 assert!(matches!(color_dot(ProjectColor::Teal), Widget::ColorDot { .. }));
1229 assert!(matches!(card(text("x"), CardStyle::Filled), Widget::Card { on_press: None, .. }));
1230 assert!(matches!(stack(BoxAlign::Center, true, vec![]), Widget::Box { scrim: true, .. }));
1232 }
1233
1234 #[test]
1235 fn input_builders_carry_ids_values_and_event_tokens() {
1236 assert!(matches!(text_field("id", "ph", "v"), Widget::TextField { kind: FieldKind::Text, error: None, .. }));
1237 assert!(matches!(pdf_view("https://x/report.pdf"), Widget::PdfView { url } if url == "https://x/report.pdf"));
1238 assert!(matches!(secure_field("pw", "Password", ""), Widget::TextField { kind: FieldKind::Secure, .. }));
1239 assert!(matches!(email_field("e", "", ""), Widget::TextField { kind: FieldKind::Email, .. }));
1240 assert!(matches!(multiline_field("note", "", ""), Widget::TextField { kind: FieldKind::Multiline, .. }));
1241 assert!(matches!(with_error(email_field("e", "", "x"), "Invalid"), Widget::TextField { error: Some(m), kind: FieldKind::Email, .. } if m == "Invalid"));
1242 assert!(matches!(with_error(divider(), "ignored"), Widget::Divider));
1243 assert!(matches!(toggle("t", "l", true), Widget::Toggle { value: true, .. }));
1244 assert!(matches!(checkbox("c", "l", false), Widget::Checkbox { value: false, .. }));
1245 assert!(matches!(slider("s", 3, 10), Widget::Slider { value: 3, max: 10, .. }));
1246
1247 match chip("Latte", true, Ev::Open(2)) {
1248 Widget::Chip { selected, on_press, .. } => {
1249 assert!(selected);
1250 assert_eq!(on_press, serde_json::to_string(&Ev::Open(2)).unwrap());
1251 }
1252 other => panic!("expected Chip, got {other:?}"),
1253 }
1254 match stepper(5, Ev::Tap, Ev::Open(1)) {
1255 Widget::Stepper { value, on_decrement, on_increment } => {
1256 assert_eq!(value, 5);
1257 assert_eq!(on_decrement, serde_json::to_string(&Ev::Tap).unwrap());
1258 assert_eq!(on_increment, serde_json::to_string(&Ev::Open(1)).unwrap());
1259 }
1260 other => panic!("expected Stepper, got {other:?}"),
1261 }
1262 let t = tab("Home", true, Ev::Tap);
1263 assert_eq!(t.label, "Home");
1264 assert!(t.selected);
1265 assert_eq!(t.on_select, serde_json::to_string(&Ev::Tap).unwrap());
1266 }
1267
1268 #[test]
1271 fn widget_tree_round_trips_through_serde() {
1272 let tree = scaffold(
1273 "Home",
1274 true,
1275 vec![tab("A", true, Ev::Tap)],
1276 column(vec![
1277 title("Hi"),
1278 row(vec![button("Go", ButtonStyle::Filled, Ev::Open(3)), chip("x", false, Ev::Tap)]),
1279 image("u", ImageShape::Rounded, ImageRatio::Wide),
1280 slider("s", 2, 5),
1281 ]),
1282 );
1283 let s = serde_json::to_string(&tree).unwrap();
1284 let back: Widget = serde_json::from_str(&s).unwrap();
1285 assert_eq!(s, serde_json::to_string(&back).unwrap());
1286 }
1287
1288 #[test]
1289 fn actions_and_input_values_round_trip() {
1290 let actions = vec![
1291 Action::Fired { token: serde_json::to_string(&Ev::Open(1)).unwrap() },
1292 Action::Input { id: "n".into(), value: InputValue::Int(7) },
1293 Action::Input { id: "n".into(), value: InputValue::Text("hi".into()) },
1294 Action::Input { id: "n".into(), value: InputValue::Bool(true) },
1295 Action::Restore { data: "blob".into() },
1296 Action::Start,
1297 ];
1298 for a in actions {
1299 let s = serde_json::to_string(&a).unwrap();
1300 let back: Action = serde_json::from_str(&s).unwrap();
1301 assert_eq!(s, serde_json::to_string(&back).unwrap());
1302 }
1303 }
1304
1305 #[derive(Default)]
1308 struct CounterModel {
1309 count: i32,
1310 restored: String,
1311 started: bool,
1312 last_input: String,
1313 }
1314
1315 #[derive(serde::Serialize, serde::Deserialize)]
1316 enum CounterEv {
1317 Inc,
1318 Add(i32),
1319 }
1320
1321 #[derive(Default)]
1322 struct CounterApp;
1323
1324 impl MobilerApp for CounterApp {
1325 type Event = CounterEv;
1326 type Model = CounterModel;
1327 fn update(&self, ev: CounterEv, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1328 match ev {
1329 CounterEv::Inc => model.count += 1,
1330 CounterEv::Add(n) => model.count += n,
1331 }
1332 }
1333 fn input(&self, id: &str, value: InputValue, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1334 if let InputValue::Text(t) = value {
1335 model.last_input = format!("{id}={t}");
1336 }
1337 }
1338 fn restore(&self, data: &str, model: &mut CounterModel) {
1339 model.restored = data.to_string();
1340 }
1341 fn init(&self, model: &mut CounterModel, _cx: &mut Cx<CounterEv>) {
1342 model.started = true;
1343 }
1344 fn view(&self, model: &CounterModel) -> Widget {
1345 text(format!("{}", model.count))
1346 }
1347 }
1348
1349 #[test]
1350 fn shell_dispatches_fired_input_restore_and_start() {
1351 use crux_core::App as _;
1352 let shell = MobilerShell::<CounterApp>::default();
1353 let mut m = CounterModel::default();
1354
1355 let _ = shell.update(Action::Fired { token: serde_json::to_string(&CounterEv::Add(5)).unwrap() }, &mut m);
1357 assert_eq!(m.count, 5);
1358 let _ = shell.update(Action::Input { id: "name".into(), value: InputValue::Text("bob".into()) }, &mut m);
1360 assert_eq!(m.last_input, "name=bob");
1361 let _ = shell.update(Action::Restore { data: "saved".into() }, &mut m);
1363 assert_eq!(m.restored, "saved");
1364 let _ = shell.update(Action::Start, &mut m);
1366 assert!(m.started);
1367 assert!(matches!(shell.view(&m), Widget::Text { .. }));
1369 }
1370
1371 #[test]
1372 fn shell_ignores_a_malformed_fired_token() {
1373 use crux_core::App as _;
1374 let shell = MobilerShell::<CounterApp>::default();
1375 let mut m = CounterModel::default();
1376 let _ = shell.update(Action::Fired { token: "not a valid token".into() }, &mut m);
1379 assert_eq!(m.count, 0);
1380 }
1381}