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 (unless `selection` is set).
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 (Danger: unless
496    /// `error_fill` is set).
497    pub success: Option<TonePair>,
498    pub warning: Option<TonePair>,
499    pub danger: Option<TonePair>,
500    pub info: Option<TonePair>,
501    /// Sheet and dialog scrim.
502    pub scrim: Option<Rgba>,
503    /// Focus and selection marks: the focused field's border, label and cursor, checked toggles and
504    /// checkboxes, sliders, progress. Unset: the shell's current colour (`primary` on most shells).
505    pub selection: Option<Rgb>,
506    /// Error text and the invalid field's border; outlined and text Danger buttons. Unset: `danger`'s
507    /// on-container colour, as before.
508    pub error: Option<Rgb>,
509    /// A filled Danger button's background. Unset: the `danger` pair, swapped, as before.
510    pub error_fill: Option<Rgb>,
511    /// A filled Danger button's text. Unset: as before.
512    pub on_error_fill: Option<Rgb>,
513}
514
515/// A tone's soft background and its foreground.
516#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
517#[repr(C)]
518pub struct TonePair {
519    pub container: Rgb,
520    pub on_container: Rgb,
521}
522
523impl TonePair {
524    #[must_use]
525    pub const fn new(container: Rgb, on_container: Rgb) -> Self {
526        Self { container, on_container }
527    }
528}
529
530/// A colour with alpha (`a`: 0 = transparent, 255 = opaque).
531#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
532#[repr(C)]
533pub struct Rgba {
534    pub r: u8,
535    pub g: u8,
536    pub b: u8,
537    pub a: u8,
538}
539
540impl Rgba {
541    #[must_use]
542    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
543        Self { r, g, b, a }
544    }
545}
546
547/// How the scaffold picks light or dark. `Light`/`Dark` force it; `System` follows the OS live (the
548/// shell switches palette sets itself, no core round-trip). Set with `with_appearance`.
549#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
550#[repr(C)]
551pub enum Appearance { Light, Dark, System }
552
553/// Text the shells draw themselves (back buttons, web list controls, dialog/picker defaults), in the
554/// app's language. Set once on the scaffold with `with_labels`; every field is optional and falls
555/// back to the shell's built-in English. A label passed to a specific call (`confirm_with`,
556/// `Picker`) still wins over these.
557#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
558#[repr(C)]
559pub struct ShellLabels {
560    /// `Split` back-button text on every shell; the Scaffold back button's accessible name.
561    pub back: Option<String>,
562    /// Web `LazyList` "Load more" button.
563    pub load_more: Option<String>,
564    /// Web `LazyList` refresh button (shown after a ↻) and the web scaffold refresh button's name.
565    pub refresh: Option<String>,
566    /// Confirm dialog: the confirming button when the call gives no label.
567    pub ok: Option<String>,
568    /// Confirm dialog and pickers: the dismissing button when the call gives no label.
569    pub cancel: Option<String>,
570    /// Pickers: the accepting button when the call gives no label.
571    pub done: Option<String>,
572    /// Android PdfView error text.
573    pub pdf_error: Option<String>,
574    /// Web PDF iframe title (accessibility).
575    pub pdf_title: Option<String>,
576    /// Web WebView iframe title (accessibility).
577    pub web_title: Option<String>,
578    /// The step indicator's spoken text ([`Widget::Steps`]), with `{current}` / `{total}`
579    /// placeholders: `"Korak {current} od {total}"`. Default `"Step {current} of {total}"`.
580    pub step_of: Option<String>,
581}
582
583impl ShellLabels {
584    #[must_use]
585    pub fn new() -> Self {
586        Self::default()
587    }
588    #[must_use]
589    pub fn back(mut self, l: impl Into<String>) -> Self {
590        self.back = Some(l.into());
591        self
592    }
593    #[must_use]
594    pub fn load_more(mut self, l: impl Into<String>) -> Self {
595        self.load_more = Some(l.into());
596        self
597    }
598    #[must_use]
599    pub fn refresh(mut self, l: impl Into<String>) -> Self {
600        self.refresh = Some(l.into());
601        self
602    }
603    #[must_use]
604    pub fn ok(mut self, l: impl Into<String>) -> Self {
605        self.ok = Some(l.into());
606        self
607    }
608    #[must_use]
609    pub fn cancel(mut self, l: impl Into<String>) -> Self {
610        self.cancel = Some(l.into());
611        self
612    }
613    #[must_use]
614    pub fn done(mut self, l: impl Into<String>) -> Self {
615        self.done = Some(l.into());
616        self
617    }
618    #[must_use]
619    pub fn pdf_error(mut self, l: impl Into<String>) -> Self {
620        self.pdf_error = Some(l.into());
621        self
622    }
623    #[must_use]
624    pub fn pdf_title(mut self, l: impl Into<String>) -> Self {
625        self.pdf_title = Some(l.into());
626        self
627    }
628    #[must_use]
629    pub fn web_title(mut self, l: impl Into<String>) -> Self {
630        self.web_title = Some(l.into());
631        self
632    }
633    #[must_use]
634    pub fn step_of(mut self, l: impl Into<String>) -> Self {
635        self.step_of = Some(l.into());
636        self
637    }
638}
639
640/// A bottom-navigation tab. `selected` marks the active one; tapping sends
641/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
642#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
643#[repr(C)]
644pub struct Tab {
645    pub label: String,
646    pub selected: bool,
647    pub on_select: ActionToken,
648    /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
649    pub icon: Option<Icon>,
650}
651
652/// A floating action button anchored over the scaffold body (the raised primary action).
653#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
654#[repr(C)]
655pub struct Fab {
656    pub icon: Icon,
657    pub on_press: ActionToken,
658    /// Extended FAB: the label shown next to the icon, which is also its accessible name. `None` = the
659    /// round FAB. BREAKING (Moj Termin design release): `Fab { .. }` literals need this field; the
660    /// `with_fab` / `with_extended_fab` builders are unaffected.
661    pub label: Option<String>,
662}
663
664/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
665/// active segment; tapping sends `on_select`.
666#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
667#[repr(C)]
668pub struct Segment {
669    pub label: String,
670    pub selected: bool,
671    pub on_select: ActionToken,
672}
673
674/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
675/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
676#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
677#[repr(C)]
678pub struct Sheet {
679    pub title: String,
680    pub child: Box<Widget>,
681    pub on_dismiss: ActionToken,
682}
683
684/// One revealed action in a `SwipeAction` row (swipe to reveal, tap to fire).
685#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
686#[repr(C)]
687pub struct SwipeButton {
688    pub label: String,
689    pub tone: Tone,
690    pub on_tap: ActionToken,
691}
692
693/// One subtitle/caption track for a [`Widget::Video`]. `url` points at a WebVTT (`.vtt`) file,
694/// `language` is a BCP-47 tag (e.g. `"en"`), `label` is the human-readable menu entry, and
695/// `default_on` selects it by default. Sidecar tracks work on web (`<track>`) and Android
696/// (Media3 subtitle configuration); on iOS only captions already embedded in an HLS manifest are
697/// selectable (AVPlayer can't attach a sidecar VTT to an MP4 — a documented v1 gap).
698#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
699#[repr(C)]
700pub struct Caption {
701    pub url: String,
702    pub label: String,
703    pub language: String,
704    pub default_on: bool,
705}
706
707/// A pin on a [`Widget::Map`]. `id` is echoed back when the marker is tapped
708/// (`Action::Input { id: "{map_id}.marker", value: Text(marker.id) }`).
709#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
710#[repr(C)]
711pub struct MapMarker {
712    pub id: String,
713    pub lat: f64,
714    pub lng: f64,
715    pub title: Option<String>,
716}
717
718// ------------------------------- widgets -------------------------------
719
720/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
721// `Scaffold`'s `ShellLabels` (nine `Option<String>` fields) makes it the largest variant by a wide
722// margin; boxing it would ripple through every `with_labels`/scaffold call site for no runtime
723// benefit on a wire type that is rebuilt per-render, not stored in bulk.
724#[allow(clippy::large_enum_variant)]
725#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
726#[repr(C)]
727pub enum Widget {
728    // Content
729    Text { content: String, style: TextStyle },
730    Image { source: String, shape: ImageShape, ratio: ImageRatio },
731    /// A status pill. `icon` (before the label, decorative) makes the status readable without its
732    /// colour. BREAKING (Moj Termin design release): `icon` was added — exhaustive patterns and full
733    /// literals need it; `badge` / `with_icon` are unaffected.
734    Badge { label: String, tone: Tone, icon: Option<Icon> },
735    /// A circular avatar image with an optional colored status dot. `initials` (at most two
736    /// characters) are drawn when `source` is empty or fails to load; `size` is the diameter
737    /// (`None` = 48). BREAKING (Moj Termin design release): `initials` and `size` were added.
738    Avatar { source: String, status: Option<Tone>, initials: Option<String>, size: Option<u8> },
739    /// An in-app PDF viewer showing the document at `url` (a remote https URL or a local
740    /// file URI). Each shell uses its native renderer — PDFKit on iOS, a paged `PdfRenderer`
741    /// on Android, an `<iframe>` on web — so the app only supplies the URL (e.g. a
742    /// backend-generated report). Fills its width; give it room (place in a sized container).
743    PdfView { url: String },
744    /// An in-app native video player for the stream/file at `url` (MP4 everywhere; HLS `.m3u8` on
745    /// iOS/Android natively + Safari on web; or a local file URI). Native player per shell — AVPlayer
746    /// (iOS), Media3/ExoPlayer (Android), a `<video>` element (web). **Controllable:** `playing` drives
747    /// play/pause (app-owned, like a `Toggle`); set `seek_to_ms` to jump (the shell seeks when the value
748    /// CHANGES; `-1` = no seek). The shell reports the current position ~once/second via
749    /// `Action::Input { id, value: Int(position_ms) }` (handle it in [`MobilerApp::input`]), and fires
750    /// `on_ended` when the clip finishes. `controls` shows the native transport bar; `looping` restarts
751    /// on end; `muted` starts muted (needed for reliable autoplay). Fills its width; give it room.
752    ///
753    /// v2 fields: `poster` shows a thumbnail image before the first play; `start_at_ms` resumes at an
754    /// offset (applied once on load, `-1` = start). `captions` adds subtitle tracks (see [`Caption`]).
755    /// `rate` sets playback speed (`1.0` = normal) and `volume` the level (`0.0`–`1.0`). For a playlist,
756    /// set `urls` (non-empty takes precedence over `url`) with `start_index`; the shell auto-advances
757    /// and reports the current track ~as it changes via `Action::Input { id: "{id}.index", … }`, and
758    /// `seek_index` jumps to a track when it CHANGES (`-1` = none). The shell also reports
759    /// `"{id}.duration"`, `"{id}.state"` (0 idle / 1 buffering / 2 ready-paused / 3 playing / 4 ended)
760    /// and `"{id}.buffered"` via the same `Input` path (handle them in [`MobilerApp::input`]). Set
761    /// `allow_pip` to enable Picture-in-Picture (the shell adds a PiP affordance).
762    Video {
763        url: String,
764        id: String,
765        playing: bool,
766        seek_to_ms: i64,
767        controls: bool,
768        looping: bool,
769        muted: bool,
770        on_ended: Option<ActionToken>,
771        poster: Option<String>,
772        start_at_ms: i64,
773        captions: Vec<Caption>,
774        rate: f32,
775        volume: f32,
776        urls: Vec<String>,
777        start_index: i64,
778        seek_index: i64,
779        allow_pip: bool,
780    },
781    /// Displays the web page / embedded player at `url` in a native web view — `WKWebView` on iOS,
782    /// `android.webkit.WebView` on Android, an `<iframe>` on web. General-purpose: docs, dashboards,
783    /// or a hosted player embed (e.g. a Bunny.net / YouTube embed URL, which brings its own
784    /// captions/quality/thumbnails). JavaScript and inline media autoplay are enabled so hosted
785    /// players work. This is NOT the default way to play video — use [`Widget::Video`] for a
786    /// controllable native player. Fills its width; give it room (place in a sized container).
787    WebView { url: String },
788    /// An interactive map (a "live native view" like [`Widget::Video`]): iOS MapKit, Android MapLibre
789    /// Native, web MapLibre-GL — no API key. The app drives the camera (`center_lat`/`center_lng`/`zoom`)
790    /// and `markers`; the user pans/zooms when `interactive`. Taps report back via `Action::Input`:
791    /// a map tap → `{ id: "{id}.tap", value: Text("lat,lng") }`, a marker tap → `{ id: "{id}.marker",
792    /// value: Text(marker.id) }` (handle in [`MobilerApp::input`] by id-suffix). `style_url` selects the
793    /// MapLibre vector style on Android/web (None → a free default); iOS MapKit uses Apple Maps and
794    /// ignores it. Fills its width; give it a height (place in a sized container).
795    Map {
796        id: String,
797        center_lat: f64,
798        center_lng: f64,
799        zoom: f64,
800        markers: Vec<MapMarker>,
801        style_url: Option<String>,
802        interactive: bool,
803    },
804    /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
805    /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
806    Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
807    /// Small non-interactive colored dot — a project/identity hint.
808    ColorDot { color: ProjectColor },
809    Divider,
810    /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
811    Progress { value: Option<f32> },
812    /// Shimmer placeholder shown while content loads.
813    Skeleton,
814    /// A data chart drawing one or more named `series` in the given `style` (see [`ChartStyle`]).
815    /// `labels` (optional) annotate the x-axis for cartesian styles. `axis` shows y gridlines +
816    /// tick values (cartesian only); `legend` shows a series swatch+name row. Non-interactive.
817    Chart { series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool },
818    /// A variable-width stacked-region ("Marimekko" / coverage-gap) chart: `regions` are arbitrary
819    /// colored rectangles in the `[0, x_max] × [0, y_max]` plane (each with an in-cell label),
820    /// `ticks` annotate the irregular x-axis, `ref_lines` are horizontal target/max lines with
821    /// right-edge chips, `bracket` is an optional right-side range annotation, and `legend` names
822    /// the colors. The app supplies all geometry; shells map domain→pixels. Non-interactive.
823    RegionChart {
824        regions: Vec<ChartRegion>,
825        ticks: Vec<ChartTick>,
826        x_max: f32,
827        y_max: f32,
828        ref_lines: Vec<ChartRefLine>,
829        bracket: Option<ChartBracket>,
830        legend: Vec<ChartLegendItem>,
831    },
832    /// An inline month calendar. The core pre-computes everything locale-dependent so shells only
833    /// draw: `title` (e.g. "Septembar 2026"), the 7 `weekday_labels` in column order (week start
834    /// first), and `leading_blanks` (empty cells before day 1). `on_day[d-1]` fires when day `d` is
835    /// tapped (length = days in the month); `selected` highlights a day. `markers` is empty (no
836    /// markers) or one level per day, `0..=3`, drawn as that many small dots under the day number.
837    Calendar {
838        year: u32,
839        month: u8,
840        title: String,
841        weekday_labels: Vec<String>,
842        leading_blanks: u8,
843        selected: Option<u8>,
844        on_day: Vec<ActionToken>,
845        markers: Vec<u8>,
846    },
847    /// A list row that reveals trailing `actions` on horizontal swipe (each tappable). On web the
848    /// actions render inline as a trailing button row (no gesture).
849    SwipeAction { child: Box<Widget>, actions: Vec<SwipeButton> },
850    /// A scrollable list for long/paged feeds, with shell-detected events at both ends: the bottom
851    /// `on_load_more` fires when the user scrolls near the end (infinite scroll), the top
852    /// `on_refresh` fires on pull-to-refresh. `loading`/`refreshing`/`has_more` are app-owned: set
853    /// `loading` while a page loads (shell shows a spinner, stops firing), `has_more=false` when
854    /// exhausted, and `refreshing` while a pull-refresh runs. The app appends to `children` on each
855    /// load-more. `on_refresh` is set via [`with_refresh`](mobiler_core::with_refresh).
856    LazyList {
857        children: Vec<Widget>,
858        on_load_more: Option<ActionToken>,
859        loading: bool,
860        has_more: bool,
861        on_refresh: Option<ActionToken>,
862        refreshing: bool,
863        /// Text shown under an exhausted paged list (`has_more == false` with `on_load_more` set),
864        /// e.g. "You're all caught up" in the app's language. `None` shows nothing. Set with
865        /// `with_end_label`.
866        end_label: Option<String>,
867        /// Fill the rest of the screen instead of the fixed height, when this list is the scaffold
868        /// body or a direct child of the body's column (the first one). Set with `with_fill`.
869        fill: bool,
870    },
871    Spacer { size: Spacing },
872    // Layout
873    Row { children: Vec<Widget> },
874    Column { children: Vec<Widget> },
875    /// Card; tappable when `on_press` is set. Fires `on_long_press` (when set) on a
876    /// press-and-hold (web: a ~500 ms pointer-hold; iOS: `onLongPressGesture`;
877    /// Android: `combinedClickable`'s `onLongClick`).
878    Card {
879        child: Box<Widget>,
880        style: CardStyle,
881        on_press: Option<ActionToken>,
882        on_long_press: Option<ActionToken>,
883    },
884    /// Z-stack: children layered back-to-front, positioned by `align`. With
885    /// `scrim`, the first child is a background image, darkened for legibility,
886    /// and the rest render on top in light content.
887    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
888    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
889    /// `columns`: exactly that many equal columns (1–4) at every width; `None` = the adaptive grid
890    /// (2 on a phone, more on a tablet). BREAKING (Moj Termin design release): `columns` was added.
891    Grid { children: Vec<Widget>, columns: Option<u8> },
892    /// Horizontally scrolling row. `edge_fade` fades the trailing edge (plus trailing room so the
893    /// last item clears the fade at scroll-end) to hint there is more to scroll.
894    Scroller { children: Vec<Widget>, edge_fade: bool },
895    /// Two-pane master-detail. On a **wide** screen (tablet / landscape — the shell's regular size
896    /// class) `primary` and `detail` render side-by-side; on a **compact** screen (phone) it shows
897    /// ONE pane: `primary` until `show_detail` is set (the app sets it when a row is selected), then
898    /// `detail` with a back chevron that fires `on_back` (the app clears its selection). On wide,
899    /// `show_detail`/`on_back` are ignored — both panes stay visible, so `detail` should show a
900    /// placeholder until something is selected.
901    Split { primary: Box<Widget>, detail: Box<Widget>, show_detail: bool, on_back: Option<ActionToken> },
902    /// Accessibility wrapper: presents `child`'s subtree as ONE screen-reader element named by `label`
903    /// (so an unlabeled IconButton/Image gets a name, or a Card's children group into one announced
904    /// element). `hint` describes what activation does; `role` is the control type. Shell-applied:
905    /// iOS accessibilityLabel/Hint/Traits, Android contentDescription/role/heading, web aria-label/role.
906    A11y { child: Box<Widget>, label: String, hint: Option<String>, role: Option<A11yRole> },
907    // Input
908    /// A tappable button. `tone` recolors it (`Neutral` = the brand/primary look; `Danger` = the
909    /// error color pair for destructive actions). `icon` draws a leading glyph; `wide` stretches it
910    /// to the available width.
911    Button { label: String, style: ButtonStyle, on_press: ActionToken, tone: Tone, icon: Option<Icon>, wide: bool },
912    IconButton { icon: Icon, on_press: ActionToken },
913    Chip { label: String, selected: bool, on_press: ActionToken },
914    /// A text input. `kind` selects keyboard / secure entry / multiline
915    /// (see [`FieldKind`]); `error`, when `Some`, shows an inline validation
916    /// message below the field and marks it invalid. Emits `Input { id, Text }`.
917    TextField { id: String, placeholder: String, value: String, kind: FieldKind, error: Option<String> },
918    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
919    SearchField { id: String, placeholder: String, value: String },
920    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
921    Segmented { segments: Vec<Segment> },
922    Toggle { id: String, label: String, value: bool },
923    Checkbox { id: String, label: String, value: bool },
924    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
925    Slider { id: String, value: i32, max: i32 },
926    /// Numeric stepper with −/+ controls carrying their own events.
927    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
928    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
929    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
930    /// the whole app from it.
931    ///
932    /// `route` + `depth` drive navigation: the shell animates the body when
933    /// `route` (the current screen's identity) changes — slide for push/pop
934    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
935    /// move at the same depth — and wires the system back button to `back`.
936    Scaffold {
937        title: String,
938        body: Box<Widget>,
939        tabs: Vec<Tab>,
940        back: Option<ActionToken>,
941        dark_mode: bool,
942        /// App branding (brand color, corner, density, font). `None` = framework
943        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
944        theme: Option<Theme>,
945        /// Optional floating action button (raised primary action over the body).
946        fab: Option<Fab>,
947        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
948        sheet: Option<Sheet>,
949        /// Pull-to-refresh: when set, the body is pull-refreshable and fires this event on pull.
950        /// The app owns `refreshing` — set it true when the pull fires, clear it when the async
951        /// reload completes (the shell shows a spinner while it's true).
952        on_refresh: Option<ActionToken>,
953        refreshing: bool,
954        route: String,
955        depth: u32,
956        /// App-wide shell text (see [`ShellLabels`]). `None` ⇒ the shells' English defaults.
957        labels: Option<ShellLabels>,
958        /// `Some` overrides `dark_mode` (see [`Appearance`]); `None` = `dark_mode` decides.
959        appearance: Option<Appearance>,
960        /// A screen's main actions pinned above the tabs and the system navigation (equal-width
961        /// row); the body ends above it. `None` / empty = no bar. BREAKING (Moj Termin design
962        /// release): appended — full `Scaffold` literals and patterns need it.
963        bottom_bar: Option<Vec<Widget>>,
964    },
965    /// A step indicator for a multi-step flow: `total` equal segments, the first `current` filled.
966    /// Spoken as one element, "Step 2 of 3" (or [`ShellLabels::step_of`]), never as a percentage.
967    /// `caption` also shows that text above the bar, still as the same single element.
968    Steps { total: u8, current: u8, caption: bool },
969}
970
971#[cfg(test)]
972mod tests {
973    use super::*;
974    use serde::Serialize;
975    use serde::de::DeserializeOwned;
976
977    // Round-trips the ABI without requiring `PartialEq` on the wire types:
978    // serialize → deserialize → re-serialize, and compare the two encodings.
979    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
980        let a = serde_json::to_string(value).expect("serialize");
981        let back: T = serde_json::from_str(&a).expect("deserialize");
982        let b = serde_json::to_string(&back).expect("re-serialize");
983        assert_eq!(a, b);
984    }
985
986    #[test]
987    fn action_round_trips() {
988        round_trips(&Action::Start);
989        round_trips(&Action::Fired { token: "tok".to_string() });
990        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
991        round_trips(&Action::Restore { data: "{}".to_string() });
992        round_trips(&Action::AppInfo {
993            version: "1.0".to_string(),
994            build: "7".to_string(),
995            platform: "ios".to_string(),
996            bundle_id: "rs.x".to_string(),
997        });
998    }
999
1000    #[test]
1001    fn steps_round_trip() {
1002        round_trips(&Widget::Steps { total: 3, current: 2, caption: true });
1003    }
1004
1005    #[test]
1006    fn grid_columns_and_dashed_card_round_trip() {
1007        round_trips(&Widget::Grid { children: vec![], columns: Some(3) });
1008        round_trips(&Widget::Card { child: Box::new(Widget::Spacer { size: Spacing::Md }), style: CardStyle::Dashed, on_press: None, on_long_press: None });
1009    }
1010
1011    #[test]
1012    fn badge_icon_and_avatar_initials_round_trip() {
1013        round_trips(&Widget::Badge { label: "Finished".into(), tone: Tone::Info, icon: Some(Icon::DoneAll) });
1014        round_trips(&Widget::Avatar { source: String::new(), status: None, initials: Some("MJ".into()), size: Some(40) });
1015    }
1016
1017    #[test]
1018    fn extended_fab_round_trips() {
1019        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: Some("Novi termin".into()) });
1020        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: None });
1021    }
1022
1023    #[test]
1024    fn shapes_round_trip() {
1025        let shapes = Shapes { card: Some(Radius::Dp(12)), button: Some(Radius::Pill), ..Default::default() };
1026        round_trips(&Theme { shapes: Some(shapes), ..Default::default() });
1027        assert_eq!(Theme::default().shapes, None);
1028    }
1029
1030    #[test]
1031    fn type_scale_and_new_styles_round_trip() {
1032        let ts = TypeScale { display: Some(TypeSpec::new(36, 700, FamilyRole::Display)), ..Default::default() };
1033        round_trips(&Theme { type_scale: Some(ts), ..Default::default() });
1034        round_trips(&Widget::Text { content: "12:00".to_string(), style: TextStyle::Display });
1035        round_trips(&Widget::Text { content: "Booking".to_string(), style: TextStyle::Headline });
1036        assert_eq!(Theme::default().type_scale, None);
1037    }
1038
1039    #[test]
1040    fn custom_font_family_round_trips() {
1041        round_trips(&Theme { font: FontFamily::Custom, ..Default::default() });
1042    }
1043
1044    #[test]
1045    fn rgb_hex_splits_channels() {
1046        assert_eq!(Rgb::hex(0x231f20), Rgb::new(0x23, 0x1f, 0x20));
1047        assert_eq!(Rgb::hex(0xffffff), Rgb::new(255, 255, 255));
1048    }
1049
1050    #[test]
1051    fn theme_default_has_no_palette_and_palette_round_trips() {
1052        assert_eq!(Theme::default().palette, None);
1053        let dark = ColorRoles {
1054            background: Some(Rgb::hex(0x231f20)),
1055            danger: Some(TonePair::new(Rgb::hex(0x4d2626), Rgb::hex(0xffb4ab))),
1056            scrim: Some(Rgba::new(0, 0, 0, 82)),
1057            ..Default::default()
1058        };
1059        let theme = Theme { palette: Some(Palette { light: ColorRoles::default(), dark }), ..Default::default() };
1060        round_trips(&theme);
1061        assert_eq!(ColorRoles::default().surface, None);
1062    }
1063
1064    #[test]
1065    fn selection_and_error_roles_round_trip_and_default_to_none() {
1066        let d = ColorRoles::default();
1067        assert_eq!((d.selection, d.error, d.error_fill, d.on_error_fill), (None, None, None, None));
1068        let dark = ColorRoles {
1069            selection: Some(Rgb::hex(0x4fb3a4)),
1070            error: Some(Rgb::hex(0xff8f85)),
1071            error_fill: Some(Rgb::hex(0xc0392b)),
1072            on_error_fill: Some(Rgb::hex(0xffffff)),
1073            ..Default::default()
1074        };
1075        round_trips(&Theme { palette: Some(Palette { light: ColorRoles::default(), dark }), ..Default::default() });
1076    }
1077
1078    #[test]
1079    fn widget_round_trips() {
1080        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
1081        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
1082        round_trips(&Widget::Chart {
1083            series: vec![ChartSeries { name: "s".to_string(), values: vec![1.0, 2.5, 3.0], color: None, goal: None }],
1084            labels: vec!["a".to_string()],
1085            style: ChartStyle::Bar,
1086            axis: true,
1087            legend: false,
1088        });
1089        round_trips(&Widget::RegionChart {
1090            regions: vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical(),
1091                          ChartRegion::new(3.0, 21.0, 0.0, 80.0, "CHF 80'000").with_color(Rgb::new(0x8E, 0xC6, 0xBA))],
1092            ticks: vec![ChartTick { at: 3.0, label: "3 Mt.".to_string() }, ChartTick { at: 65.0, label: "65 J.".to_string() }],
1093            x_max: 65.0,
1094            y_max: 80.0,
1095            ref_lines: vec![ChartRefLine { value: 80.0, label: "CHF 80'000".to_string(), dashed: false }],
1096            bracket: Some(ChartBracket { y0: 60.0, y1: 80.0, label: "Ceiling".to_string(), info: true }),
1097            legend: vec![ChartLegendItem { label: "Gap".to_string(), color: Rgb::new(0x5A, 0x7D, 0x9A) }],
1098        });
1099        round_trips(&Widget::PdfView { url: "https://example.com/report.pdf".to_string() });
1100        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 });
1101        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 });
1102        round_trips(&Widget::WebView { url: "https://iframe.mediadelivery.net/embed/1/abc".to_string() });
1103        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 });
1104        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 });
1105        round_trips(&Widget::TextField { id: "email".to_string(), placeholder: "you@co".to_string(), value: "".to_string(), kind: FieldKind::Email, error: None });
1106        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()) });
1107        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] });
1108        round_trips(&Widget::SwipeAction { child: Box::new(Widget::Divider), actions: vec![SwipeButton { label: "Del".to_string(), tone: Tone::Danger, on_tap: "t".to_string() }] });
1109        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 });
1110        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: true, on_back: Some("back".to_string()) });
1111        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: false, on_back: None });
1112        round_trips(&Widget::Scroller { children: vec![Widget::Divider], edge_fade: true });
1113        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 });
1114        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 });
1115        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 });
1116        // Un-themed scaffold (theme: None) — the default, must round-trip.
1117        round_trips(&Widget::Scaffold {
1118            title: "T".to_string(),
1119            body: Box::new(Widget::Divider),
1120            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
1121            back: Some("b".to_string()),
1122            dark_mode: true,
1123            theme: None,
1124            fab: None,
1125            sheet: None,
1126            on_refresh: None,
1127            refreshing: false,
1128            route: "r".to_string(),
1129            depth: 2,
1130            labels: None,
1131            appearance: None,
1132            bottom_bar: None,
1133        });
1134        // Themed scaffold — all four theme knobs 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::Compact,
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: Some(vec![Widget::Divider]),
1158        });
1159        // Themed scaffold with Density::Large — the big-touch-target density 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: Some(Theme {
1167                seed: Rgb::new(0xC8, 0x5A, 0x3C),
1168                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
1169                corner: Corner::Large,
1170                density: Density::Large,
1171                font: FontFamily::Rounded,
1172                ..Default::default()
1173            }),
1174            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string(), label: None }),
1175            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
1176            on_refresh: Some("r".to_string()),
1177            refreshing: true,
1178            route: "r".to_string(),
1179            depth: 1,
1180            labels: None,
1181            appearance: None,
1182            bottom_bar: None,
1183        });
1184        // Labelled scaffold — every ShellLabels field must round-trip.
1185        round_trips(&Widget::Scaffold {
1186            title: "T".to_string(),
1187            body: Box::new(Widget::Divider),
1188            tabs: vec![],
1189            back: None,
1190            dark_mode: false,
1191            theme: None,
1192            fab: None,
1193            sheet: None,
1194            on_refresh: None,
1195            refreshing: false,
1196            route: "r".to_string(),
1197            depth: 1,
1198            labels: Some(
1199                ShellLabels::new()
1200                    .back("Nazad")
1201                    .load_more("Učitaj još")
1202                    .refresh("Osveži")
1203                    .ok("U redu")
1204                    .cancel("Otkaži")
1205                    .done("Gotovo")
1206                    .pdf_error("Greška")
1207                    .pdf_title("Dokument")
1208                    .web_title("Stranica"),
1209            ),
1210            appearance: Some(Appearance::System),
1211            bottom_bar: None,
1212        });
1213    }
1214}