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/// What a [`Widget::TextField`] accepts — selects the on-screen keyboard,
62/// secure (masked) entry, and single- vs multi-line layout in one axis.
63///
64/// `Text` is the plain default. `Secure` masks input (passwords). `Email`,
65/// `Number` (integer), `Decimal`, `Phone`, and `Url` pick the matching native
66/// keyboard / input mode without masking. `Multiline` is a growable multi-row
67/// text area (plain keyboard).
68#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
69#[repr(C)]
70pub enum FieldKind { Text, Secure, Email, Number, Decimal, Phone, Url, Multiline }
71
72/// Semantic status color (distinct from brand/identity color).
73#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
74#[repr(C)]
75pub enum Tone { Neutral, Success, Warning, Danger, Info }
76
77/// How a `Chart` draws its series.
78///
79/// **Cartesian** styles plot every series over the shared `labels` x-axis:
80/// `Bar`/`Line` (grouped bars / one polyline per series), `StackedBar` (series stack to a total
81/// per x-slot), `StackedBar100` (each x-slot fills to 100% — series as proportions).
82///
83/// **Circular** styles ignore the x-axis and the `axis` flag: `Pie`/`Donut` turn **each series**
84/// into one wedge sized by its magnitude (`Donut` leaves a center hole); `Rings` draws concentric
85/// progress arcs (Apple-Watch fitness style), one per series, swept by `sum(values) / goal`;
86/// `Gauge` draws a single arc for the first series' `value / goal` with the number in the center.
87#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
88#[repr(C)]
89pub enum ChartStyle { Bar, Line, StackedBar, StackedBar100, Pie, Donut, Rings, Gauge }
90
91/// One named data series in a [`Widget::Chart`]. Cartesian styles plot `values` across the chart's
92/// x-axis `labels`; circular styles (pie/donut/rings/gauge) collapse the series to a single
93/// magnitude (`values` summed). `color` overrides the auto-assigned palette slot; `goal` is the
94/// denominator for `Rings`/`Gauge` progress (ignored by the other styles).
95#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
96#[repr(C)]
97pub struct ChartSeries {
98    pub name: String,
99    pub values: Vec<f32>,
100    pub color: Option<Rgb>,
101    pub goal: Option<f32>,
102}
103
104impl ChartSeries {
105    /// A named series carrying `values`. Color falls back to the chart palette; no goal.
106    #[must_use]
107    pub fn new(name: impl Into<String>, values: Vec<f32>) -> Self {
108        Self { name: name.into(), values, color: None, goal: None }
109    }
110    /// Override the auto-assigned palette color for this series.
111    #[must_use]
112    pub fn with_color(mut self, color: Rgb) -> Self {
113        self.color = Some(color);
114        self
115    }
116    /// Set the denominator for `Rings`/`Gauge` progress (`sum(values) / goal`). Ignored by
117    /// cartesian and pie/donut styles.
118    #[must_use]
119    pub fn with_goal(mut self, goal: f32) -> Self {
120        self.goal = Some(goal);
121        self
122    }
123}
124
125// ----------------------------- region chart -----------------------------
126//
127// A [`Widget::RegionChart`] is a variable-width stacked-region ("Marimekko" / coverage-gap)
128// chart: arbitrary colored rectangles placed in a 2-D `[0, x_max] × [0, y_max]` plane, each with
129// an in-cell label, plus horizontal reference lines, an irregular x-axis, an optional right-side
130// bracket annotation, and a legend. The app computes the geometry; the shells map domain→pixels.
131
132/// One rectangle in a [`Widget::RegionChart`], spanning `[x0, x1]` horizontally and `[y0, y1]`
133/// vertically in the chart's domain. `label` is centered inside (empty = none); `vertical` rotates
134/// it 90° for narrow columns. `color` overrides the auto-assigned palette slot.
135#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
136#[repr(C)]
137pub struct ChartRegion {
138    pub x0: f32,
139    pub x1: f32,
140    pub y0: f32,
141    pub y1: f32,
142    pub color: Option<Rgb>,
143    pub label: String,
144    pub vertical: bool,
145}
146
147/// A horizontal reference line across a [`Widget::RegionChart`] at `value`, with a right-edge
148/// `label` chip. `dashed` draws it dashed (e.g. a "max insured" ceiling) vs solid (a target).
149#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
150#[repr(C)]
151pub struct ChartRefLine {
152    pub value: f32,
153    pub label: String,
154    pub dashed: bool,
155}
156
157/// A right-side bracket annotation spanning `[y0, y1]` with a `label` note (e.g. a ceiling band).
158#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
159#[repr(C)]
160pub struct ChartBracket {
161    pub y0: f32,
162    pub y1: f32,
163    pub label: String,
164    /// Show an ⓘ info marker above the label (e.g. a "Ceiling max …" note). `label` may contain
165    /// `\n` for multiple lines.
166    pub info: bool,
167}
168
169/// An x-axis tick on a [`Widget::RegionChart`] at domain position `at`, labelled `label`. Ticks
170/// are irregular (the app places them), so shells position them by fraction, not even spacing.
171#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
172#[repr(C)]
173pub struct ChartTick {
174    pub at: f32,
175    pub label: String,
176}
177
178/// One legend entry (swatch + name) for a [`Widget::RegionChart`].
179#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
180#[repr(C)]
181pub struct ChartLegendItem {
182    pub label: String,
183    pub color: Rgb,
184}
185
186impl ChartRegion {
187    /// A region spanning `[x0,x1] × [y0,y1]` with a centered `label` (palette color, horizontal).
188    #[must_use]
189    pub fn new(x0: f32, x1: f32, y0: f32, y1: f32, label: impl Into<String>) -> Self {
190        Self { x0, x1, y0, y1, color: None, label: label.into(), vertical: false }
191    }
192    /// Override the fill color.
193    #[must_use]
194    pub fn with_color(mut self, color: Rgb) -> Self {
195        self.color = Some(color);
196        self
197    }
198    /// Render the label rotated 90° (for tall, narrow regions).
199    #[must_use]
200    pub fn vertical(mut self) -> Self {
201        self.vertical = true;
202        self
203    }
204}
205
206impl ChartRefLine {
207    /// A solid target line at `value` with a right-edge chip.
208    #[must_use]
209    pub fn target(value: f32, label: impl Into<String>) -> Self {
210        Self { value, label: label.into(), dashed: false }
211    }
212    /// A dashed "max"/ceiling line at `value`.
213    #[must_use]
214    pub fn max(value: f32, label: impl Into<String>) -> Self {
215        Self { value, label: label.into(), dashed: true }
216    }
217}
218
219impl ChartTick {
220    #[must_use]
221    pub fn new(at: f32, label: impl Into<String>) -> Self {
222        Self { at, label: label.into() }
223    }
224}
225
226impl ChartLegendItem {
227    #[must_use]
228    pub fn new(label: impl Into<String>, color: Rgb) -> Self {
229        Self { label: label.into(), color }
230    }
231}
232
233impl ChartBracket {
234    #[must_use]
235    pub fn new(y0: f32, y1: f32, label: impl Into<String>) -> Self {
236        Self { y0, y1, label: label.into(), info: false }
237    }
238    /// Show an ⓘ info marker above the label.
239    #[must_use]
240    pub fn with_info(mut self) -> Self {
241        self.info = true;
242        self
243    }
244}
245
246#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
247#[repr(C)]
248pub enum Spacing { Xs, Sm, Md, Lg, Xl }
249
250/// A finite icon set (maps to Material icons / SF Symbols / web glyphs per shell).
251/// Grouped: editing, navigation/chrome, content, and domain icons.
252#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
253#[repr(C)]
254pub enum Icon {
255    // editing / status
256    Delete, Add, Edit, Close, Settings, Check, Star, Info,
257    // navigation / chrome
258    Home, Search, Menu, Filter, Back, Forward, Down, Bell, Cart, Share, Heart, HeartFilled,
259    // people / contact
260    Person, People, Phone, Mail, Calendar, Clock, MapPin,
261    // content / media
262    Camera, Photo, Play,
263    // domain
264    Scissors,
265}
266
267#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
268#[repr(C)]
269pub enum ImageShape { Square, Rounded, Circle }
270
271#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
272#[repr(C)]
273pub enum ImageRatio { Wide, Square, Tall }
274
275#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
276#[repr(C)]
277pub enum BoxAlign { TopStart, TopEnd, Center, BottomStart, BottomCenter, BottomEnd }
278
279/// Project-identity colors (distinct from semantic `Tone`). Concrete RGB decided
280/// in the render layer.
281#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
282#[repr(C)]
283pub enum ProjectColor { Indigo, Teal, Coral, Amber, Lime, Pink }
284
285// ------------------------------- theme -------------------------------
286
287/// A 24-bit RGB color. Used for a theme's brand/seed color — the one place an app
288/// supplies an arbitrary color (everything else is intent tokens).
289#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
290#[repr(C)]
291pub struct Rgb {
292    pub r: u8,
293    pub g: u8,
294    pub b: u8,
295}
296
297impl Rgb {
298    pub const fn new(r: u8, g: u8, b: u8) -> Self {
299        Self { r, g, b }
300    }
301}
302
303/// Global corner-radius scale. `Medium` ≈ the current (un-themed) look.
304#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
305#[repr(C)]
306pub enum Corner { None, Small, Medium, Large }
307
308/// Global spacing scale. `Comfortable` ≈ the current (un-themed) spacing.
309#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
310#[repr(C)]
311pub enum Density { Compact, Comfortable }
312
313/// A finite, cross-platform font family (maps to each platform's nearest system
314/// font design — no bundled font files). `System` ≈ the current look.
315#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
316#[repr(C)]
317pub enum FontFamily { System, Rounded, Serif, Monospace }
318
319/// App branding as data — the visual twin of `dark_mode`. Set on a [`Widget::Scaffold`]
320/// (`theme: None` = the framework defaults, i.e. no visual change). The shell maps these
321/// to its native theming: `seed` → the brand/primary color (Android M3 scheme / iOS tint /
322/// web `--primary`), plus a global corner, spacing, and font choice.
323#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
324#[repr(C)]
325pub struct Theme {
326    pub seed: Rgb,
327    /// Optional secondary brand color. `None` ⇒ derived from `seed`. Used for the
328    /// gradient on `CardStyle::Brand` (seed → accent) and as a secondary accent.
329    pub accent: Option<Rgb>,
330    pub corner: Corner,
331    pub density: Density,
332    pub font: FontFamily,
333}
334
335/// `Theme::default()` matches the framework's un-themed look as closely as a theme can
336/// (medium corners, comfortable spacing, system font) with a neutral indigo seed — so an
337/// app can override just the bits it cares about: `Theme { seed: brand, ..Default::default() }`.
338impl Default for Theme {
339    fn default() -> Self {
340        Theme {
341            seed: Rgb::new(0x5C, 0x6B, 0xC0), // indigo — matches the legacy default accent
342            accent: None,
343            corner: Corner::Medium,
344            density: Density::Comfortable,
345            font: FontFamily::System,
346        }
347    }
348}
349
350/// A bottom-navigation tab. `selected` marks the active one; tapping sends
351/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
352#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
353#[repr(C)]
354pub struct Tab {
355    pub label: String,
356    pub selected: bool,
357    pub on_select: ActionToken,
358    /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
359    pub icon: Option<Icon>,
360}
361
362/// A floating action button anchored over the scaffold body (the raised primary action).
363#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
364#[repr(C)]
365pub struct Fab {
366    pub icon: Icon,
367    pub on_press: ActionToken,
368}
369
370/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
371/// active segment; tapping sends `on_select`.
372#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
373#[repr(C)]
374pub struct Segment {
375    pub label: String,
376    pub selected: bool,
377    pub on_select: ActionToken,
378}
379
380/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
381/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
382#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
383#[repr(C)]
384pub struct Sheet {
385    pub title: String,
386    pub child: Box<Widget>,
387    pub on_dismiss: ActionToken,
388}
389
390/// One revealed action in a `SwipeAction` row (swipe to reveal, tap to fire).
391#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
392#[repr(C)]
393pub struct SwipeButton {
394    pub label: String,
395    pub tone: Tone,
396    pub on_tap: ActionToken,
397}
398
399/// One subtitle/caption track for a [`Widget::Video`]. `url` points at a WebVTT (`.vtt`) file,
400/// `language` is a BCP-47 tag (e.g. `"en"`), `label` is the human-readable menu entry, and
401/// `default_on` selects it by default. Sidecar tracks work on web (`<track>`) and Android
402/// (Media3 subtitle configuration); on iOS only captions already embedded in an HLS manifest are
403/// selectable (AVPlayer can't attach a sidecar VTT to an MP4 — a documented v1 gap).
404#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
405#[repr(C)]
406pub struct Caption {
407    pub url: String,
408    pub label: String,
409    pub language: String,
410    pub default_on: bool,
411}
412
413// ------------------------------- widgets -------------------------------
414
415/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
416#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
417#[repr(C)]
418pub enum Widget {
419    // Content
420    Text { content: String, style: TextStyle },
421    Image { source: String, shape: ImageShape, ratio: ImageRatio },
422    Badge { label: String, tone: Tone },
423    /// A circular avatar image with an optional colored status dot.
424    Avatar { source: String, status: Option<Tone> },
425    /// An in-app PDF viewer showing the document at `url` (a remote https URL or a local
426    /// file URI). Each shell uses its native renderer — PDFKit on iOS, a paged `PdfRenderer`
427    /// on Android, an `<iframe>` on web — so the app only supplies the URL (e.g. a
428    /// backend-generated report). Fills its width; give it room (place in a sized container).
429    PdfView { url: String },
430    /// An in-app native video player for the stream/file at `url` (MP4 everywhere; HLS `.m3u8` on
431    /// iOS/Android natively + Safari on web; or a local file URI). Native player per shell — AVPlayer
432    /// (iOS), Media3/ExoPlayer (Android), a `<video>` element (web). **Controllable:** `playing` drives
433    /// play/pause (app-owned, like a `Toggle`); set `seek_to_ms` to jump (the shell seeks when the value
434    /// CHANGES; `-1` = no seek). The shell reports the current position ~once/second via
435    /// `Action::Input { id, value: Int(position_ms) }` (handle it in [`MobilerApp::input`]), and fires
436    /// `on_ended` when the clip finishes. `controls` shows the native transport bar; `looping` restarts
437    /// on end; `muted` starts muted (needed for reliable autoplay). Fills its width; give it room.
438    ///
439    /// v2 fields: `poster` shows a thumbnail image before the first play; `start_at_ms` resumes at an
440    /// offset (applied once on load, `-1` = start). `captions` adds subtitle tracks (see [`Caption`]).
441    /// `rate` sets playback speed (`1.0` = normal) and `volume` the level (`0.0`–`1.0`). For a playlist,
442    /// set `urls` (non-empty takes precedence over `url`) with `start_index`; the shell auto-advances
443    /// and reports the current track ~as it changes via `Action::Input { id: "{id}.index", … }`, and
444    /// `seek_index` jumps to a track when it CHANGES (`-1` = none). The shell also reports
445    /// `"{id}.duration"`, `"{id}.state"` (0 idle / 1 buffering / 2 ready-paused / 3 playing / 4 ended)
446    /// and `"{id}.buffered"` via the same `Input` path (handle them in [`MobilerApp::input`]). Set
447    /// `allow_pip` to enable Picture-in-Picture (the shell adds a PiP affordance).
448    Video {
449        url: String,
450        id: String,
451        playing: bool,
452        seek_to_ms: i64,
453        controls: bool,
454        looping: bool,
455        muted: bool,
456        on_ended: Option<ActionToken>,
457        poster: Option<String>,
458        start_at_ms: i64,
459        captions: Vec<Caption>,
460        rate: f32,
461        volume: f32,
462        urls: Vec<String>,
463        start_index: i64,
464        seek_index: i64,
465        allow_pip: bool,
466    },
467    /// Displays the web page / embedded player at `url` in a native web view — `WKWebView` on iOS,
468    /// `android.webkit.WebView` on Android, an `<iframe>` on web. General-purpose: docs, dashboards,
469    /// or a hosted player embed (e.g. a Bunny.net / YouTube embed URL, which brings its own
470    /// captions/quality/thumbnails). JavaScript and inline media autoplay are enabled so hosted
471    /// players work. This is NOT the default way to play video — use [`Widget::Video`] for a
472    /// controllable native player. Fills its width; give it room (place in a sized container).
473    WebView { url: String },
474    /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
475    /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
476    Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
477    /// Small non-interactive colored dot — a project/identity hint.
478    ColorDot { color: ProjectColor },
479    Divider,
480    /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
481    Progress { value: Option<f32> },
482    /// Shimmer placeholder shown while content loads.
483    Skeleton,
484    /// A data chart drawing one or more named `series` in the given `style` (see [`ChartStyle`]).
485    /// `labels` (optional) annotate the x-axis for cartesian styles. `axis` shows y gridlines +
486    /// tick values (cartesian only); `legend` shows a series swatch+name row. Non-interactive.
487    Chart { series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool },
488    /// A variable-width stacked-region ("Marimekko" / coverage-gap) chart: `regions` are arbitrary
489    /// colored rectangles in the `[0, x_max] × [0, y_max]` plane (each with an in-cell label),
490    /// `ticks` annotate the irregular x-axis, `ref_lines` are horizontal target/max lines with
491    /// right-edge chips, `bracket` is an optional right-side range annotation, and `legend` names
492    /// the colors. The app supplies all geometry; shells map domain→pixels. Non-interactive.
493    RegionChart {
494        regions: Vec<ChartRegion>,
495        ticks: Vec<ChartTick>,
496        x_max: f32,
497        y_max: f32,
498        ref_lines: Vec<ChartRefLine>,
499        bracket: Option<ChartBracket>,
500        legend: Vec<ChartLegendItem>,
501    },
502    /// An inline month calendar. `first_weekday` is the weekday of day 1 (0=Sun..6=Sat) so the
503    /// shells render leading blanks without date math; `on_day[d-1]` fires when day `d` is tapped
504    /// (length = days in the month). `selected` highlights a day.
505    Calendar { year: u32, month: u8, first_weekday: u8, selected: Option<u8>, on_day: Vec<ActionToken> },
506    /// A list row that reveals trailing `actions` on horizontal swipe (each tappable). On web the
507    /// actions render inline as a trailing button row (no gesture).
508    SwipeAction { child: Box<Widget>, actions: Vec<SwipeButton> },
509    /// A scrollable list for long/paged feeds, with shell-detected events at both ends: the bottom
510    /// `on_load_more` fires when the user scrolls near the end (infinite scroll), the top
511    /// `on_refresh` fires on pull-to-refresh. `loading`/`refreshing`/`has_more` are app-owned: set
512    /// `loading` while a page loads (shell shows a spinner, stops firing), `has_more=false` when
513    /// exhausted, and `refreshing` while a pull-refresh runs. The app appends to `children` on each
514    /// load-more. `on_refresh` is set via [`with_refresh`](mobiler_core::with_refresh).
515    LazyList {
516        children: Vec<Widget>,
517        on_load_more: Option<ActionToken>,
518        loading: bool,
519        has_more: bool,
520        on_refresh: Option<ActionToken>,
521        refreshing: bool,
522    },
523    Spacer { size: Spacing },
524    // Layout
525    Row { children: Vec<Widget> },
526    Column { children: Vec<Widget> },
527    /// Card; tappable when `on_press` is set.
528    Card { child: Box<Widget>, style: CardStyle, on_press: Option<ActionToken> },
529    /// Z-stack: children layered back-to-front, positioned by `align`. With
530    /// `scrim`, the first child is a background image, darkened for legibility,
531    /// and the rest render on top in light content.
532    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
533    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
534    Grid { children: Vec<Widget> },
535    /// Horizontally scrolling row of children (a carousel / chip rail).
536    Scroller { children: Vec<Widget> },
537    /// Two-pane master-detail. On a **wide** screen (tablet / landscape — the shell's regular size
538    /// class) `primary` and `detail` render side-by-side; on a **compact** screen (phone) it shows
539    /// ONE pane: `primary` until `show_detail` is set (the app sets it when a row is selected), then
540    /// `detail` with a back chevron that fires `on_back` (the app clears its selection). On wide,
541    /// `show_detail`/`on_back` are ignored — both panes stay visible, so `detail` should show a
542    /// placeholder until something is selected.
543    Split { primary: Box<Widget>, detail: Box<Widget>, show_detail: bool, on_back: Option<ActionToken> },
544    // Input
545    Button { label: String, style: ButtonStyle, on_press: ActionToken },
546    IconButton { icon: Icon, on_press: ActionToken },
547    Chip { label: String, selected: bool, on_press: ActionToken },
548    /// A text input. `kind` selects keyboard / secure entry / multiline
549    /// (see [`FieldKind`]); `error`, when `Some`, shows an inline validation
550    /// message below the field and marks it invalid. Emits `Input { id, Text }`.
551    TextField { id: String, placeholder: String, value: String, kind: FieldKind, error: Option<String> },
552    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
553    SearchField { id: String, placeholder: String, value: String },
554    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
555    Segmented { segments: Vec<Segment> },
556    Toggle { id: String, label: String, value: bool },
557    Checkbox { id: String, label: String, value: bool },
558    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
559    Slider { id: String, value: i32, max: i32 },
560    /// Numeric stepper with −/+ controls carrying their own events.
561    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
562    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
563    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
564    /// the whole app from it.
565    ///
566    /// `route` + `depth` drive navigation: the shell animates the body when
567    /// `route` (the current screen's identity) changes — slide for push/pop
568    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
569    /// move at the same depth — and wires the system back button to `back`.
570    Scaffold {
571        title: String,
572        body: Box<Widget>,
573        tabs: Vec<Tab>,
574        back: Option<ActionToken>,
575        dark_mode: bool,
576        /// App branding (brand color, corner, density, font). `None` = framework
577        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
578        theme: Option<Theme>,
579        /// Optional floating action button (raised primary action over the body).
580        fab: Option<Fab>,
581        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
582        sheet: Option<Sheet>,
583        /// Pull-to-refresh: when set, the body is pull-refreshable and fires this event on pull.
584        /// The app owns `refreshing` — set it true when the pull fires, clear it when the async
585        /// reload completes (the shell shows a spinner while it's true).
586        on_refresh: Option<ActionToken>,
587        refreshing: bool,
588        route: String,
589        depth: u32,
590    },
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use serde::Serialize;
597    use serde::de::DeserializeOwned;
598
599    // Round-trips the ABI without requiring `PartialEq` on the wire types:
600    // serialize → deserialize → re-serialize, and compare the two encodings.
601    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
602        let a = serde_json::to_string(value).expect("serialize");
603        let back: T = serde_json::from_str(&a).expect("deserialize");
604        let b = serde_json::to_string(&back).expect("re-serialize");
605        assert_eq!(a, b);
606    }
607
608    #[test]
609    fn action_round_trips() {
610        round_trips(&Action::Start);
611        round_trips(&Action::Fired { token: "tok".to_string() });
612        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
613        round_trips(&Action::Restore { data: "{}".to_string() });
614    }
615
616    #[test]
617    fn widget_round_trips() {
618        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
619        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
620        round_trips(&Widget::Chart {
621            series: vec![ChartSeries { name: "s".to_string(), values: vec![1.0, 2.5, 3.0], color: None, goal: None }],
622            labels: vec!["a".to_string()],
623            style: ChartStyle::Bar,
624            axis: true,
625            legend: false,
626        });
627        round_trips(&Widget::RegionChart {
628            regions: vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical(),
629                          ChartRegion::new(3.0, 21.0, 0.0, 80.0, "CHF 80'000").with_color(Rgb::new(0x8E, 0xC6, 0xBA))],
630            ticks: vec![ChartTick { at: 3.0, label: "3 Mt.".to_string() }, ChartTick { at: 65.0, label: "65 J.".to_string() }],
631            x_max: 65.0,
632            y_max: 80.0,
633            ref_lines: vec![ChartRefLine { value: 80.0, label: "CHF 80'000".to_string(), dashed: false }],
634            bracket: Some(ChartBracket { y0: 60.0, y1: 80.0, label: "Ceiling".to_string(), info: true }),
635            legend: vec![ChartLegendItem { label: "Gap".to_string(), color: Rgb::new(0x5A, 0x7D, 0x9A) }],
636        });
637        round_trips(&Widget::PdfView { url: "https://example.com/report.pdf".to_string() });
638        round_trips(&Widget::Video { url: "https://example.com/clip.mp4".to_string(), id: "v1".to_string(), playing: true, seek_to_ms: -1, controls: true, looping: false, muted: true, on_ended: Some("ended".to_string()), poster: Some("https://example.com/poster.jpg".to_string()), start_at_ms: 12000, captions: vec![Caption { url: "https://example.com/en.vtt".to_string(), label: "English".to_string(), language: "en".to_string(), default_on: true }], rate: 1.5, volume: 0.8, urls: vec![], start_index: 0, seek_index: -1, allow_pip: true });
639        round_trips(&Widget::Video { url: "https://example.com/live.m3u8".to_string(), id: "v2".to_string(), playing: false, seek_to_ms: 5000, controls: false, looping: true, muted: false, on_ended: None, poster: None, start_at_ms: -1, captions: vec![], rate: 1.0, volume: 1.0, urls: vec!["https://example.com/a.mp4".to_string(), "https://example.com/b.mp4".to_string()], start_index: 1, seek_index: 0, allow_pip: false });
640        round_trips(&Widget::WebView { url: "https://iframe.mediadelivery.net/embed/1/abc".to_string() });
641        round_trips(&Widget::TextField { id: "email".to_string(), placeholder: "you@co".to_string(), value: "".to_string(), kind: FieldKind::Email, error: None });
642        round_trips(&Widget::TextField { id: "pw".to_string(), placeholder: "Password".to_string(), value: "x".to_string(), kind: FieldKind::Secure, error: Some("Too short".to_string()) });
643        round_trips(&Widget::Calendar { year: 2026, month: 6, first_weekday: 1, selected: Some(15), on_day: vec!["d1".to_string(), "d2".to_string()] });
644        round_trips(&Widget::SwipeAction { child: Box::new(Widget::Divider), actions: vec![SwipeButton { label: "Del".to_string(), tone: Tone::Danger, on_tap: "t".to_string() }] });
645        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: true, on_back: Some("back".to_string()) });
646        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: false, on_back: None });
647        round_trips(&Widget::LazyList { children: vec![Widget::Divider], on_load_more: Some("more".to_string()), loading: false, has_more: true, on_refresh: Some("refresh".to_string()), refreshing: false });
648        // Un-themed scaffold (theme: None) — the default, must round-trip.
649        round_trips(&Widget::Scaffold {
650            title: "T".to_string(),
651            body: Box::new(Widget::Divider),
652            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
653            back: Some("b".to_string()),
654            dark_mode: true,
655            theme: None,
656            fab: None,
657            sheet: None,
658            on_refresh: None,
659            refreshing: false,
660            route: "r".to_string(),
661            depth: 2,
662        });
663        // Themed scaffold — all four theme knobs must round-trip.
664        round_trips(&Widget::Scaffold {
665            title: "T".to_string(),
666            body: Box::new(Widget::Divider),
667            tabs: vec![],
668            back: None,
669            dark_mode: false,
670            theme: Some(Theme {
671                seed: Rgb::new(0xC8, 0x5A, 0x3C),
672                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
673                corner: Corner::Large,
674                density: Density::Compact,
675                font: FontFamily::Rounded,
676            }),
677            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string() }),
678            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
679            on_refresh: Some("r".to_string()),
680            refreshing: true,
681            route: "r".to_string(),
682            depth: 1,
683        });
684    }
685}