Skip to main content

mobiler_ui/
lib.rs

1//! Mobiler's fixed UI wire ABI.
2//!
3//! These types are the **stable contract** between any Mobiler app's Rust core
4//! and the native shell. Because they never change per app, a single shell is
5//! built once and renders *any* Mobiler app — the shell only ever knows these
6//! types, never an app's domain events or widgets.
7//!
8//! - The core emits a [`Widget`] tree (the `ViewModel`).
9//! - The shell sends back an [`Action`] (the `Event`).
10//! - App domain events ride inside actions as opaque [`ActionToken`]s that the
11//!   shell round-trips without interpreting.
12//!
13//! Style is expressed as **intent tokens** (e.g. [`TextStyle`], [`Tone`]); the
14//! shell maps each to a concrete look (font, color, dp), so dark mode and theme
15//! come for free on the native side.
16
17use facet::Facet;
18use serde::{Deserialize, Serialize};
19
20/// An opaque, serialized app event (e.g. JSON of the app's domain action).
21pub type ActionToken = String;
22
23/// A value produced by an input widget at runtime.
24#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
25#[repr(C)]
26pub enum InputValue {
27    Text(String),
28    Bool(bool),
29    Int(i64),
30}
31
32/// What the shell sends back to the core. **Fixed across all apps.**
33#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
34#[repr(C)]
35pub enum Action {
36    /// An action widget (button/etc.) fired; `token` is the opaque app event.
37    Fired { token: ActionToken },
38    /// A value-carrying input changed; `id` names the widget.
39    Input { id: String, value: InputValue },
40    /// Persisted state handed back to the core on startup (empty string if none).
41    Restore { data: String },
42    /// Fired once on startup (after `Restore`) so the app can kick off initial
43    /// effects (e.g. fetching data).
44    Start,
45}
46
47// ---------------------------- style tokens ----------------------------
48
49#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
50#[repr(C)]
51pub enum TextStyle { Body, Title, Subtitle, Caption, Emphasis }
52
53#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
54#[repr(C)]
55pub enum ButtonStyle { Filled, Outlined, Text }
56
57#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
58#[repr(C)]
59pub enum CardStyle { Elevated, Outlined, Filled, Brand }
60
61/// Semantic status color (distinct from brand/identity color).
62#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
63#[repr(C)]
64pub enum Tone { Neutral, Success, Warning, Danger, Info }
65
66#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
67#[repr(C)]
68pub enum Spacing { Xs, Sm, Md, Lg, Xl }
69
70/// A finite icon set (maps to Material icons / SF Symbols / web glyphs per shell).
71/// Grouped: editing, navigation/chrome, content, and domain icons.
72#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
73#[repr(C)]
74pub enum Icon {
75    // editing / status
76    Delete, Add, Edit, Close, Settings, Check, Star, Info,
77    // navigation / chrome
78    Home, Search, Menu, Filter, Back, Forward, Down, Bell, Cart, Share, Heart, HeartFilled,
79    // people / contact
80    Person, People, Phone, Mail, Calendar, Clock, MapPin,
81    // content / media
82    Camera, Photo, Play,
83    // domain
84    Scissors,
85}
86
87#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
88#[repr(C)]
89pub enum ImageShape { Square, Rounded, Circle }
90
91#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
92#[repr(C)]
93pub enum ImageRatio { Wide, Square, Tall }
94
95#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
96#[repr(C)]
97pub enum BoxAlign { TopStart, TopEnd, Center, BottomStart, BottomCenter, BottomEnd }
98
99/// Project-identity colors (distinct from semantic `Tone`). Concrete RGB decided
100/// in the render layer.
101#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
102#[repr(C)]
103pub enum ProjectColor { Indigo, Teal, Coral, Amber, Lime, Pink }
104
105// ------------------------------- theme -------------------------------
106
107/// A 24-bit RGB color. Used for a theme's brand/seed color — the one place an app
108/// supplies an arbitrary color (everything else is intent tokens).
109#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
110#[repr(C)]
111pub struct Rgb {
112    pub r: u8,
113    pub g: u8,
114    pub b: u8,
115}
116
117impl Rgb {
118    pub const fn new(r: u8, g: u8, b: u8) -> Self {
119        Self { r, g, b }
120    }
121}
122
123/// Global corner-radius scale. `Medium` ≈ the current (un-themed) look.
124#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
125#[repr(C)]
126pub enum Corner { None, Small, Medium, Large }
127
128/// Global spacing scale. `Comfortable` ≈ the current (un-themed) spacing.
129#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
130#[repr(C)]
131pub enum Density { Compact, Comfortable }
132
133/// A finite, cross-platform font family (maps to each platform's nearest system
134/// font design — no bundled font files). `System` ≈ the current look.
135#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
136#[repr(C)]
137pub enum FontFamily { System, Rounded, Serif, Monospace }
138
139/// App branding as data — the visual twin of `dark_mode`. Set on a [`Widget::Scaffold`]
140/// (`theme: None` = the framework defaults, i.e. no visual change). The shell maps these
141/// to its native theming: `seed` → the brand/primary color (Android M3 scheme / iOS tint /
142/// web `--primary`), plus a global corner, spacing, and font choice.
143#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
144#[repr(C)]
145pub struct Theme {
146    pub seed: Rgb,
147    /// Optional secondary brand color. `None` ⇒ derived from `seed`. Used for the
148    /// gradient on `CardStyle::Brand` (seed → accent) and as a secondary accent.
149    pub accent: Option<Rgb>,
150    pub corner: Corner,
151    pub density: Density,
152    pub font: FontFamily,
153}
154
155/// `Theme::default()` matches the framework's un-themed look as closely as a theme can
156/// (medium corners, comfortable spacing, system font) with a neutral indigo seed — so an
157/// app can override just the bits it cares about: `Theme { seed: brand, ..Default::default() }`.
158impl Default for Theme {
159    fn default() -> Self {
160        Theme {
161            seed: Rgb::new(0x5C, 0x6B, 0xC0), // indigo — matches the legacy default accent
162            accent: None,
163            corner: Corner::Medium,
164            density: Density::Comfortable,
165            font: FontFamily::System,
166        }
167    }
168}
169
170/// A bottom-navigation tab. `selected` marks the active one; tapping sends
171/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
172#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
173#[repr(C)]
174pub struct Tab {
175    pub label: String,
176    pub selected: bool,
177    pub on_select: ActionToken,
178    /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
179    pub icon: Option<Icon>,
180}
181
182/// A floating action button anchored over the scaffold body (the raised primary action).
183#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
184#[repr(C)]
185pub struct Fab {
186    pub icon: Icon,
187    pub on_press: ActionToken,
188}
189
190/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
191/// active segment; tapping sends `on_select`.
192#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
193#[repr(C)]
194pub struct Segment {
195    pub label: String,
196    pub selected: bool,
197    pub on_select: ActionToken,
198}
199
200/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
201/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
202#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
203#[repr(C)]
204pub struct Sheet {
205    pub title: String,
206    pub child: Box<Widget>,
207    pub on_dismiss: ActionToken,
208}
209
210// ------------------------------- widgets -------------------------------
211
212/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
213#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
214#[repr(C)]
215pub enum Widget {
216    // Content
217    Text { content: String, style: TextStyle },
218    Image { source: String, shape: ImageShape, ratio: ImageRatio },
219    Badge { label: String, tone: Tone },
220    /// A circular avatar image with an optional colored status dot.
221    Avatar { source: String, status: Option<Tone> },
222    /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
223    /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
224    Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
225    /// Small non-interactive colored dot — a project/identity hint.
226    ColorDot { color: ProjectColor },
227    Divider,
228    Spacer { size: Spacing },
229    // Layout
230    Row { children: Vec<Widget> },
231    Column { children: Vec<Widget> },
232    /// Card; tappable when `on_press` is set.
233    Card { child: Box<Widget>, style: CardStyle, on_press: Option<ActionToken> },
234    /// Z-stack: children layered back-to-front, positioned by `align`. With
235    /// `scrim`, the first child is a background image, darkened for legibility,
236    /// and the rest render on top in light content.
237    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
238    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
239    Grid { children: Vec<Widget> },
240    /// Horizontally scrolling row of children (a carousel / chip rail).
241    Scroller { children: Vec<Widget> },
242    // Input
243    Button { label: String, style: ButtonStyle, on_press: ActionToken },
244    IconButton { icon: Icon, on_press: ActionToken },
245    Chip { label: String, selected: bool, on_press: ActionToken },
246    TextField { id: String, placeholder: String, value: String },
247    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
248    SearchField { id: String, placeholder: String, value: String },
249    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
250    Segmented { segments: Vec<Segment> },
251    Toggle { id: String, label: String, value: bool },
252    Checkbox { id: String, label: String, value: bool },
253    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
254    Slider { id: String, value: i32, max: i32 },
255    /// Numeric stepper with −/+ controls carrying their own events.
256    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
257    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
258    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
259    /// the whole app from it.
260    ///
261    /// `route` + `depth` drive navigation: the shell animates the body when
262    /// `route` (the current screen's identity) changes — slide for push/pop
263    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
264    /// move at the same depth — and wires the system back button to `back`.
265    Scaffold {
266        title: String,
267        body: Box<Widget>,
268        tabs: Vec<Tab>,
269        back: Option<ActionToken>,
270        dark_mode: bool,
271        /// App branding (brand color, corner, density, font). `None` = framework
272        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
273        theme: Option<Theme>,
274        /// Optional floating action button (raised primary action over the body).
275        fab: Option<Fab>,
276        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
277        sheet: Option<Sheet>,
278        route: String,
279        depth: u32,
280    },
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use serde::Serialize;
287    use serde::de::DeserializeOwned;
288
289    // Round-trips the ABI without requiring `PartialEq` on the wire types:
290    // serialize → deserialize → re-serialize, and compare the two encodings.
291    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
292        let a = serde_json::to_string(value).expect("serialize");
293        let back: T = serde_json::from_str(&a).expect("deserialize");
294        let b = serde_json::to_string(&back).expect("re-serialize");
295        assert_eq!(a, b);
296    }
297
298    #[test]
299    fn action_round_trips() {
300        round_trips(&Action::Start);
301        round_trips(&Action::Fired { token: "tok".to_string() });
302        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
303        round_trips(&Action::Restore { data: "{}".to_string() });
304    }
305
306    #[test]
307    fn widget_round_trips() {
308        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
309        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
310        // Un-themed scaffold (theme: None) — the default, must round-trip.
311        round_trips(&Widget::Scaffold {
312            title: "T".to_string(),
313            body: Box::new(Widget::Divider),
314            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
315            back: Some("b".to_string()),
316            dark_mode: true,
317            theme: None,
318            fab: None,
319            sheet: None,
320            route: "r".to_string(),
321            depth: 2,
322        });
323        // Themed scaffold — all four theme knobs must round-trip.
324        round_trips(&Widget::Scaffold {
325            title: "T".to_string(),
326            body: Box::new(Widget::Divider),
327            tabs: vec![],
328            back: None,
329            dark_mode: false,
330            theme: Some(Theme {
331                seed: Rgb::new(0xC8, 0x5A, 0x3C),
332                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
333                corner: Corner::Large,
334                density: Density::Compact,
335                font: FontFamily::Rounded,
336            }),
337            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string() }),
338            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
339            route: "r".to_string(),
340            depth: 1,
341        });
342    }
343}