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    /// The app's own version, sent once by the shell at startup **before** `Restore`/`Start`:
46    /// iOS `CFBundleShortVersionString`/`CFBundleVersion`/bundle id, Android
47    /// `versionName`/`longVersionCode`/package name, web empty strings. `platform` is
48    /// `"ios"`/`"android"`/`"web"`. Read in the core via `cx.app_info()`.
49    AppInfo { version: String, build: String, platform: String, bundle_id: String },
50}
51
52// ---------------------------- style tokens ----------------------------
53
54#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
55#[repr(C)]
56pub enum TextStyle { Body, Title, Subtitle, Caption, Emphasis, Display, Headline }
57
58/// Button emphasis. `Tonal` is the quieter filled secondary (M3 filled-tonal).
59#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
60#[repr(C)]
61pub enum ButtonStyle { Filled, Outlined, Text, Tonal }
62
63#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
64#[repr(C)]
65/// `Dashed`: no fill and a dashed outline ("empty, you can fill this"). BREAKING (Moj Termin design
66/// release): appended, so exhaustive matches need the case.
67pub enum CardStyle { Elevated, Outlined, Filled, Brand, Dashed }
68
69/// Accessibility role for [`Widget::A11y`] — the control type announced to a screen reader. Maps
70/// best-effort per platform: iOS accessibility traits, Android semantics role / `heading()`, web ARIA role.
71#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
72#[repr(C)]
73pub enum A11yRole { Button, Link, Image, Header, Adjustable }
74
75/// What a [`Widget::TextField`] accepts — selects the on-screen keyboard,
76/// secure (masked) entry, and single- vs multi-line layout in one axis.
77///
78/// `Text` is the plain default. `Secure` masks input (passwords). `Email`,
79/// `Number` (integer), `Decimal`, `Phone`, and `Url` pick the matching native
80/// keyboard / input mode without masking. `Multiline` is a growable multi-row
81/// text area (plain keyboard).
82#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
83#[repr(C)]
84pub enum FieldKind { Text, Secure, Email, Number, Decimal, Phone, Url, Multiline }
85
86/// Semantic status color (distinct from brand/identity color).
87#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
88#[repr(C)]
89pub enum Tone { Neutral, Success, Warning, Danger, Info }
90
91/// How a `Chart` draws its series.
92///
93/// **Cartesian** styles plot every series over the shared `labels` x-axis:
94/// `Bar`/`Line` (grouped bars / one polyline per series), `StackedBar` (series stack to a total
95/// per x-slot), `StackedBar100` (each x-slot fills to 100% — series as proportions).
96///
97/// **Circular** styles ignore the x-axis and the `axis` flag: `Pie`/`Donut` turn **each series**
98/// into one wedge sized by its magnitude (`Donut` leaves a center hole); `Rings` draws concentric
99/// progress arcs (Apple-Watch fitness style), one per series, swept by `sum(values) / goal`;
100/// `Gauge` draws a single arc for the first series' `value / goal` with the number in the center.
101#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
102#[repr(C)]
103pub enum ChartStyle { Bar, Line, StackedBar, StackedBar100, Pie, Donut, Rings, Gauge }
104
105/// One named data series in a [`Widget::Chart`]. Cartesian styles plot `values` across the chart's
106/// x-axis `labels`; circular styles (pie/donut/rings/gauge) collapse the series to a single
107/// magnitude (`values` summed). `color` overrides the auto-assigned palette slot; `goal` is the
108/// denominator for `Rings`/`Gauge` progress (ignored by the other styles).
109#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
110#[repr(C)]
111pub struct ChartSeries {
112    pub name: String,
113    pub values: Vec<f32>,
114    pub color: Option<Rgb>,
115    pub goal: Option<f32>,
116}
117
118impl ChartSeries {
119    /// A named series carrying `values`. Color falls back to the chart palette; no goal.
120    #[must_use]
121    pub fn new(name: impl Into<String>, values: Vec<f32>) -> Self {
122        Self { name: name.into(), values, color: None, goal: None }
123    }
124    /// Override the auto-assigned palette color for this series.
125    #[must_use]
126    pub fn with_color(mut self, color: Rgb) -> Self {
127        self.color = Some(color);
128        self
129    }
130    /// Set the denominator for `Rings`/`Gauge` progress (`sum(values) / goal`). Ignored by
131    /// cartesian and pie/donut styles.
132    #[must_use]
133    pub fn with_goal(mut self, goal: f32) -> Self {
134        self.goal = Some(goal);
135        self
136    }
137}
138
139// ----------------------------- region chart -----------------------------
140//
141// A [`Widget::RegionChart`] is a variable-width stacked-region ("Marimekko" / coverage-gap)
142// chart: arbitrary colored rectangles placed in a 2-D `[0, x_max] × [0, y_max]` plane, each with
143// an in-cell label, plus horizontal reference lines, an irregular x-axis, an optional right-side
144// bracket annotation, and a legend. The app computes the geometry; the shells map domain→pixels.
145
146/// One rectangle in a [`Widget::RegionChart`], spanning `[x0, x1]` horizontally and `[y0, y1]`
147/// vertically in the chart's domain. `label` is centered inside (empty = none); `vertical` rotates
148/// it 90° for narrow columns. `color` overrides the auto-assigned palette slot.
149#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
150#[repr(C)]
151pub struct ChartRegion {
152    pub x0: f32,
153    pub x1: f32,
154    pub y0: f32,
155    pub y1: f32,
156    pub color: Option<Rgb>,
157    pub label: String,
158    pub vertical: bool,
159}
160
161/// A horizontal reference line across a [`Widget::RegionChart`] at `value`, with a right-edge
162/// `label` chip. `dashed` draws it dashed (e.g. a "max insured" ceiling) vs solid (a target).
163#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
164#[repr(C)]
165pub struct ChartRefLine {
166    pub value: f32,
167    pub label: String,
168    pub dashed: bool,
169}
170
171/// A right-side bracket annotation spanning `[y0, y1]` with a `label` note (e.g. a ceiling band).
172#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
173#[repr(C)]
174pub struct ChartBracket {
175    pub y0: f32,
176    pub y1: f32,
177    pub label: String,
178    /// Show an ⓘ info marker above the label (e.g. a "Ceiling max …" note). `label` may contain
179    /// `\n` for multiple lines.
180    pub info: bool,
181}
182
183/// An x-axis tick on a [`Widget::RegionChart`] at domain position `at`, labelled `label`. Ticks
184/// are irregular (the app places them), so shells position them by fraction, not even spacing.
185#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
186#[repr(C)]
187pub struct ChartTick {
188    pub at: f32,
189    pub label: String,
190}
191
192/// One legend entry (swatch + name) for a [`Widget::RegionChart`].
193#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
194#[repr(C)]
195pub struct ChartLegendItem {
196    pub label: String,
197    pub color: Rgb,
198}
199
200impl ChartRegion {
201    /// A region spanning `[x0,x1] × [y0,y1]` with a centered `label` (palette color, horizontal).
202    #[must_use]
203    pub fn new(x0: f32, x1: f32, y0: f32, y1: f32, label: impl Into<String>) -> Self {
204        Self { x0, x1, y0, y1, color: None, label: label.into(), vertical: false }
205    }
206    /// Override the fill color.
207    #[must_use]
208    pub fn with_color(mut self, color: Rgb) -> Self {
209        self.color = Some(color);
210        self
211    }
212    /// Render the label rotated 90° (for tall, narrow regions).
213    #[must_use]
214    pub fn vertical(mut self) -> Self {
215        self.vertical = true;
216        self
217    }
218}
219
220impl ChartRefLine {
221    /// A solid target line at `value` with a right-edge chip.
222    #[must_use]
223    pub fn target(value: f32, label: impl Into<String>) -> Self {
224        Self { value, label: label.into(), dashed: false }
225    }
226    /// A dashed "max"/ceiling line at `value`.
227    #[must_use]
228    pub fn max(value: f32, label: impl Into<String>) -> Self {
229        Self { value, label: label.into(), dashed: true }
230    }
231}
232
233impl ChartTick {
234    #[must_use]
235    pub fn new(at: f32, label: impl Into<String>) -> Self {
236        Self { at, label: label.into() }
237    }
238}
239
240impl ChartLegendItem {
241    #[must_use]
242    pub fn new(label: impl Into<String>, color: Rgb) -> Self {
243        Self { label: label.into(), color }
244    }
245}
246
247impl ChartBracket {
248    #[must_use]
249    pub fn new(y0: f32, y1: f32, label: impl Into<String>) -> Self {
250        Self { y0, y1, label: label.into(), info: false }
251    }
252    /// Show an ⓘ info marker above the label.
253    #[must_use]
254    pub fn with_info(mut self) -> Self {
255        self.info = true;
256        self
257    }
258}
259
260#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
261#[repr(C)]
262pub enum Spacing { Xs, Sm, Md, Lg, Xl }
263
264/// A finite icon set (maps to Material icons / SF Symbols / web glyphs per shell).
265/// Grouped: editing, navigation/chrome, content, and domain icons.
266#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
267#[repr(C)]
268pub enum Icon {
269    // editing / status
270    Delete, Add, Edit, Close, Settings, Check, Star, Info,
271    // navigation / chrome
272    Home, Search, Menu, Filter, Back, Forward, Down, Bell, Cart, Share, Heart, HeartFilled,
273    // people / contact
274    Person, People, Phone, Mail, Calendar, Clock, MapPin,
275    // content / media
276    Camera, Photo, Play,
277    // domain
278    Scissors,
279    // status: a double check ("finished")
280    DoneAll,
281}
282
283#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
284#[repr(C)]
285pub enum ImageShape { Square, Rounded, Circle }
286
287#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
288#[repr(C)]
289pub enum ImageRatio { Wide, Square, Tall }
290
291#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
292#[repr(C)]
293pub enum BoxAlign { TopStart, TopEnd, Center, BottomStart, BottomCenter, BottomEnd }
294
295/// Project-identity colors (distinct from semantic `Tone`). Concrete RGB decided
296/// in the render layer.
297#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
298#[repr(C)]
299pub enum ProjectColor { Indigo, Teal, Coral, Amber, Lime, Pink }
300
301// ------------------------------- theme -------------------------------
302
303/// A 24-bit RGB color. Used for a theme's brand/seed color — the one place an app
304/// supplies an arbitrary color (everything else is intent tokens).
305#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
306#[repr(C)]
307pub struct Rgb {
308    pub r: u8,
309    pub g: u8,
310    pub b: u8,
311}
312
313impl Rgb {
314    pub const fn new(r: u8, g: u8, b: u8) -> Self {
315        Self { r, g, b }
316    }
317
318    /// `Rgb::hex(0x231f20)` — a colour from a 24-bit hex literal, as design tokens are written.
319    #[must_use]
320    pub const fn hex(v: u32) -> Self {
321        Self { r: ((v >> 16) & 0xff) as u8, g: ((v >> 8) & 0xff) as u8, b: (v & 0xff) as u8 }
322    }
323}
324
325/// Global corner-radius scale. `Medium` ≈ the current (un-themed) look.
326#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
327#[repr(C)]
328pub enum Corner { None, Small, Medium, Large }
329
330/// Global density. `Comfortable` ≈ the current (un-themed) look; `Compact` tightens spacing.
331/// `Large` is for hurried / wet / gloved hands: bigger controls (56 buttons & segmented, 48 chips
332/// & calendar days, 56 icon-button targets), 16 control labels, ≥ 12 between adjacent tappables.
333/// Body text stays on the platform's font-scale setting.
334#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
335#[repr(C)]
336pub enum Density { Compact, Comfortable, Large }
337
338/// A cross-platform font family. `System`/`Rounded`/`Serif`/`Monospace` map to each platform's
339/// nearest system font design. `Custom` = the app's `mobiler.toml` `[fonts]`, synced into the shells
340/// by the CLI (`mobiler fonts sync`, also run by build/dev): the display family for titles and
341/// subtitles, the body family for the rest; a role without files falls back to the system font.
342/// `System` ≈ the current look.
343#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
344#[repr(C)]
345pub enum FontFamily { System, Rounded, Serif, Monospace, Custom }
346
347/// App branding as data — the visual twin of `dark_mode`. Set on a [`Widget::Scaffold`]
348/// (`theme: None` = the framework defaults, i.e. no visual change). The shell maps these
349/// to its native theming: `seed` → the brand/primary color (Android M3 scheme / iOS tint /
350/// web `--primary`), plus a global corner, spacing, and font choice.
351///
352/// **Breaking in mobiler-ui 0.29 / mobiler-core 0.40:** `Theme` gained `palette` (and further
353/// design-release fields follow). Code that lists every field in a `Theme { … }` literal no longer
354/// compiles. Write `Theme { seed, ..Default::default() }` and set only what you need.
355#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
356#[repr(C)]
357pub struct Theme {
358    pub seed: Rgb,
359    /// Optional secondary brand color. `None` ⇒ derived from `seed`. Used for the
360    /// gradient on `CardStyle::Brand` (seed → accent) and as a secondary accent.
361    pub accent: Option<Rgb>,
362    pub corner: Corner,
363    pub density: Density,
364    pub font: FontFamily,
365    /// Explicit colour roles for light and dark (`dark_mode` picks the set). `None` = the shell's
366    /// own colours, exactly as before; a role left `None` inside a set keeps the shell's colour too.
367    pub palette: Option<Palette>,
368    /// Per-style size, weight and font role (see [`TypeScale`]). `None`, or a style left `None`, keeps
369    /// the shell's current look for that style.
370    pub type_scale: Option<TypeScale>,
371    /// Per-component corner radii (see [`Shapes`]). `None`, or a component left `None`, keeps the
372    /// shell's current shape for it.
373    pub shapes: Option<Shapes>,
374}
375
376/// `Theme::default()` matches the framework's un-themed look as closely as a theme can
377/// (medium corners, comfortable spacing, system font) with a neutral indigo seed — so an
378/// app can override just the bits it cares about: `Theme { seed: brand, ..Default::default() }`.
379impl Default for Theme {
380    fn default() -> Self {
381        Theme {
382            seed: Rgb::new(0x5C, 0x6B, 0xC0), // indigo — matches the legacy default accent
383            accent: None,
384            corner: Corner::Medium,
385            density: Density::Comfortable,
386            font: FontFamily::System,
387            palette: None,
388            type_scale: None,
389            shapes: None,
390        }
391    }
392}
393
394/// A corner radius per component. `sheet_top` rounds only the bottom sheet's top corners (`Pill` there
395/// is capped at 32 — a dome would clip the sheet's content). `button` also shapes the confirm dialog's
396/// buttons where the shell draws them (web, Android); iOS uses the system alert.
397#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
398#[repr(C)]
399pub struct Shapes {
400    /// Every card style, including tappable cards.
401    pub card: Option<Radius>,
402    /// Every button style, including toned and `Density::Large` buttons.
403    pub button: Option<Radius>,
404    pub fab: Option<Radius>,
405    pub sheet_top: Option<Radius>,
406    pub chip: Option<Radius>,
407    pub badge: Option<Radius>,
408    /// Text and search fields.
409    pub input: Option<Radius>,
410}
411
412/// A corner radius: `Dp(n)` (dp/pt/px), or `Pill` — fully round (half the component's height), at
413/// any density.
414#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
415#[repr(C)]
416pub enum Radius {
417    Dp(u8),
418    Pill,
419}
420
421/// The app's type scale: one optional [`TypeSpec`] per text style. `title` also sets the scaffold's
422/// top-bar title and `headline` the sheet titles. Sizes are sp/pt/px and still follow the platform's
423/// text-size accessibility setting.
424#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
425#[repr(C)]
426pub struct TypeScale {
427    pub display: Option<TypeSpec>,
428    pub headline: Option<TypeSpec>,
429    pub title: Option<TypeSpec>,
430    pub subtitle: Option<TypeSpec>,
431    pub body: Option<TypeSpec>,
432    pub emphasis: Option<TypeSpec>,
433    pub caption: Option<TypeSpec>,
434}
435
436/// One style's size (sp/pt/px), weight (100..=900, rounded to the nearest 100) and font role.
437#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
438#[repr(C)]
439pub struct TypeSpec {
440    pub size: u8,
441    pub weight: u16,
442    pub family: FamilyRole,
443}
444
445impl TypeSpec {
446    #[must_use]
447    pub const fn new(size: u8, weight: u16, family: FamilyRole) -> Self {
448        Self { size, weight, family }
449    }
450}
451
452/// Which synced font a [`TypeSpec`] uses under `FontFamily::Custom` (otherwise the theme's system font).
453#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
454#[repr(C)]
455pub enum FamilyRole { Display, Body }
456
457/// A light and a dark set of colour roles — the design's tokens. See [`ColorRoles`].
458#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
459#[repr(C)]
460pub struct Palette {
461    pub light: ColorRoles,
462    pub dark: ColorRoles,
463}
464
465/// Colour roles; every one optional (`None` = the shell's current colour for that role).
466#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
467#[repr(C)]
468pub struct ColorRoles {
469    /// Page background.
470    pub background: Option<Rgb>,
471    /// Cards, sheets, dialogs.
472    pub surface: Option<Rgb>,
473    /// Top bar, bottom navigation, navigation rail.
474    pub surface_bar: Option<Rgb>,
475    /// Chips, input fills, segmented track, Filled cards, skeletons, the Neutral tone.
476    pub surface_muted: Option<Rgb>,
477    /// Text and icons.
478    pub on_surface: Option<Rgb>,
479    /// Secondary text (captions, unselected tabs).
480    pub on_surface_variant: Option<Rgb>,
481    /// Field and outlined-button borders.
482    pub outline: Option<Rgb>,
483    /// Hairlines and dividers.
484    pub outline_variant: Option<Rgb>,
485    /// Filled buttons, selected calendar day, toggles.
486    pub primary: Option<Rgb>,
487    pub on_primary: Option<Rgb>,
488    /// Primary-coloured text/icons on the background (text buttons, selected tab, back button).
489    pub primary_text: Option<Rgb>,
490    /// Tonal buttons, selected segment/chip, navigation indicator.
491    pub secondary_container: Option<Rgb>,
492    pub on_secondary_container: Option<Rgb>,
493    pub fab: Option<Rgb>,
494    pub on_fab: Option<Rgb>,
495    /// One container/on-container pair per [`Tone`]. Filled toned buttons swap the pair.
496    pub success: Option<TonePair>,
497    pub warning: Option<TonePair>,
498    pub danger: Option<TonePair>,
499    pub info: Option<TonePair>,
500    /// Sheet and dialog scrim.
501    pub scrim: Option<Rgba>,
502}
503
504/// A tone's soft background and its foreground.
505#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
506#[repr(C)]
507pub struct TonePair {
508    pub container: Rgb,
509    pub on_container: Rgb,
510}
511
512impl TonePair {
513    #[must_use]
514    pub const fn new(container: Rgb, on_container: Rgb) -> Self {
515        Self { container, on_container }
516    }
517}
518
519/// A colour with alpha (`a`: 0 = transparent, 255 = opaque).
520#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
521#[repr(C)]
522pub struct Rgba {
523    pub r: u8,
524    pub g: u8,
525    pub b: u8,
526    pub a: u8,
527}
528
529impl Rgba {
530    #[must_use]
531    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
532        Self { r, g, b, a }
533    }
534}
535
536/// How the scaffold picks light or dark. `Light`/`Dark` force it; `System` follows the OS live (the
537/// shell switches palette sets itself, no core round-trip). Set with `with_appearance`.
538#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
539#[repr(C)]
540pub enum Appearance { Light, Dark, System }
541
542/// Text the shells draw themselves (back buttons, web list controls, dialog/picker defaults), in the
543/// app's language. Set once on the scaffold with `with_labels`; every field is optional and falls
544/// back to the shell's built-in English. A label passed to a specific call (`confirm_with`,
545/// `Picker`) still wins over these.
546#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
547#[repr(C)]
548pub struct ShellLabels {
549    /// `Split` back-button text on every shell; the Scaffold back button's accessible name.
550    pub back: Option<String>,
551    /// Web `LazyList` "Load more" button.
552    pub load_more: Option<String>,
553    /// Web `LazyList` refresh button (shown after a ↻) and the web scaffold refresh button's name.
554    pub refresh: Option<String>,
555    /// Confirm dialog: the confirming button when the call gives no label.
556    pub ok: Option<String>,
557    /// Confirm dialog and pickers: the dismissing button when the call gives no label.
558    pub cancel: Option<String>,
559    /// Pickers: the accepting button when the call gives no label.
560    pub done: Option<String>,
561    /// Android PdfView error text.
562    pub pdf_error: Option<String>,
563    /// Web PDF iframe title (accessibility).
564    pub pdf_title: Option<String>,
565    /// Web WebView iframe title (accessibility).
566    pub web_title: Option<String>,
567    /// The step indicator's spoken text ([`Widget::Steps`]), with `{current}` / `{total}`
568    /// placeholders: `"Korak {current} od {total}"`. Default `"Step {current} of {total}"`.
569    pub step_of: Option<String>,
570}
571
572impl ShellLabels {
573    #[must_use]
574    pub fn new() -> Self {
575        Self::default()
576    }
577    #[must_use]
578    pub fn back(mut self, l: impl Into<String>) -> Self {
579        self.back = Some(l.into());
580        self
581    }
582    #[must_use]
583    pub fn load_more(mut self, l: impl Into<String>) -> Self {
584        self.load_more = Some(l.into());
585        self
586    }
587    #[must_use]
588    pub fn refresh(mut self, l: impl Into<String>) -> Self {
589        self.refresh = Some(l.into());
590        self
591    }
592    #[must_use]
593    pub fn ok(mut self, l: impl Into<String>) -> Self {
594        self.ok = Some(l.into());
595        self
596    }
597    #[must_use]
598    pub fn cancel(mut self, l: impl Into<String>) -> Self {
599        self.cancel = Some(l.into());
600        self
601    }
602    #[must_use]
603    pub fn done(mut self, l: impl Into<String>) -> Self {
604        self.done = Some(l.into());
605        self
606    }
607    #[must_use]
608    pub fn pdf_error(mut self, l: impl Into<String>) -> Self {
609        self.pdf_error = Some(l.into());
610        self
611    }
612    #[must_use]
613    pub fn pdf_title(mut self, l: impl Into<String>) -> Self {
614        self.pdf_title = Some(l.into());
615        self
616    }
617    #[must_use]
618    pub fn web_title(mut self, l: impl Into<String>) -> Self {
619        self.web_title = Some(l.into());
620        self
621    }
622    #[must_use]
623    pub fn step_of(mut self, l: impl Into<String>) -> Self {
624        self.step_of = Some(l.into());
625        self
626    }
627}
628
629/// A bottom-navigation tab. `selected` marks the active one; tapping sends
630/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
631#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
632#[repr(C)]
633pub struct Tab {
634    pub label: String,
635    pub selected: bool,
636    pub on_select: ActionToken,
637    /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
638    pub icon: Option<Icon>,
639}
640
641/// A floating action button anchored over the scaffold body (the raised primary action).
642#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
643#[repr(C)]
644pub struct Fab {
645    pub icon: Icon,
646    pub on_press: ActionToken,
647    /// Extended FAB: the label shown next to the icon, which is also its accessible name. `None` = the
648    /// round FAB. BREAKING (Moj Termin design release): `Fab { .. }` literals need this field; the
649    /// `with_fab` / `with_extended_fab` builders are unaffected.
650    pub label: Option<String>,
651}
652
653/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
654/// active segment; tapping sends `on_select`.
655#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
656#[repr(C)]
657pub struct Segment {
658    pub label: String,
659    pub selected: bool,
660    pub on_select: ActionToken,
661}
662
663/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
664/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
665#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
666#[repr(C)]
667pub struct Sheet {
668    pub title: String,
669    pub child: Box<Widget>,
670    pub on_dismiss: ActionToken,
671}
672
673/// One revealed action in a `SwipeAction` row (swipe to reveal, tap to fire).
674#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
675#[repr(C)]
676pub struct SwipeButton {
677    pub label: String,
678    pub tone: Tone,
679    pub on_tap: ActionToken,
680}
681
682/// One subtitle/caption track for a [`Widget::Video`]. `url` points at a WebVTT (`.vtt`) file,
683/// `language` is a BCP-47 tag (e.g. `"en"`), `label` is the human-readable menu entry, and
684/// `default_on` selects it by default. Sidecar tracks work on web (`<track>`) and Android
685/// (Media3 subtitle configuration); on iOS only captions already embedded in an HLS manifest are
686/// selectable (AVPlayer can't attach a sidecar VTT to an MP4 — a documented v1 gap).
687#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
688#[repr(C)]
689pub struct Caption {
690    pub url: String,
691    pub label: String,
692    pub language: String,
693    pub default_on: bool,
694}
695
696/// A pin on a [`Widget::Map`]. `id` is echoed back when the marker is tapped
697/// (`Action::Input { id: "{map_id}.marker", value: Text(marker.id) }`).
698#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
699#[repr(C)]
700pub struct MapMarker {
701    pub id: String,
702    pub lat: f64,
703    pub lng: f64,
704    pub title: Option<String>,
705}
706
707// ------------------------------- widgets -------------------------------
708
709/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
710// `Scaffold`'s `ShellLabels` (nine `Option<String>` fields) makes it the largest variant by a wide
711// margin; boxing it would ripple through every `with_labels`/scaffold call site for no runtime
712// benefit on a wire type that is rebuilt per-render, not stored in bulk.
713#[allow(clippy::large_enum_variant)]
714#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
715#[repr(C)]
716pub enum Widget {
717    // Content
718    Text { content: String, style: TextStyle },
719    Image { source: String, shape: ImageShape, ratio: ImageRatio },
720    /// A status pill. `icon` (before the label, decorative) makes the status readable without its
721    /// colour. BREAKING (Moj Termin design release): `icon` was added — exhaustive patterns and full
722    /// literals need it; `badge` / `with_icon` are unaffected.
723    Badge { label: String, tone: Tone, icon: Option<Icon> },
724    /// A circular avatar image with an optional colored status dot. `initials` (at most two
725    /// characters) are drawn when `source` is empty or fails to load; `size` is the diameter
726    /// (`None` = 48). BREAKING (Moj Termin design release): `initials` and `size` were added.
727    Avatar { source: String, status: Option<Tone>, initials: Option<String>, size: Option<u8> },
728    /// An in-app PDF viewer showing the document at `url` (a remote https URL or a local
729    /// file URI). Each shell uses its native renderer — PDFKit on iOS, a paged `PdfRenderer`
730    /// on Android, an `<iframe>` on web — so the app only supplies the URL (e.g. a
731    /// backend-generated report). Fills its width; give it room (place in a sized container).
732    PdfView { url: String },
733    /// An in-app native video player for the stream/file at `url` (MP4 everywhere; HLS `.m3u8` on
734    /// iOS/Android natively + Safari on web; or a local file URI). Native player per shell — AVPlayer
735    /// (iOS), Media3/ExoPlayer (Android), a `<video>` element (web). **Controllable:** `playing` drives
736    /// play/pause (app-owned, like a `Toggle`); set `seek_to_ms` to jump (the shell seeks when the value
737    /// CHANGES; `-1` = no seek). The shell reports the current position ~once/second via
738    /// `Action::Input { id, value: Int(position_ms) }` (handle it in [`MobilerApp::input`]), and fires
739    /// `on_ended` when the clip finishes. `controls` shows the native transport bar; `looping` restarts
740    /// on end; `muted` starts muted (needed for reliable autoplay). Fills its width; give it room.
741    ///
742    /// v2 fields: `poster` shows a thumbnail image before the first play; `start_at_ms` resumes at an
743    /// offset (applied once on load, `-1` = start). `captions` adds subtitle tracks (see [`Caption`]).
744    /// `rate` sets playback speed (`1.0` = normal) and `volume` the level (`0.0`–`1.0`). For a playlist,
745    /// set `urls` (non-empty takes precedence over `url`) with `start_index`; the shell auto-advances
746    /// and reports the current track ~as it changes via `Action::Input { id: "{id}.index", … }`, and
747    /// `seek_index` jumps to a track when it CHANGES (`-1` = none). The shell also reports
748    /// `"{id}.duration"`, `"{id}.state"` (0 idle / 1 buffering / 2 ready-paused / 3 playing / 4 ended)
749    /// and `"{id}.buffered"` via the same `Input` path (handle them in [`MobilerApp::input`]). Set
750    /// `allow_pip` to enable Picture-in-Picture (the shell adds a PiP affordance).
751    Video {
752        url: String,
753        id: String,
754        playing: bool,
755        seek_to_ms: i64,
756        controls: bool,
757        looping: bool,
758        muted: bool,
759        on_ended: Option<ActionToken>,
760        poster: Option<String>,
761        start_at_ms: i64,
762        captions: Vec<Caption>,
763        rate: f32,
764        volume: f32,
765        urls: Vec<String>,
766        start_index: i64,
767        seek_index: i64,
768        allow_pip: bool,
769    },
770    /// Displays the web page / embedded player at `url` in a native web view — `WKWebView` on iOS,
771    /// `android.webkit.WebView` on Android, an `<iframe>` on web. General-purpose: docs, dashboards,
772    /// or a hosted player embed (e.g. a Bunny.net / YouTube embed URL, which brings its own
773    /// captions/quality/thumbnails). JavaScript and inline media autoplay are enabled so hosted
774    /// players work. This is NOT the default way to play video — use [`Widget::Video`] for a
775    /// controllable native player. Fills its width; give it room (place in a sized container).
776    WebView { url: String },
777    /// An interactive map (a "live native view" like [`Widget::Video`]): iOS MapKit, Android MapLibre
778    /// Native, web MapLibre-GL — no API key. The app drives the camera (`center_lat`/`center_lng`/`zoom`)
779    /// and `markers`; the user pans/zooms when `interactive`. Taps report back via `Action::Input`:
780    /// a map tap → `{ id: "{id}.tap", value: Text("lat,lng") }`, a marker tap → `{ id: "{id}.marker",
781    /// value: Text(marker.id) }` (handle in [`MobilerApp::input`] by id-suffix). `style_url` selects the
782    /// MapLibre vector style on Android/web (None → a free default); iOS MapKit uses Apple Maps and
783    /// ignores it. Fills its width; give it a height (place in a sized container).
784    Map {
785        id: String,
786        center_lat: f64,
787        center_lng: f64,
788        zoom: f64,
789        markers: Vec<MapMarker>,
790        style_url: Option<String>,
791        interactive: bool,
792    },
793    /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
794    /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
795    Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
796    /// Small non-interactive colored dot — a project/identity hint.
797    ColorDot { color: ProjectColor },
798    Divider,
799    /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
800    Progress { value: Option<f32> },
801    /// Shimmer placeholder shown while content loads.
802    Skeleton,
803    /// A data chart drawing one or more named `series` in the given `style` (see [`ChartStyle`]).
804    /// `labels` (optional) annotate the x-axis for cartesian styles. `axis` shows y gridlines +
805    /// tick values (cartesian only); `legend` shows a series swatch+name row. Non-interactive.
806    Chart { series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool },
807    /// A variable-width stacked-region ("Marimekko" / coverage-gap) chart: `regions` are arbitrary
808    /// colored rectangles in the `[0, x_max] × [0, y_max]` plane (each with an in-cell label),
809    /// `ticks` annotate the irregular x-axis, `ref_lines` are horizontal target/max lines with
810    /// right-edge chips, `bracket` is an optional right-side range annotation, and `legend` names
811    /// the colors. The app supplies all geometry; shells map domain→pixels. Non-interactive.
812    RegionChart {
813        regions: Vec<ChartRegion>,
814        ticks: Vec<ChartTick>,
815        x_max: f32,
816        y_max: f32,
817        ref_lines: Vec<ChartRefLine>,
818        bracket: Option<ChartBracket>,
819        legend: Vec<ChartLegendItem>,
820    },
821    /// An inline month calendar. The core pre-computes everything locale-dependent so shells only
822    /// draw: `title` (e.g. "Septembar 2026"), the 7 `weekday_labels` in column order (week start
823    /// first), and `leading_blanks` (empty cells before day 1). `on_day[d-1]` fires when day `d` is
824    /// tapped (length = days in the month); `selected` highlights a day. `markers` is empty (no
825    /// markers) or one level per day, `0..=3`, drawn as that many small dots under the day number.
826    Calendar {
827        year: u32,
828        month: u8,
829        title: String,
830        weekday_labels: Vec<String>,
831        leading_blanks: u8,
832        selected: Option<u8>,
833        on_day: Vec<ActionToken>,
834        markers: Vec<u8>,
835    },
836    /// A list row that reveals trailing `actions` on horizontal swipe (each tappable). On web the
837    /// actions render inline as a trailing button row (no gesture).
838    SwipeAction { child: Box<Widget>, actions: Vec<SwipeButton> },
839    /// A scrollable list for long/paged feeds, with shell-detected events at both ends: the bottom
840    /// `on_load_more` fires when the user scrolls near the end (infinite scroll), the top
841    /// `on_refresh` fires on pull-to-refresh. `loading`/`refreshing`/`has_more` are app-owned: set
842    /// `loading` while a page loads (shell shows a spinner, stops firing), `has_more=false` when
843    /// exhausted, and `refreshing` while a pull-refresh runs. The app appends to `children` on each
844    /// load-more. `on_refresh` is set via [`with_refresh`](mobiler_core::with_refresh).
845    LazyList {
846        children: Vec<Widget>,
847        on_load_more: Option<ActionToken>,
848        loading: bool,
849        has_more: bool,
850        on_refresh: Option<ActionToken>,
851        refreshing: bool,
852        /// Text shown under an exhausted paged list (`has_more == false` with `on_load_more` set),
853        /// e.g. "You're all caught up" in the app's language. `None` shows nothing. Set with
854        /// `with_end_label`.
855        end_label: Option<String>,
856        /// Fill the rest of the screen instead of the fixed height, when this list is the scaffold
857        /// body or a direct child of the body's column (the first one). Set with `with_fill`.
858        fill: bool,
859    },
860    Spacer { size: Spacing },
861    // Layout
862    Row { children: Vec<Widget> },
863    Column { children: Vec<Widget> },
864    /// Card; tappable when `on_press` is set. Fires `on_long_press` (when set) on a
865    /// press-and-hold (web: a ~500 ms pointer-hold; iOS: `onLongPressGesture`;
866    /// Android: `combinedClickable`'s `onLongClick`).
867    Card {
868        child: Box<Widget>,
869        style: CardStyle,
870        on_press: Option<ActionToken>,
871        on_long_press: Option<ActionToken>,
872    },
873    /// Z-stack: children layered back-to-front, positioned by `align`. With
874    /// `scrim`, the first child is a background image, darkened for legibility,
875    /// and the rest render on top in light content.
876    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
877    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
878    /// `columns`: exactly that many equal columns (1–4) at every width; `None` = the adaptive grid
879    /// (2 on a phone, more on a tablet). BREAKING (Moj Termin design release): `columns` was added.
880    Grid { children: Vec<Widget>, columns: Option<u8> },
881    /// Horizontally scrolling row. `edge_fade` fades the trailing edge (plus trailing room so the
882    /// last item clears the fade at scroll-end) to hint there is more to scroll.
883    Scroller { children: Vec<Widget>, edge_fade: bool },
884    /// Two-pane master-detail. On a **wide** screen (tablet / landscape — the shell's regular size
885    /// class) `primary` and `detail` render side-by-side; on a **compact** screen (phone) it shows
886    /// ONE pane: `primary` until `show_detail` is set (the app sets it when a row is selected), then
887    /// `detail` with a back chevron that fires `on_back` (the app clears its selection). On wide,
888    /// `show_detail`/`on_back` are ignored — both panes stay visible, so `detail` should show a
889    /// placeholder until something is selected.
890    Split { primary: Box<Widget>, detail: Box<Widget>, show_detail: bool, on_back: Option<ActionToken> },
891    /// Accessibility wrapper: presents `child`'s subtree as ONE screen-reader element named by `label`
892    /// (so an unlabeled IconButton/Image gets a name, or a Card's children group into one announced
893    /// element). `hint` describes what activation does; `role` is the control type. Shell-applied:
894    /// iOS accessibilityLabel/Hint/Traits, Android contentDescription/role/heading, web aria-label/role.
895    A11y { child: Box<Widget>, label: String, hint: Option<String>, role: Option<A11yRole> },
896    // Input
897    /// A tappable button. `tone` recolors it (`Neutral` = the brand/primary look; `Danger` = the
898    /// error color pair for destructive actions). `icon` draws a leading glyph; `wide` stretches it
899    /// to the available width.
900    Button { label: String, style: ButtonStyle, on_press: ActionToken, tone: Tone, icon: Option<Icon>, wide: bool },
901    IconButton { icon: Icon, on_press: ActionToken },
902    Chip { label: String, selected: bool, on_press: ActionToken },
903    /// A text input. `kind` selects keyboard / secure entry / multiline
904    /// (see [`FieldKind`]); `error`, when `Some`, shows an inline validation
905    /// message below the field and marks it invalid. Emits `Input { id, Text }`.
906    TextField { id: String, placeholder: String, value: String, kind: FieldKind, error: Option<String> },
907    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
908    SearchField { id: String, placeholder: String, value: String },
909    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
910    Segmented { segments: Vec<Segment> },
911    Toggle { id: String, label: String, value: bool },
912    Checkbox { id: String, label: String, value: bool },
913    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
914    Slider { id: String, value: i32, max: i32 },
915    /// Numeric stepper with −/+ controls carrying their own events.
916    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
917    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
918    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
919    /// the whole app from it.
920    ///
921    /// `route` + `depth` drive navigation: the shell animates the body when
922    /// `route` (the current screen's identity) changes — slide for push/pop
923    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
924    /// move at the same depth — and wires the system back button to `back`.
925    Scaffold {
926        title: String,
927        body: Box<Widget>,
928        tabs: Vec<Tab>,
929        back: Option<ActionToken>,
930        dark_mode: bool,
931        /// App branding (brand color, corner, density, font). `None` = framework
932        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
933        theme: Option<Theme>,
934        /// Optional floating action button (raised primary action over the body).
935        fab: Option<Fab>,
936        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
937        sheet: Option<Sheet>,
938        /// Pull-to-refresh: when set, the body is pull-refreshable and fires this event on pull.
939        /// The app owns `refreshing` — set it true when the pull fires, clear it when the async
940        /// reload completes (the shell shows a spinner while it's true).
941        on_refresh: Option<ActionToken>,
942        refreshing: bool,
943        route: String,
944        depth: u32,
945        /// App-wide shell text (see [`ShellLabels`]). `None` ⇒ the shells' English defaults.
946        labels: Option<ShellLabels>,
947        /// `Some` overrides `dark_mode` (see [`Appearance`]); `None` = `dark_mode` decides.
948        appearance: Option<Appearance>,
949        /// A screen's main actions pinned above the tabs and the system navigation (equal-width
950        /// row); the body ends above it. `None` / empty = no bar. BREAKING (Moj Termin design
951        /// release): appended — full `Scaffold` literals and patterns need it.
952        bottom_bar: Option<Vec<Widget>>,
953    },
954    /// A step indicator for a multi-step flow: `total` equal segments, the first `current` filled.
955    /// Spoken as one element, "Step 2 of 3" (or [`ShellLabels::step_of`]), never as a percentage.
956    /// `caption` also shows that text above the bar, still as the same single element.
957    Steps { total: u8, current: u8, caption: bool },
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963    use serde::Serialize;
964    use serde::de::DeserializeOwned;
965
966    // Round-trips the ABI without requiring `PartialEq` on the wire types:
967    // serialize → deserialize → re-serialize, and compare the two encodings.
968    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
969        let a = serde_json::to_string(value).expect("serialize");
970        let back: T = serde_json::from_str(&a).expect("deserialize");
971        let b = serde_json::to_string(&back).expect("re-serialize");
972        assert_eq!(a, b);
973    }
974
975    #[test]
976    fn action_round_trips() {
977        round_trips(&Action::Start);
978        round_trips(&Action::Fired { token: "tok".to_string() });
979        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
980        round_trips(&Action::Restore { data: "{}".to_string() });
981        round_trips(&Action::AppInfo {
982            version: "1.0".to_string(),
983            build: "7".to_string(),
984            platform: "ios".to_string(),
985            bundle_id: "rs.x".to_string(),
986        });
987    }
988
989    #[test]
990    fn steps_round_trip() {
991        round_trips(&Widget::Steps { total: 3, current: 2, caption: true });
992    }
993
994    #[test]
995    fn grid_columns_and_dashed_card_round_trip() {
996        round_trips(&Widget::Grid { children: vec![], columns: Some(3) });
997        round_trips(&Widget::Card { child: Box::new(Widget::Spacer { size: Spacing::Md }), style: CardStyle::Dashed, on_press: None, on_long_press: None });
998    }
999
1000    #[test]
1001    fn badge_icon_and_avatar_initials_round_trip() {
1002        round_trips(&Widget::Badge { label: "Finished".into(), tone: Tone::Info, icon: Some(Icon::DoneAll) });
1003        round_trips(&Widget::Avatar { source: String::new(), status: None, initials: Some("MJ".into()), size: Some(40) });
1004    }
1005
1006    #[test]
1007    fn extended_fab_round_trips() {
1008        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: Some("Novi termin".into()) });
1009        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: None });
1010    }
1011
1012    #[test]
1013    fn shapes_round_trip() {
1014        let shapes = Shapes { card: Some(Radius::Dp(12)), button: Some(Radius::Pill), ..Default::default() };
1015        round_trips(&Theme { shapes: Some(shapes), ..Default::default() });
1016        assert_eq!(Theme::default().shapes, None);
1017    }
1018
1019    #[test]
1020    fn type_scale_and_new_styles_round_trip() {
1021        let ts = TypeScale { display: Some(TypeSpec::new(36, 700, FamilyRole::Display)), ..Default::default() };
1022        round_trips(&Theme { type_scale: Some(ts), ..Default::default() });
1023        round_trips(&Widget::Text { content: "12:00".to_string(), style: TextStyle::Display });
1024        round_trips(&Widget::Text { content: "Booking".to_string(), style: TextStyle::Headline });
1025        assert_eq!(Theme::default().type_scale, None);
1026    }
1027
1028    #[test]
1029    fn custom_font_family_round_trips() {
1030        round_trips(&Theme { font: FontFamily::Custom, ..Default::default() });
1031    }
1032
1033    #[test]
1034    fn rgb_hex_splits_channels() {
1035        assert_eq!(Rgb::hex(0x231f20), Rgb::new(0x23, 0x1f, 0x20));
1036        assert_eq!(Rgb::hex(0xffffff), Rgb::new(255, 255, 255));
1037    }
1038
1039    #[test]
1040    fn theme_default_has_no_palette_and_palette_round_trips() {
1041        assert_eq!(Theme::default().palette, None);
1042        let dark = ColorRoles {
1043            background: Some(Rgb::hex(0x231f20)),
1044            danger: Some(TonePair::new(Rgb::hex(0x4d2626), Rgb::hex(0xffb4ab))),
1045            scrim: Some(Rgba::new(0, 0, 0, 82)),
1046            ..Default::default()
1047        };
1048        let theme = Theme { palette: Some(Palette { light: ColorRoles::default(), dark }), ..Default::default() };
1049        round_trips(&theme);
1050        assert_eq!(ColorRoles::default().surface, None);
1051    }
1052
1053    #[test]
1054    fn widget_round_trips() {
1055        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
1056        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
1057        round_trips(&Widget::Chart {
1058            series: vec![ChartSeries { name: "s".to_string(), values: vec![1.0, 2.5, 3.0], color: None, goal: None }],
1059            labels: vec!["a".to_string()],
1060            style: ChartStyle::Bar,
1061            axis: true,
1062            legend: false,
1063        });
1064        round_trips(&Widget::RegionChart {
1065            regions: vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical(),
1066                          ChartRegion::new(3.0, 21.0, 0.0, 80.0, "CHF 80'000").with_color(Rgb::new(0x8E, 0xC6, 0xBA))],
1067            ticks: vec![ChartTick { at: 3.0, label: "3 Mt.".to_string() }, ChartTick { at: 65.0, label: "65 J.".to_string() }],
1068            x_max: 65.0,
1069            y_max: 80.0,
1070            ref_lines: vec![ChartRefLine { value: 80.0, label: "CHF 80'000".to_string(), dashed: false }],
1071            bracket: Some(ChartBracket { y0: 60.0, y1: 80.0, label: "Ceiling".to_string(), info: true }),
1072            legend: vec![ChartLegendItem { label: "Gap".to_string(), color: Rgb::new(0x5A, 0x7D, 0x9A) }],
1073        });
1074        round_trips(&Widget::PdfView { url: "https://example.com/report.pdf".to_string() });
1075        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 });
1076        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 });
1077        round_trips(&Widget::WebView { url: "https://iframe.mediadelivery.net/embed/1/abc".to_string() });
1078        round_trips(&Widget::Map { id: "m1".to_string(), center_lat: 47.3769, center_lng: 8.5417, zoom: 14.0, markers: vec![MapMarker { id: "shop".to_string(), lat: 47.3769, lng: 8.5417, title: Some("Fade House".to_string()) }], style_url: Some("https://tiles.openfreemap.org/styles/liberty".to_string()), interactive: true });
1079        round_trips(&Widget::Map { id: "m2".to_string(), center_lat: 0.0, center_lng: 0.0, zoom: 2.0, markers: vec![], style_url: None, interactive: false });
1080        round_trips(&Widget::TextField { id: "email".to_string(), placeholder: "you@co".to_string(), value: "".to_string(), kind: FieldKind::Email, error: None });
1081        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()) });
1082        round_trips(&Widget::Calendar { year: 2026, month: 9, title: "Septembar 2026".to_string(), weekday_labels: ["P", "U", "S", "Č", "P", "S", "N"].map(String::from).to_vec(), leading_blanks: 1, selected: Some(15), on_day: vec!["d1".to_string(), "d2".to_string()], markers: vec![0, 3] });
1083        round_trips(&Widget::SwipeAction { child: Box::new(Widget::Divider), actions: vec![SwipeButton { label: "Del".to_string(), tone: Tone::Danger, on_tap: "t".to_string() }] });
1084        round_trips(&Widget::Button { label: "Otkaži".to_string(), style: ButtonStyle::Tonal, on_press: "x".to_string(), tone: Tone::Danger, icon: Some(Icon::Close), wide: true });
1085        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: true, on_back: Some("back".to_string()) });
1086        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: false, on_back: None });
1087        round_trips(&Widget::Scroller { children: vec![Widget::Divider], edge_fade: true });
1088        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, end_label: None, fill: false });
1089        round_trips(&Widget::LazyList { children: vec![], on_load_more: Some("more".to_string()), loading: false, has_more: false, on_refresh: None, refreshing: false, end_label: Some("Kraj liste".to_string()), fill: false });
1090        round_trips(&Widget::LazyList { children: vec![], on_load_more: Some("more".to_string()), loading: false, has_more: true, on_refresh: None, refreshing: false, end_label: None, fill: true });
1091        // Un-themed scaffold (theme: None) — the default, must round-trip.
1092        round_trips(&Widget::Scaffold {
1093            title: "T".to_string(),
1094            body: Box::new(Widget::Divider),
1095            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
1096            back: Some("b".to_string()),
1097            dark_mode: true,
1098            theme: None,
1099            fab: None,
1100            sheet: None,
1101            on_refresh: None,
1102            refreshing: false,
1103            route: "r".to_string(),
1104            depth: 2,
1105            labels: None,
1106            appearance: None,
1107            bottom_bar: None,
1108        });
1109        // Themed scaffold — all four theme knobs must round-trip.
1110        round_trips(&Widget::Scaffold {
1111            title: "T".to_string(),
1112            body: Box::new(Widget::Divider),
1113            tabs: vec![],
1114            back: None,
1115            dark_mode: false,
1116            theme: Some(Theme {
1117                seed: Rgb::new(0xC8, 0x5A, 0x3C),
1118                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
1119                corner: Corner::Large,
1120                density: Density::Compact,
1121                font: FontFamily::Rounded,
1122                ..Default::default()
1123            }),
1124            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string(), label: None }),
1125            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
1126            on_refresh: Some("r".to_string()),
1127            refreshing: true,
1128            route: "r".to_string(),
1129            depth: 1,
1130            labels: None,
1131            appearance: None,
1132            bottom_bar: Some(vec![Widget::Divider]),
1133        });
1134        // Themed scaffold with Density::Large — the big-touch-target density must round-trip.
1135        round_trips(&Widget::Scaffold {
1136            title: "T".to_string(),
1137            body: Box::new(Widget::Divider),
1138            tabs: vec![],
1139            back: None,
1140            dark_mode: false,
1141            theme: Some(Theme {
1142                seed: Rgb::new(0xC8, 0x5A, 0x3C),
1143                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
1144                corner: Corner::Large,
1145                density: Density::Large,
1146                font: FontFamily::Rounded,
1147                ..Default::default()
1148            }),
1149            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string(), label: None }),
1150            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
1151            on_refresh: Some("r".to_string()),
1152            refreshing: true,
1153            route: "r".to_string(),
1154            depth: 1,
1155            labels: None,
1156            appearance: None,
1157            bottom_bar: None,
1158        });
1159        // Labelled scaffold — every ShellLabels field must round-trip.
1160        round_trips(&Widget::Scaffold {
1161            title: "T".to_string(),
1162            body: Box::new(Widget::Divider),
1163            tabs: vec![],
1164            back: None,
1165            dark_mode: false,
1166            theme: None,
1167            fab: None,
1168            sheet: None,
1169            on_refresh: None,
1170            refreshing: false,
1171            route: "r".to_string(),
1172            depth: 1,
1173            labels: Some(
1174                ShellLabels::new()
1175                    .back("Nazad")
1176                    .load_more("Učitaj još")
1177                    .refresh("Osveži")
1178                    .ok("U redu")
1179                    .cancel("Otkaži")
1180                    .done("Gotovo")
1181                    .pdf_error("Greška")
1182                    .pdf_title("Dokument")
1183                    .web_title("Stranica"),
1184            ),
1185            appearance: Some(Appearance::System),
1186            bottom_bar: None,
1187        });
1188    }
1189}