1use std::marker::PhantomData;
9
10use crux_core::{
11 App, Command,
12 capability::Operation,
13 macros::effect,
14 render::{RenderOperation, render},
15};
16use facet::Facet;
17use serde::{Deserialize, Serialize, de::DeserializeOwned};
18
19pub use mobiler_ui::{
20 Action, BoxAlign, ButtonStyle, CardStyle, Icon, ImageRatio, ImageShape, InputValue,
21 ProjectColor, Spacing, Tab, TextStyle, Tone, Widget,
22};
23
24#[effect(facet_typegen)]
28#[derive(Debug)]
29pub enum Effect {
30 Render(RenderOperation),
31 PluginNotify(PluginNotify),
33 Plugin(PluginCall),
35}
36
37#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
38pub struct PluginNotify {
39 pub plugin: String,
40 pub op: String,
41 pub input: String,
42}
43impl Operation for PluginNotify {
44 type Output = ();
45}
46
47#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct PluginCall {
49 pub plugin: String,
50 pub op: String,
51 pub input: String,
52}
53impl Operation for PluginCall {
54 type Output = PluginResponse;
55}
56
57#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
58pub struct PluginResponse {
59 pub ok: bool,
60 pub output: String,
61}
62
63type Continuation<E> = Box<dyn FnOnce(PluginResponse) -> E + Send>;
64
65pub struct Cx<E> {
68 notifications: Vec<PluginNotify>,
69 requests: Vec<(PluginCall, Continuation<E>)>,
70}
71
72impl<E> Default for Cx<E> {
73 fn default() -> Self {
74 Self { notifications: Vec::new(), requests: Vec::new() }
75 }
76}
77
78impl<E> Cx<E> {
79 pub fn notify(&mut self, plugin: impl Into<String>, op: impl Into<String>, input: impl Into<String>) {
81 self.notifications.push(PluginNotify { plugin: plugin.into(), op: op.into(), input: input.into() });
82 }
83
84 pub fn plugin(
87 &mut self,
88 plugin: impl Into<String>,
89 op: impl Into<String>,
90 input: impl Into<String>,
91 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
92 ) {
93 self.requests
94 .push((PluginCall { plugin: plugin.into(), op: op.into(), input: input.into() }, Box::new(then)));
95 }
96
97 pub fn save(&mut self, data: impl Into<String>) {
99 self.notify("storage", "save", data);
100 }
101
102 pub fn copy(&mut self, text: impl Into<String>) {
104 self.notify("clipboard", "copy", text);
105 }
106
107 pub fn share(&mut self, text: impl Into<String>) {
109 self.notify("share", "text", text);
110 }
111
112 pub fn open_url(&mut self, url: impl Into<String>) {
115 self.notify("browser", "open", url);
116 }
117
118 pub fn toast(&mut self, text: impl Into<String>) {
120 self.notify("toast", "show", text);
121 }
122
123 pub fn haptic(&mut self, style: impl Into<String>) {
126 self.notify("haptics", style, "");
127 }
128
129 pub fn http(
134 &mut self,
135 method: impl Into<String>,
136 url: impl Into<String>,
137 body: Option<String>,
138 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
139 ) {
140 #[derive(Serialize)]
141 struct HttpReq {
142 url: String,
143 body: Option<String>,
144 }
145 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
146 .expect("serialize http request");
147 self.plugin("http", method, input, then);
148 }
149
150 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
152 self.http("GET", url, None, then);
153 }
154 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
156 self.http("POST", url, Some(body.into()), then);
157 }
158 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
160 self.http("PATCH", url, Some(body.into()), then);
161 }
162 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
164 self.http("DELETE", url, None, then);
165 }
166
167 pub fn device_model(&mut self, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
171 self.plugin("device", "model", "", then);
172 }
173
174 pub fn confirm(
178 &mut self,
179 title: impl Into<String>,
180 message: impl Into<String>,
181 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
182 ) {
183 #[derive(Serialize)]
184 struct Confirm {
185 title: String,
186 message: String,
187 }
188 let input = serde_json::to_string(&Confirm { title: title.into(), message: message.into() })
189 .expect("serialize confirm");
190 self.plugin("dialog", "confirm", input, then);
191 }
192}
193
194pub trait MobilerApp: Default {
199 type Event: Serialize + DeserializeOwned + Send + 'static;
200 type Model: Default;
201
202 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
203
204 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
205 let _ = (id, value, model, cx);
206 }
207
208 fn restore(&self, data: &str, model: &mut Self::Model) {
211 let _ = (data, model);
212 }
213
214 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
217 let _ = (model, cx);
218 }
219
220 fn view(&self, model: &Self::Model) -> Widget;
221}
222
223pub struct MobilerShell<A>(PhantomData<fn() -> A>);
225
226impl<A> Default for MobilerShell<A> {
227 fn default() -> Self {
228 Self(PhantomData)
229 }
230}
231
232impl<A: MobilerApp> App for MobilerShell<A> {
233 type Event = Action;
234 type Model = A::Model;
235 type ViewModel = Widget;
236 type Effect = Effect;
237
238 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
239 let app = A::default();
240 let mut cx = Cx::<A::Event>::default();
241 match action {
242 Action::Fired { token } => {
243 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
244 app.update(event, model, &mut cx);
245 }
246 }
247 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
248 Action::Restore { data } => app.restore(&data, model),
249 Action::Start => app.init(model, &mut cx),
250 }
251 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
252 for op in cx.notifications {
253 commands.push(Command::notify_shell(op).build());
254 }
255 for (op, then) in cx.requests {
256 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
257 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
258 }));
259 }
260 commands.push(render());
261 Command::all(commands)
262 }
263
264 fn view(&self, model: &Self::Model) -> Widget {
265 A::default().view(model)
266 }
267}
268
269#[derive(Clone, Debug)]
288pub struct Nav<R> {
289 stack: Vec<R>,
290}
291
292impl<R: Clone + Serialize> Nav<R> {
293 #[must_use]
295 pub fn new(root: R) -> Self {
296 Self { stack: vec![root] }
297 }
298 pub fn push(&mut self, route: R) {
300 self.stack.push(route);
301 }
302 pub fn pop(&mut self) {
304 if self.stack.len() > 1 {
305 self.stack.pop();
306 }
307 }
308 pub fn reset(&mut self, root: R) {
310 self.stack = vec![root];
311 }
312 #[must_use]
314 pub fn current(&self) -> &R {
315 self.stack.last().expect("nav stack is never empty")
316 }
317 #[must_use]
319 pub fn depth(&self) -> u32 {
320 self.stack.len() as u32
321 }
322 #[must_use]
324 pub fn can_go_back(&self) -> bool {
325 self.stack.len() > 1
326 }
327 fn route_key(&self) -> String {
330 serde_json::to_string(self.current()).expect("serialize route")
331 }
332}
333
334fn tok<E: Serialize>(event: E) -> String {
338 serde_json::to_string(&event).expect("serialize event")
339}
340
341#[must_use]
342pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
343 Widget::Text { content: content.into(), style }
344}
345#[must_use]
346pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
347#[must_use]
348pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
349#[must_use]
350pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
351#[must_use]
352pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
353#[must_use]
354pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
355
356#[must_use]
357pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
358 Widget::Image { source: source.into(), shape, ratio }
359}
360#[must_use]
361pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
362 Widget::Badge { label: label.into(), tone }
363}
364#[must_use]
366pub fn color_dot(color: ProjectColor) -> Widget {
367 Widget::ColorDot { color }
368}
369#[must_use]
370pub fn divider() -> Widget { Widget::Divider }
371#[must_use]
372pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
373
374#[must_use]
375pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
376#[must_use]
377pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
378#[must_use]
379pub fn card(child: Widget, style: CardStyle) -> Widget {
380 Widget::Card { child: Box::new(child), style, on_press: None }
381}
382#[must_use]
384pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
385 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
386}
387#[must_use]
390pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
391 Widget::Box { children, align, scrim }
392}
393#[must_use]
394pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
395
396#[must_use]
397pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
398 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
399}
400#[must_use]
401pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
402 Widget::IconButton { icon, on_press: tok(on_press) }
403}
404#[must_use]
405pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
406 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
407}
408#[must_use]
409pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
410 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
411}
412#[must_use]
413pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
414 Widget::Toggle { id: id.into(), label: label.into(), value }
415}
416#[must_use]
417pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
418 Widget::Checkbox { id: id.into(), label: label.into(), value }
419}
420#[must_use]
421pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
422 Widget::Slider { id: id.into(), value, max }
423}
424#[must_use]
425pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
426 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
427}
428
429#[must_use]
431pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
432 Tab { label: label.into(), selected, on_select: tok(on_select) }
433}
434
435#[must_use]
438pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
439 let title = title.into();
440 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, depth: 1 }
442}
443
444#[must_use]
448pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
449 let title = title.into();
450 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, depth: 2 }
451}
452
453#[must_use]
458pub fn nav_scaffold<R, E>(
459 title: impl Into<String>,
460 dark_mode: bool,
461 tabs: Vec<Tab>,
462 body: Widget,
463 nav: &Nav<R>,
464 on_back: E,
465) -> Widget
466where
467 R: Clone + Serialize,
468 E: Serialize,
469{
470 Widget::Scaffold {
471 title: title.into(),
472 body: Box::new(body),
473 tabs,
474 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
475 dark_mode,
476 route: nav.route_key(),
477 depth: nav.depth(),
478 }
479}
480
481#[cfg(test)]
482mod tests {
483 use super::*;
484 use serde::Serialize;
485
486 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
487 enum Route {
488 Home,
489 Detail(u32),
490 }
491
492 #[derive(Serialize)]
493 enum Ev {
494 Tap,
495 Open(u32),
496 }
497
498 #[test]
501 fn nav_push_pop_depth() {
502 let mut nav = Nav::new(Route::Home);
503 assert_eq!(nav.depth(), 1);
504 assert!(!nav.can_go_back());
505
506 nav.push(Route::Detail(7));
507 assert_eq!(nav.depth(), 2);
508 assert!(nav.can_go_back());
509 assert!(matches!(nav.current(), Route::Detail(7)));
510
511 nav.pop();
512 assert_eq!(nav.depth(), 1);
513 assert!(matches!(nav.current(), Route::Home));
514
515 nav.pop(); assert_eq!(nav.depth(), 1);
517 }
518
519 #[test]
520 fn nav_reset_replaces_stack() {
521 let mut nav = Nav::new(Route::Home);
522 nav.push(Route::Detail(1));
523 nav.push(Route::Detail(2));
524 nav.reset(Route::Detail(9));
525 assert_eq!(nav.depth(), 1);
526 assert!(matches!(nav.current(), Route::Detail(9)));
527 }
528
529 #[test]
530 fn nav_route_key_is_serialization() {
531 let nav = Nav::new(Route::Detail(3));
532 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
533 }
534
535 #[test]
538 fn scaffold_sets_route_depth_and_no_back() {
539 match scaffold("Home", false, vec![], text("x")) {
540 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
541 assert_eq!(route, "Home");
542 assert_eq!(depth, 1);
543 assert!(back.is_none());
544 assert!(!dark_mode);
545 }
546 other => panic!("expected Scaffold, got {other:?}"),
547 }
548 }
549
550 #[test]
551 fn scaffold_back_is_depth_2_with_back() {
552 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
553 Widget::Scaffold { depth, back, dark_mode, .. } => {
554 assert_eq!(depth, 2);
555 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
556 assert!(dark_mode);
557 }
558 other => panic!("expected Scaffold, got {other:?}"),
559 }
560 }
561
562 #[test]
563 fn nav_scaffold_shows_back_only_when_poppable() {
564 let mut nav = Nav::new(Route::Home);
565 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
567 Widget::Scaffold { back, depth, route, .. } => {
568 assert!(back.is_none());
569 assert_eq!(depth, 1);
570 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
571 }
572 other => panic!("expected Scaffold, got {other:?}"),
573 }
574 nav.push(Route::Detail(2));
576 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
577 Widget::Scaffold { back, depth, .. } => {
578 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
579 assert_eq!(depth, 2);
580 }
581 other => panic!("expected Scaffold, got {other:?}"),
582 }
583 }
584
585 #[test]
586 fn buttons_carry_serialized_event_tokens() {
587 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
588 Widget::Button { label, on_press, .. } => {
589 assert_eq!(label, "Go");
590 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
591 }
592 other => panic!("expected Button, got {other:?}"),
593 }
594 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
595 Widget::Card { on_press, .. } => {
596 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
597 }
598 other => panic!("expected Card, got {other:?}"),
599 }
600 match card(text("c"), CardStyle::Elevated) {
602 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
603 other => panic!("expected Card, got {other:?}"),
604 }
605 }
606
607 #[test]
610 fn cx_notify_and_save_enqueue_notifications() {
611 let mut cx = Cx::<Ev>::default();
612 cx.notify("toast", "show", "hi");
613 cx.save("blob");
614 assert_eq!(cx.notifications.len(), 2);
615 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
616 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
617 assert!(cx.requests.is_empty());
618 }
619
620 #[test]
621 fn cx_http_helpers_build_requests() {
622 let mut cx = Cx::<Ev>::default();
623 cx.get("http://h/x", |_| Ev::Tap);
624 cx.post("http://h/y", "hello", |_| Ev::Tap);
625 cx.patch("http://h/z", "patch", |_| Ev::Tap);
626 cx.delete("http://h/d", |_| Ev::Tap);
627
628 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
629 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
630 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
631
632 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
633 assert_eq!(get_input["url"], "http://h/x");
634 assert!(get_input["body"].is_null());
635
636 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
637 assert_eq!(post_input["url"], "http://h/y");
638 assert_eq!(post_input["body"], "hello");
639 }
640}