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 http(
107 &mut self,
108 method: impl Into<String>,
109 url: impl Into<String>,
110 body: Option<String>,
111 then: impl FnOnce(PluginResponse) -> E + Send + 'static,
112 ) {
113 #[derive(Serialize)]
114 struct HttpReq {
115 url: String,
116 body: Option<String>,
117 }
118 let input = serde_json::to_string(&HttpReq { url: url.into(), body })
119 .expect("serialize http request");
120 self.plugin("http", method, input, then);
121 }
122
123 pub fn get(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
125 self.http("GET", url, None, then);
126 }
127 pub fn post(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
129 self.http("POST", url, Some(body.into()), then);
130 }
131 pub fn patch(&mut self, url: impl Into<String>, body: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
133 self.http("PATCH", url, Some(body.into()), then);
134 }
135 pub fn delete(&mut self, url: impl Into<String>, then: impl FnOnce(PluginResponse) -> E + Send + 'static) {
137 self.http("DELETE", url, None, then);
138 }
139}
140
141pub trait MobilerApp: Default {
146 type Event: Serialize + DeserializeOwned + Send + 'static;
147 type Model: Default;
148
149 fn update(&self, event: Self::Event, model: &mut Self::Model, cx: &mut Cx<Self::Event>);
150
151 fn input(&self, id: &str, value: InputValue, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
152 let _ = (id, value, model, cx);
153 }
154
155 fn restore(&self, data: &str, model: &mut Self::Model) {
158 let _ = (data, model);
159 }
160
161 fn init(&self, model: &mut Self::Model, cx: &mut Cx<Self::Event>) {
164 let _ = (model, cx);
165 }
166
167 fn view(&self, model: &Self::Model) -> Widget;
168}
169
170pub struct MobilerShell<A>(PhantomData<fn() -> A>);
172
173impl<A> Default for MobilerShell<A> {
174 fn default() -> Self {
175 Self(PhantomData)
176 }
177}
178
179impl<A: MobilerApp> App for MobilerShell<A> {
180 type Event = Action;
181 type Model = A::Model;
182 type ViewModel = Widget;
183 type Effect = Effect;
184
185 fn update(&self, action: Action, model: &mut Self::Model) -> Command<Effect, Action> {
186 let app = A::default();
187 let mut cx = Cx::<A::Event>::default();
188 match action {
189 Action::Fired { token } => {
190 if let Ok(event) = serde_json::from_str::<A::Event>(&token) {
191 app.update(event, model, &mut cx);
192 }
193 }
194 Action::Input { id, value } => app.input(&id, value, model, &mut cx),
195 Action::Restore { data } => app.restore(&data, model),
196 Action::Start => app.init(model, &mut cx),
197 }
198 let mut commands: Vec<Command<Effect, Action>> = Vec::new();
199 for op in cx.notifications {
200 commands.push(Command::notify_shell(op).build());
201 }
202 for (op, then) in cx.requests {
203 commands.push(Command::request_from_shell(op).then_send(move |response: PluginResponse| {
204 Action::Fired { token: serde_json::to_string(&then(response)).expect("serialize event") }
205 }));
206 }
207 commands.push(render());
208 Command::all(commands)
209 }
210
211 fn view(&self, model: &Self::Model) -> Widget {
212 A::default().view(model)
213 }
214}
215
216#[derive(Clone, Debug)]
235pub struct Nav<R> {
236 stack: Vec<R>,
237}
238
239impl<R: Clone + Serialize> Nav<R> {
240 #[must_use]
242 pub fn new(root: R) -> Self {
243 Self { stack: vec![root] }
244 }
245 pub fn push(&mut self, route: R) {
247 self.stack.push(route);
248 }
249 pub fn pop(&mut self) {
251 if self.stack.len() > 1 {
252 self.stack.pop();
253 }
254 }
255 pub fn reset(&mut self, root: R) {
257 self.stack = vec![root];
258 }
259 #[must_use]
261 pub fn current(&self) -> &R {
262 self.stack.last().expect("nav stack is never empty")
263 }
264 #[must_use]
266 pub fn depth(&self) -> u32 {
267 self.stack.len() as u32
268 }
269 #[must_use]
271 pub fn can_go_back(&self) -> bool {
272 self.stack.len() > 1
273 }
274 fn route_key(&self) -> String {
277 serde_json::to_string(self.current()).expect("serialize route")
278 }
279}
280
281fn tok<E: Serialize>(event: E) -> String {
285 serde_json::to_string(&event).expect("serialize event")
286}
287
288#[must_use]
289pub fn styled(content: impl Into<String>, style: TextStyle) -> Widget {
290 Widget::Text { content: content.into(), style }
291}
292#[must_use]
293pub fn text(content: impl Into<String>) -> Widget { styled(content, TextStyle::Body) }
294#[must_use]
295pub fn title(content: impl Into<String>) -> Widget { styled(content, TextStyle::Title) }
296#[must_use]
297pub fn subtitle(content: impl Into<String>) -> Widget { styled(content, TextStyle::Subtitle) }
298#[must_use]
299pub fn caption(content: impl Into<String>) -> Widget { styled(content, TextStyle::Caption) }
300#[must_use]
301pub fn emphasis(content: impl Into<String>) -> Widget { styled(content, TextStyle::Emphasis) }
302
303#[must_use]
304pub fn image(source: impl Into<String>, shape: ImageShape, ratio: ImageRatio) -> Widget {
305 Widget::Image { source: source.into(), shape, ratio }
306}
307#[must_use]
308pub fn badge(label: impl Into<String>, tone: Tone) -> Widget {
309 Widget::Badge { label: label.into(), tone }
310}
311#[must_use]
313pub fn color_dot(color: ProjectColor) -> Widget {
314 Widget::ColorDot { color }
315}
316#[must_use]
317pub fn divider() -> Widget { Widget::Divider }
318#[must_use]
319pub fn spacer(size: Spacing) -> Widget { Widget::Spacer { size } }
320
321#[must_use]
322pub fn row(children: Vec<Widget>) -> Widget { Widget::Row { children } }
323#[must_use]
324pub fn column(children: Vec<Widget>) -> Widget { Widget::Column { children } }
325#[must_use]
326pub fn card(child: Widget, style: CardStyle) -> Widget {
327 Widget::Card { child: Box::new(child), style, on_press: None }
328}
329#[must_use]
331pub fn card_button<E: Serialize>(child: Widget, style: CardStyle, on_press: E) -> Widget {
332 Widget::Card { child: Box::new(child), style, on_press: Some(tok(on_press)) }
333}
334#[must_use]
337pub fn stack(align: BoxAlign, scrim: bool, children: Vec<Widget>) -> Widget {
338 Widget::Box { children, align, scrim }
339}
340#[must_use]
341pub fn grid(children: Vec<Widget>) -> Widget { Widget::Grid { children } }
342
343#[must_use]
344pub fn button<E: Serialize>(label: impl Into<String>, style: ButtonStyle, on_press: E) -> Widget {
345 Widget::Button { label: label.into(), style, on_press: tok(on_press) }
346}
347#[must_use]
348pub fn icon_button<E: Serialize>(icon: Icon, on_press: E) -> Widget {
349 Widget::IconButton { icon, on_press: tok(on_press) }
350}
351#[must_use]
352pub fn chip<E: Serialize>(label: impl Into<String>, selected: bool, on_press: E) -> Widget {
353 Widget::Chip { label: label.into(), selected, on_press: tok(on_press) }
354}
355#[must_use]
356pub fn text_field(id: impl Into<String>, placeholder: impl Into<String>, value: impl Into<String>) -> Widget {
357 Widget::TextField { id: id.into(), placeholder: placeholder.into(), value: value.into() }
358}
359#[must_use]
360pub fn toggle(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
361 Widget::Toggle { id: id.into(), label: label.into(), value }
362}
363#[must_use]
364pub fn checkbox(id: impl Into<String>, label: impl Into<String>, value: bool) -> Widget {
365 Widget::Checkbox { id: id.into(), label: label.into(), value }
366}
367#[must_use]
368pub fn slider(id: impl Into<String>, value: i32, max: i32) -> Widget {
369 Widget::Slider { id: id.into(), value, max }
370}
371#[must_use]
372pub fn stepper<E: Serialize>(value: i32, on_decrement: E, on_increment: E) -> Widget {
373 Widget::Stepper { value, on_decrement: tok(on_decrement), on_increment: tok(on_increment) }
374}
375
376#[must_use]
378pub fn tab<E: Serialize>(label: impl Into<String>, selected: bool, on_select: E) -> Tab {
379 Tab { label: label.into(), selected, on_select: tok(on_select) }
380}
381
382#[must_use]
385pub fn scaffold(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget) -> Widget {
386 let title = title.into();
387 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: None, dark_mode, depth: 1 }
389}
390
391#[must_use]
395pub fn scaffold_back<E: Serialize>(title: impl Into<String>, dark_mode: bool, tabs: Vec<Tab>, body: Widget, back: E) -> Widget {
396 let title = title.into();
397 Widget::Scaffold { route: title.clone(), title, body: Box::new(body), tabs, back: Some(tok(back)), dark_mode, depth: 2 }
398}
399
400#[must_use]
405pub fn nav_scaffold<R, E>(
406 title: impl Into<String>,
407 dark_mode: bool,
408 tabs: Vec<Tab>,
409 body: Widget,
410 nav: &Nav<R>,
411 on_back: E,
412) -> Widget
413where
414 R: Clone + Serialize,
415 E: Serialize,
416{
417 Widget::Scaffold {
418 title: title.into(),
419 body: Box::new(body),
420 tabs,
421 back: if nav.can_go_back() { Some(tok(on_back)) } else { None },
422 dark_mode,
423 route: nav.route_key(),
424 depth: nav.depth(),
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 use serde::Serialize;
432
433 #[derive(Clone, Copy, Serialize, PartialEq, Debug)]
434 enum Route {
435 Home,
436 Detail(u32),
437 }
438
439 #[derive(Serialize)]
440 enum Ev {
441 Tap,
442 Open(u32),
443 }
444
445 #[test]
448 fn nav_push_pop_depth() {
449 let mut nav = Nav::new(Route::Home);
450 assert_eq!(nav.depth(), 1);
451 assert!(!nav.can_go_back());
452
453 nav.push(Route::Detail(7));
454 assert_eq!(nav.depth(), 2);
455 assert!(nav.can_go_back());
456 assert!(matches!(nav.current(), Route::Detail(7)));
457
458 nav.pop();
459 assert_eq!(nav.depth(), 1);
460 assert!(matches!(nav.current(), Route::Home));
461
462 nav.pop(); assert_eq!(nav.depth(), 1);
464 }
465
466 #[test]
467 fn nav_reset_replaces_stack() {
468 let mut nav = Nav::new(Route::Home);
469 nav.push(Route::Detail(1));
470 nav.push(Route::Detail(2));
471 nav.reset(Route::Detail(9));
472 assert_eq!(nav.depth(), 1);
473 assert!(matches!(nav.current(), Route::Detail(9)));
474 }
475
476 #[test]
477 fn nav_route_key_is_serialization() {
478 let nav = Nav::new(Route::Detail(3));
479 assert_eq!(nav.route_key(), serde_json::to_string(&Route::Detail(3)).unwrap());
480 }
481
482 #[test]
485 fn scaffold_sets_route_depth_and_no_back() {
486 match scaffold("Home", false, vec![], text("x")) {
487 Widget::Scaffold { route, depth, back, dark_mode, .. } => {
488 assert_eq!(route, "Home");
489 assert_eq!(depth, 1);
490 assert!(back.is_none());
491 assert!(!dark_mode);
492 }
493 other => panic!("expected Scaffold, got {other:?}"),
494 }
495 }
496
497 #[test]
498 fn scaffold_back_is_depth_2_with_back() {
499 match scaffold_back("Detail", true, vec![], text("x"), Ev::Tap) {
500 Widget::Scaffold { depth, back, dark_mode, .. } => {
501 assert_eq!(depth, 2);
502 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
503 assert!(dark_mode);
504 }
505 other => panic!("expected Scaffold, got {other:?}"),
506 }
507 }
508
509 #[test]
510 fn nav_scaffold_shows_back_only_when_poppable() {
511 let mut nav = Nav::new(Route::Home);
512 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
514 Widget::Scaffold { back, depth, route, .. } => {
515 assert!(back.is_none());
516 assert_eq!(depth, 1);
517 assert_eq!(route, serde_json::to_string(&Route::Home).unwrap());
518 }
519 other => panic!("expected Scaffold, got {other:?}"),
520 }
521 nav.push(Route::Detail(2));
523 match nav_scaffold("T", false, vec![], text("x"), &nav, Ev::Tap) {
524 Widget::Scaffold { back, depth, .. } => {
525 assert_eq!(back, Some(serde_json::to_string(&Ev::Tap).unwrap()));
526 assert_eq!(depth, 2);
527 }
528 other => panic!("expected Scaffold, got {other:?}"),
529 }
530 }
531
532 #[test]
533 fn buttons_carry_serialized_event_tokens() {
534 match button("Go", ButtonStyle::Filled, Ev::Open(5)) {
535 Widget::Button { label, on_press, .. } => {
536 assert_eq!(label, "Go");
537 assert_eq!(on_press, serde_json::to_string(&Ev::Open(5)).unwrap());
538 }
539 other => panic!("expected Button, got {other:?}"),
540 }
541 match card_button(text("c"), CardStyle::Elevated, Ev::Tap) {
542 Widget::Card { on_press, .. } => {
543 assert_eq!(on_press, Some(serde_json::to_string(&Ev::Tap).unwrap()));
544 }
545 other => panic!("expected Card, got {other:?}"),
546 }
547 match card(text("c"), CardStyle::Elevated) {
549 Widget::Card { on_press, .. } => assert!(on_press.is_none()),
550 other => panic!("expected Card, got {other:?}"),
551 }
552 }
553
554 #[test]
557 fn cx_notify_and_save_enqueue_notifications() {
558 let mut cx = Cx::<Ev>::default();
559 cx.notify("toast", "show", "hi");
560 cx.save("blob");
561 assert_eq!(cx.notifications.len(), 2);
562 assert_eq!(cx.notifications[0], PluginNotify { plugin: "toast".into(), op: "show".into(), input: "hi".into() });
563 assert_eq!(cx.notifications[1], PluginNotify { plugin: "storage".into(), op: "save".into(), input: "blob".into() });
564 assert!(cx.requests.is_empty());
565 }
566
567 #[test]
568 fn cx_http_helpers_build_requests() {
569 let mut cx = Cx::<Ev>::default();
570 cx.get("http://h/x", |_| Ev::Tap);
571 cx.post("http://h/y", "hello", |_| Ev::Tap);
572 cx.patch("http://h/z", "patch", |_| Ev::Tap);
573 cx.delete("http://h/d", |_| Ev::Tap);
574
575 let methods: Vec<&str> = cx.requests.iter().map(|(c, _)| c.op.as_str()).collect();
576 assert_eq!(methods, ["GET", "POST", "PATCH", "DELETE"]);
577 assert!(cx.requests.iter().all(|(c, _)| c.plugin == "http"));
578
579 let get_input: serde_json::Value = serde_json::from_str(&cx.requests[0].0.input).unwrap();
580 assert_eq!(get_input["url"], "http://h/x");
581 assert!(get_input["body"].is_null());
582
583 let post_input: serde_json::Value = serde_json::from_str(&cx.requests[1].0.input).unwrap();
584 assert_eq!(post_input["url"], "http://h/y");
585 assert_eq!(post_input["body"], "hello");
586 }
587}