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    /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
229    Progress { value: Option<f32> },
230    /// Shimmer placeholder shown while content loads.
231    Skeleton,
232    Spacer { size: Spacing },
233    // Layout
234    Row { children: Vec<Widget> },
235    Column { children: Vec<Widget> },
236    /// Card; tappable when `on_press` is set.
237    Card { child: Box<Widget>, style: CardStyle, on_press: Option<ActionToken> },
238    /// Z-stack: children layered back-to-front, positioned by `align`. With
239    /// `scrim`, the first child is a background image, darkened for legibility,
240    /// and the rest render on top in light content.
241    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
242    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
243    Grid { children: Vec<Widget> },
244    /// Horizontally scrolling row of children (a carousel / chip rail).
245    Scroller { children: Vec<Widget> },
246    // Input
247    Button { label: String, style: ButtonStyle, on_press: ActionToken },
248    IconButton { icon: Icon, on_press: ActionToken },
249    Chip { label: String, selected: bool, on_press: ActionToken },
250    TextField { id: String, placeholder: String, value: String },
251    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
252    SearchField { id: String, placeholder: String, value: String },
253    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
254    Segmented { segments: Vec<Segment> },
255    Toggle { id: String, label: String, value: bool },
256    Checkbox { id: String, label: String, value: bool },
257    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
258    Slider { id: String, value: i32, max: i32 },
259    /// Numeric stepper with −/+ controls carrying their own events.
260    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
261    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
262    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
263    /// the whole app from it.
264    ///
265    /// `route` + `depth` drive navigation: the shell animates the body when
266    /// `route` (the current screen's identity) changes — slide for push/pop
267    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
268    /// move at the same depth — and wires the system back button to `back`.
269    Scaffold {
270        title: String,
271        body: Box<Widget>,
272        tabs: Vec<Tab>,
273        back: Option<ActionToken>,
274        dark_mode: bool,
275        /// App branding (brand color, corner, density, font). `None` = framework
276        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
277        theme: Option<Theme>,
278        /// Optional floating action button (raised primary action over the body).
279        fab: Option<Fab>,
280        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
281        sheet: Option<Sheet>,
282        route: String,
283        depth: u32,
284    },
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use serde::Serialize;
291    use serde::de::DeserializeOwned;
292
293    // Round-trips the ABI without requiring `PartialEq` on the wire types:
294    // serialize → deserialize → re-serialize, and compare the two encodings.
295    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
296        let a = serde_json::to_string(value).expect("serialize");
297        let back: T = serde_json::from_str(&a).expect("deserialize");
298        let b = serde_json::to_string(&back).expect("re-serialize");
299        assert_eq!(a, b);
300    }
301
302    #[test]
303    fn action_round_trips() {
304        round_trips(&Action::Start);
305        round_trips(&Action::Fired { token: "tok".to_string() });
306        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
307        round_trips(&Action::Restore { data: "{}".to_string() });
308    }
309
310    #[test]
311    fn widget_round_trips() {
312        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
313        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
314        // Un-themed scaffold (theme: None) — the default, must round-trip.
315        round_trips(&Widget::Scaffold {
316            title: "T".to_string(),
317            body: Box::new(Widget::Divider),
318            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
319            back: Some("b".to_string()),
320            dark_mode: true,
321            theme: None,
322            fab: None,
323            sheet: None,
324            route: "r".to_string(),
325            depth: 2,
326        });
327        // Themed scaffold — all four theme knobs must round-trip.
328        round_trips(&Widget::Scaffold {
329            title: "T".to_string(),
330            body: Box::new(Widget::Divider),
331            tabs: vec![],
332            back: None,
333            dark_mode: false,
334            theme: Some(Theme {
335                seed: Rgb::new(0xC8, 0x5A, 0x3C),
336                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
337                corner: Corner::Large,
338                density: Density::Compact,
339                font: FontFamily::Rounded,
340            }),
341            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string() }),
342            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
343            route: "r".to_string(),
344            depth: 1,
345        });
346    }
347}