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    /// A list of entries: a ledger, transactions, receipts.
282    Ledger,
283    /// A rising line chart: statistics, trends.
284    Chart,
285    /// A wallet: accounts, balances, net worth.
286    Wallet,
287    CreditCard,
288    Lock,
289    Download,
290    Upload,
291    /// A globe: language, region.
292    Globe,
293}
294
295#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
296#[repr(C)]
297pub enum ImageShape { Square, Rounded, Circle }
298
299#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
300#[repr(C)]
301pub enum ImageRatio { Wide, Square, Tall }
302
303#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
304#[repr(C)]
305pub enum BoxAlign { TopStart, TopEnd, Center, BottomStart, BottomCenter, BottomEnd }
306
307/// Project-identity colors (distinct from semantic `Tone`). Concrete RGB decided
308/// in the render layer.
309#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
310#[repr(C)]
311pub enum ProjectColor { Indigo, Teal, Coral, Amber, Lime, Pink }
312
313// ------------------------------- theme -------------------------------
314
315/// A 24-bit RGB color. Used for a theme's brand/seed color — the one place an app
316/// supplies an arbitrary color (everything else is intent tokens).
317#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
318#[repr(C)]
319pub struct Rgb {
320    pub r: u8,
321    pub g: u8,
322    pub b: u8,
323}
324
325impl Rgb {
326    pub const fn new(r: u8, g: u8, b: u8) -> Self {
327        Self { r, g, b }
328    }
329
330    /// `Rgb::hex(0x231f20)` — a colour from a 24-bit hex literal, as design tokens are written.
331    #[must_use]
332    pub const fn hex(v: u32) -> Self {
333        Self { r: ((v >> 16) & 0xff) as u8, g: ((v >> 8) & 0xff) as u8, b: (v & 0xff) as u8 }
334    }
335}
336
337/// Global corner-radius scale. `Medium` ≈ the current (un-themed) look.
338#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
339#[repr(C)]
340pub enum Corner { None, Small, Medium, Large }
341
342/// Global density. `Comfortable` ≈ the current (un-themed) look; `Compact` tightens spacing.
343/// `Large` is for hurried / wet / gloved hands: bigger controls (56 buttons & segmented, 48 chips
344/// & calendar days, 56 icon-button targets), 16 control labels, ≥ 12 between adjacent tappables.
345/// Body text stays on the platform's font-scale setting.
346#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
347#[repr(C)]
348pub enum Density { Compact, Comfortable, Large }
349
350/// A cross-platform font family. `System`/`Rounded`/`Serif`/`Monospace` map to each platform's
351/// nearest system font design. `Custom` = the app's `mobiler.toml` `[fonts]`, synced into the shells
352/// by the CLI (`mobiler fonts sync`, also run by build/dev): the display family for titles and
353/// subtitles, the body family for the rest; a role without files falls back to the system font.
354/// `System` ≈ the current look.
355#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
356#[repr(C)]
357pub enum FontFamily { System, Rounded, Serif, Monospace, Custom }
358
359/// App branding as data — the visual twin of `dark_mode`. Set on a [`Widget::Scaffold`]
360/// (`theme: None` = the framework defaults, i.e. no visual change). The shell maps these
361/// to its native theming: `seed` → the brand/primary color (Android M3 scheme / iOS tint /
362/// web `--primary`), plus a global corner, spacing, and font choice.
363///
364/// **Breaking in mobiler-ui 0.29 / mobiler-core 0.40:** `Theme` gained `palette` (and further
365/// design-release fields follow). Code that lists every field in a `Theme { … }` literal no longer
366/// compiles. Write `Theme { seed, ..Default::default() }` and set only what you need.
367#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
368#[repr(C)]
369pub struct Theme {
370    pub seed: Rgb,
371    /// Optional secondary brand color. `None` ⇒ derived from `seed`. Used for the
372    /// gradient on `CardStyle::Brand` (seed → accent) and as a secondary accent.
373    pub accent: Option<Rgb>,
374    pub corner: Corner,
375    pub density: Density,
376    pub font: FontFamily,
377    /// Explicit colour roles for light and dark (`dark_mode` picks the set). `None` = the shell's
378    /// own colours, exactly as before; a role left `None` inside a set keeps the shell's colour too.
379    pub palette: Option<Palette>,
380    /// Per-style size, weight and font role (see [`TypeScale`]). `None`, or a style left `None`, keeps
381    /// the shell's current look for that style.
382    pub type_scale: Option<TypeScale>,
383    /// Per-component corner radii (see [`Shapes`]). `None`, or a component left `None`, keeps the
384    /// shell's current shape for it.
385    pub shapes: Option<Shapes>,
386}
387
388/// `Theme::default()` matches the framework's un-themed look as closely as a theme can
389/// (medium corners, comfortable spacing, system font) with a neutral indigo seed — so an
390/// app can override just the bits it cares about: `Theme { seed: brand, ..Default::default() }`.
391impl Default for Theme {
392    fn default() -> Self {
393        Theme {
394            seed: Rgb::new(0x5C, 0x6B, 0xC0), // indigo — matches the legacy default accent
395            accent: None,
396            corner: Corner::Medium,
397            density: Density::Comfortable,
398            font: FontFamily::System,
399            palette: None,
400            type_scale: None,
401            shapes: None,
402        }
403    }
404}
405
406/// A corner radius per component. `sheet_top` rounds only the bottom sheet's top corners (`Pill` there
407/// is capped at 32 — a dome would clip the sheet's content). `button` also shapes the confirm dialog's
408/// buttons where the shell draws them (web, Android); iOS uses the system alert.
409#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
410#[repr(C)]
411pub struct Shapes {
412    /// Every card style, including tappable cards.
413    pub card: Option<Radius>,
414    /// Every button style, including toned and `Density::Large` buttons.
415    pub button: Option<Radius>,
416    pub fab: Option<Radius>,
417    pub sheet_top: Option<Radius>,
418    pub chip: Option<Radius>,
419    pub badge: Option<Radius>,
420    /// Text and search fields.
421    pub input: Option<Radius>,
422}
423
424/// A corner radius: `Dp(n)` (dp/pt/px), or `Pill` — fully round (half the component's height), at
425/// any density.
426#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
427#[repr(C)]
428pub enum Radius {
429    Dp(u8),
430    Pill,
431}
432
433/// The app's type scale: one optional [`TypeSpec`] per text style. `title` also sets the scaffold's
434/// top-bar title and `headline` the sheet titles. Sizes are sp/pt/px and still follow the platform's
435/// text-size accessibility setting.
436#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
437#[repr(C)]
438pub struct TypeScale {
439    pub display: Option<TypeSpec>,
440    pub headline: Option<TypeSpec>,
441    pub title: Option<TypeSpec>,
442    pub subtitle: Option<TypeSpec>,
443    pub body: Option<TypeSpec>,
444    pub emphasis: Option<TypeSpec>,
445    pub caption: Option<TypeSpec>,
446}
447
448/// One style's size (sp/pt/px), weight (100..=900, rounded to the nearest 100) and font role.
449#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
450#[repr(C)]
451pub struct TypeSpec {
452    pub size: u8,
453    pub weight: u16,
454    pub family: FamilyRole,
455}
456
457impl TypeSpec {
458    #[must_use]
459    pub const fn new(size: u8, weight: u16, family: FamilyRole) -> Self {
460        Self { size, weight, family }
461    }
462}
463
464/// Which synced font a [`TypeSpec`] uses under `FontFamily::Custom` (otherwise the theme's system font).
465#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
466#[repr(C)]
467pub enum FamilyRole { Display, Body }
468
469/// A light and a dark set of colour roles — the design's tokens. See [`ColorRoles`].
470#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
471#[repr(C)]
472pub struct Palette {
473    pub light: ColorRoles,
474    pub dark: ColorRoles,
475}
476
477/// Colour roles; every one optional (`None` = the shell's current colour for that role).
478#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
479#[repr(C)]
480pub struct ColorRoles {
481    /// Page background.
482    pub background: Option<Rgb>,
483    /// Cards, sheets, dialogs.
484    pub surface: Option<Rgb>,
485    /// Top bar, bottom navigation, navigation rail.
486    pub surface_bar: Option<Rgb>,
487    /// Chips, input fills, segmented track, Filled cards, skeletons, the Neutral tone.
488    pub surface_muted: Option<Rgb>,
489    /// Text and icons.
490    pub on_surface: Option<Rgb>,
491    /// Secondary text (captions, unselected tabs).
492    pub on_surface_variant: Option<Rgb>,
493    /// Field and outlined-button borders.
494    pub outline: Option<Rgb>,
495    /// Hairlines and dividers.
496    pub outline_variant: Option<Rgb>,
497    /// Filled buttons, selected calendar day, toggles (unless `selection` is set).
498    pub primary: Option<Rgb>,
499    pub on_primary: Option<Rgb>,
500    /// Primary-coloured text/icons on the background (text buttons, selected tab, back button).
501    pub primary_text: Option<Rgb>,
502    /// Tonal buttons, selected segment/chip, navigation indicator.
503    pub secondary_container: Option<Rgb>,
504    pub on_secondary_container: Option<Rgb>,
505    pub fab: Option<Rgb>,
506    pub on_fab: Option<Rgb>,
507    /// One container/on-container pair per [`Tone`]. Filled toned buttons swap the pair (Danger: unless
508    /// `error_fill` is set).
509    pub success: Option<TonePair>,
510    pub warning: Option<TonePair>,
511    pub danger: Option<TonePair>,
512    pub info: Option<TonePair>,
513    /// Sheet and dialog scrim.
514    pub scrim: Option<Rgba>,
515    /// Focus and selection marks: the focused field's border, label and cursor, checked toggles and
516    /// checkboxes, sliders, progress. Unset: the shell's current colour (`primary` on most shells).
517    pub selection: Option<Rgb>,
518    /// Error text and the invalid field's border; outlined and text Danger buttons. Unset: `danger`'s
519    /// on-container colour, as before.
520    pub error: Option<Rgb>,
521    /// A filled Danger button's background. Unset: the `danger` pair, swapped, as before.
522    pub error_fill: Option<Rgb>,
523    /// A filled Danger button's text. Unset: as before.
524    pub on_error_fill: Option<Rgb>,
525    /// An outlined button's background (alpha allowed: a soft tint). Unset: transparent, as before.
526    pub outlined_fill: Option<Rgba>,
527    /// An outlined button's border (alpha allowed). Unset: `outline`, as before.
528    pub outlined_border: Option<Rgba>,
529    /// The selected segment's fill, apart from chips and tonal buttons. Unset: `secondary_container`,
530    /// as before.
531    pub segment_selected: Option<Rgb>,
532    /// The selected segment's text and check mark. Unset: `on_secondary_container`, as before.
533    pub on_segment_selected: Option<Rgb>,
534}
535
536/// A tone's soft background and its foreground.
537#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
538#[repr(C)]
539pub struct TonePair {
540    pub container: Rgb,
541    pub on_container: Rgb,
542}
543
544impl TonePair {
545    #[must_use]
546    pub const fn new(container: Rgb, on_container: Rgb) -> Self {
547        Self { container, on_container }
548    }
549}
550
551/// A colour with alpha (`a`: 0 = transparent, 255 = opaque).
552#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
553#[repr(C)]
554pub struct Rgba {
555    pub r: u8,
556    pub g: u8,
557    pub b: u8,
558    pub a: u8,
559}
560
561impl Rgba {
562    #[must_use]
563    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
564        Self { r, g, b, a }
565    }
566}
567
568/// How the scaffold picks light or dark. `Light`/`Dark` force it; `System` follows the OS live (the
569/// shell switches palette sets itself, no core round-trip). Set with `with_appearance`.
570#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
571#[repr(C)]
572pub enum Appearance { Light, Dark, System }
573
574/// Text the shells draw themselves (back buttons, web list controls, dialog/picker defaults), in the
575/// app's language. Set once on the scaffold with `with_labels`; every field is optional and falls
576/// back to the shell's built-in English. A label passed to a specific call (`confirm_with`,
577/// `Picker`) still wins over these.
578#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
579#[repr(C)]
580pub struct ShellLabels {
581    /// `Split` back-button text on every shell; the Scaffold back button's accessible name.
582    pub back: Option<String>,
583    /// Web `LazyList` "Load more" button.
584    pub load_more: Option<String>,
585    /// Web `LazyList` refresh button (shown after a ↻) and the web scaffold refresh button's name.
586    pub refresh: Option<String>,
587    /// Confirm dialog: the confirming button when the call gives no label.
588    pub ok: Option<String>,
589    /// Confirm dialog and pickers: the dismissing button when the call gives no label.
590    pub cancel: Option<String>,
591    /// Pickers: the accepting button when the call gives no label.
592    pub done: Option<String>,
593    /// Android PdfView error text.
594    pub pdf_error: Option<String>,
595    /// Web PDF iframe title (accessibility).
596    pub pdf_title: Option<String>,
597    /// Web WebView iframe title (accessibility).
598    pub web_title: Option<String>,
599    /// The step indicator's spoken text ([`Widget::Steps`]), with `{current}` / `{total}`
600    /// placeholders: `"Korak {current} od {total}"`. Default `"Step {current} of {total}"`.
601    pub step_of: Option<String>,
602}
603
604impl ShellLabels {
605    #[must_use]
606    pub fn new() -> Self {
607        Self::default()
608    }
609    #[must_use]
610    pub fn back(mut self, l: impl Into<String>) -> Self {
611        self.back = Some(l.into());
612        self
613    }
614    #[must_use]
615    pub fn load_more(mut self, l: impl Into<String>) -> Self {
616        self.load_more = Some(l.into());
617        self
618    }
619    #[must_use]
620    pub fn refresh(mut self, l: impl Into<String>) -> Self {
621        self.refresh = Some(l.into());
622        self
623    }
624    #[must_use]
625    pub fn ok(mut self, l: impl Into<String>) -> Self {
626        self.ok = Some(l.into());
627        self
628    }
629    #[must_use]
630    pub fn cancel(mut self, l: impl Into<String>) -> Self {
631        self.cancel = Some(l.into());
632        self
633    }
634    #[must_use]
635    pub fn done(mut self, l: impl Into<String>) -> Self {
636        self.done = Some(l.into());
637        self
638    }
639    #[must_use]
640    pub fn pdf_error(mut self, l: impl Into<String>) -> Self {
641        self.pdf_error = Some(l.into());
642        self
643    }
644    #[must_use]
645    pub fn pdf_title(mut self, l: impl Into<String>) -> Self {
646        self.pdf_title = Some(l.into());
647        self
648    }
649    #[must_use]
650    pub fn web_title(mut self, l: impl Into<String>) -> Self {
651        self.web_title = Some(l.into());
652        self
653    }
654    #[must_use]
655    pub fn step_of(mut self, l: impl Into<String>) -> Self {
656        self.step_of = Some(l.into());
657        self
658    }
659}
660
661/// A bottom-navigation tab. `selected` marks the active one; tapping sends
662/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
663#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
664#[repr(C)]
665pub struct Tab {
666    pub label: String,
667    pub selected: bool,
668    pub on_select: ActionToken,
669    /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
670    pub icon: Option<Icon>,
671    /// A dot or short count on the tab (ADR-0050). `None` = no badge. BREAKING (tab badge release): `Tab { .. }`
672    /// literals need this field; `tab` / `tab_icon` set `None`, and `with_tab_dot` / `with_tab_count` set it.
673    pub badge: Option<TabBadge>,
674}
675
676/// A tab's badge (ADR-0050). Both strings are finished by the core: the shells draw `text` as-is and add no words.
677#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
678#[repr(C)]
679pub struct TabBadge {
680    /// Drawn inside the badge. Empty = a small dot with no text.
681    pub text: String,
682    /// What a screen reader says after the tab's label, e.g. "3 nove poruke". Empty = it reads `text`.
683    pub label: String,
684}
685
686/// A floating action button anchored over the scaffold body (the raised primary action).
687#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
688#[repr(C)]
689pub struct Fab {
690    pub icon: Icon,
691    pub on_press: ActionToken,
692    /// Extended FAB: the label shown next to the icon, which is also its accessible name. `None` = the
693    /// round FAB. BREAKING (Moj Termin design release): `Fab { .. }` literals need this field; the
694    /// `with_fab` / `with_extended_fab` builders are unaffected.
695    pub label: Option<String>,
696}
697
698/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
699/// active segment; tapping sends `on_select`.
700#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
701#[repr(C)]
702pub struct Segment {
703    pub label: String,
704    pub selected: bool,
705    pub on_select: ActionToken,
706}
707
708/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
709/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
710#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
711#[repr(C)]
712pub struct Sheet {
713    pub title: String,
714    pub child: Box<Widget>,
715    pub on_dismiss: ActionToken,
716}
717
718/// One revealed action in a `SwipeAction` row (swipe to reveal, tap to fire).
719#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
720#[repr(C)]
721pub struct SwipeButton {
722    pub label: String,
723    pub tone: Tone,
724    pub on_tap: ActionToken,
725}
726
727/// One subtitle/caption track for a [`Widget::Video`]. `url` points at a WebVTT (`.vtt`) file,
728/// `language` is a BCP-47 tag (e.g. `"en"`), `label` is the human-readable menu entry, and
729/// `default_on` selects it by default. Sidecar tracks work on web (`<track>`) and Android
730/// (Media3 subtitle configuration); on iOS only captions already embedded in an HLS manifest are
731/// selectable (AVPlayer can't attach a sidecar VTT to an MP4 — a documented v1 gap).
732#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
733#[repr(C)]
734pub struct Caption {
735    pub url: String,
736    pub label: String,
737    pub language: String,
738    pub default_on: bool,
739}
740
741/// A pin on a [`Widget::Map`]. `id` is echoed back when the marker is tapped
742/// (`Action::Input { id: "{map_id}.marker", value: Text(marker.id) }`).
743#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
744#[repr(C)]
745pub struct MapMarker {
746    pub id: String,
747    pub lat: f64,
748    pub lng: f64,
749    pub title: Option<String>,
750}
751
752// ------------------------------- widgets -------------------------------
753
754/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
755// `Scaffold`'s `ShellLabels` (nine `Option<String>` fields) makes it the largest variant by a wide
756// margin; boxing it would ripple through every `with_labels`/scaffold call site for no runtime
757// benefit on a wire type that is rebuilt per-render, not stored in bulk.
758#[allow(clippy::large_enum_variant)]
759#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
760#[repr(C)]
761pub enum Widget {
762    // Content
763    Text { content: String, style: TextStyle },
764    Image { source: String, shape: ImageShape, ratio: ImageRatio },
765    /// A status pill. `icon` (before the label, decorative) makes the status readable without its
766    /// colour. BREAKING (Moj Termin design release): `icon` was added — exhaustive patterns and full
767    /// literals need it; `badge` / `with_icon` are unaffected.
768    Badge { label: String, tone: Tone, icon: Option<Icon> },
769    /// A circular avatar image with an optional colored status dot. `initials` (at most two
770    /// characters) are drawn when `source` is empty or fails to load; `size` is the diameter
771    /// (`None` = 48). BREAKING (Moj Termin design release): `initials` and `size` were added.
772    Avatar { source: String, status: Option<Tone>, initials: Option<String>, size: Option<u8> },
773    /// An in-app PDF viewer showing the document at `url` (a remote https URL or a local
774    /// file URI). Each shell uses its native renderer — PDFKit on iOS, a paged `PdfRenderer`
775    /// on Android, an `<iframe>` on web — so the app only supplies the URL (e.g. a
776    /// backend-generated report). Fills its width; give it room (place in a sized container).
777    PdfView { url: String },
778    /// An in-app native video player for the stream/file at `url` (MP4 everywhere; HLS `.m3u8` on
779    /// iOS/Android natively + Safari on web; or a local file URI). Native player per shell — AVPlayer
780    /// (iOS), Media3/ExoPlayer (Android), a `<video>` element (web). **Controllable:** `playing` drives
781    /// play/pause (app-owned, like a `Toggle`); set `seek_to_ms` to jump (the shell seeks when the value
782    /// CHANGES; `-1` = no seek). The shell reports the current position ~once/second via
783    /// `Action::Input { id, value: Int(position_ms) }` (handle it in [`MobilerApp::input`]), and fires
784    /// `on_ended` when the clip finishes. `controls` shows the native transport bar; `looping` restarts
785    /// on end; `muted` starts muted (needed for reliable autoplay). Fills its width; give it room.
786    ///
787    /// v2 fields: `poster` shows a thumbnail image before the first play; `start_at_ms` resumes at an
788    /// offset (applied once on load, `-1` = start). `captions` adds subtitle tracks (see [`Caption`]).
789    /// `rate` sets playback speed (`1.0` = normal) and `volume` the level (`0.0`–`1.0`). For a playlist,
790    /// set `urls` (non-empty takes precedence over `url`) with `start_index`; the shell auto-advances
791    /// and reports the current track ~as it changes via `Action::Input { id: "{id}.index", … }`, and
792    /// `seek_index` jumps to a track when it CHANGES (`-1` = none). The shell also reports
793    /// `"{id}.duration"`, `"{id}.state"` (0 idle / 1 buffering / 2 ready-paused / 3 playing / 4 ended)
794    /// and `"{id}.buffered"` via the same `Input` path (handle them in [`MobilerApp::input`]). Set
795    /// `allow_pip` to enable Picture-in-Picture (the shell adds a PiP affordance).
796    Video {
797        url: String,
798        id: String,
799        playing: bool,
800        seek_to_ms: i64,
801        controls: bool,
802        looping: bool,
803        muted: bool,
804        on_ended: Option<ActionToken>,
805        poster: Option<String>,
806        start_at_ms: i64,
807        captions: Vec<Caption>,
808        rate: f32,
809        volume: f32,
810        urls: Vec<String>,
811        start_index: i64,
812        seek_index: i64,
813        allow_pip: bool,
814    },
815    /// Displays the web page / embedded player at `url` in a native web view — `WKWebView` on iOS,
816    /// `android.webkit.WebView` on Android, an `<iframe>` on web. General-purpose: docs, dashboards,
817    /// or a hosted player embed (e.g. a Bunny.net / YouTube embed URL, which brings its own
818    /// captions/quality/thumbnails). JavaScript and inline media autoplay are enabled so hosted
819    /// players work. This is NOT the default way to play video — use [`Widget::Video`] for a
820    /// controllable native player. Fills its width; give it room (place in a sized container).
821    WebView { url: String },
822    /// An interactive map (a "live native view" like [`Widget::Video`]): iOS MapKit, Android MapLibre
823    /// Native, web MapLibre-GL — no API key. The app drives the camera (`center_lat`/`center_lng`/`zoom`)
824    /// and `markers`; the user pans/zooms when `interactive`. Taps report back via `Action::Input`:
825    /// a map tap → `{ id: "{id}.tap", value: Text("lat,lng") }`, a marker tap → `{ id: "{id}.marker",
826    /// value: Text(marker.id) }` (handle in [`MobilerApp::input`] by id-suffix). `style_url` selects the
827    /// MapLibre vector style on Android/web (None → a free default); iOS MapKit uses Apple Maps and
828    /// ignores it. Fills its width; give it a height (place in a sized container).
829    Map {
830        id: String,
831        center_lat: f64,
832        center_lng: f64,
833        zoom: f64,
834        markers: Vec<MapMarker>,
835        style_url: Option<String>,
836        interactive: bool,
837    },
838    /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
839    /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
840    Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
841    /// Small non-interactive colored dot — a project/identity hint.
842    ColorDot { color: ProjectColor },
843    Divider,
844    /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
845    Progress { value: Option<f32> },
846    /// Shimmer placeholder shown while content loads.
847    Skeleton,
848    /// A data chart drawing one or more named `series` in the given `style` (see [`ChartStyle`]).
849    /// `labels` (optional) annotate the x-axis for cartesian styles. `axis` shows y gridlines +
850    /// tick values (cartesian only); `legend` shows a series swatch+name row. Non-interactive.
851    Chart { series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool },
852    /// A variable-width stacked-region ("Marimekko" / coverage-gap) chart: `regions` are arbitrary
853    /// colored rectangles in the `[0, x_max] × [0, y_max]` plane (each with an in-cell label),
854    /// `ticks` annotate the irregular x-axis, `ref_lines` are horizontal target/max lines with
855    /// right-edge chips, `bracket` is an optional right-side range annotation, and `legend` names
856    /// the colors. The app supplies all geometry; shells map domain→pixels. Non-interactive.
857    RegionChart {
858        regions: Vec<ChartRegion>,
859        ticks: Vec<ChartTick>,
860        x_max: f32,
861        y_max: f32,
862        ref_lines: Vec<ChartRefLine>,
863        bracket: Option<ChartBracket>,
864        legend: Vec<ChartLegendItem>,
865    },
866    /// An inline month calendar. The core pre-computes everything locale-dependent so shells only
867    /// draw: `title` (e.g. "Septembar 2026"), the 7 `weekday_labels` in column order (week start
868    /// first), and `leading_blanks` (empty cells before day 1). `on_day[d-1]` fires when day `d` is
869    /// tapped (length = days in the month); `selected` highlights a day. `markers` is empty (no
870    /// markers) or one level per day, `0..=3`, drawn as that many small dots under the day number.
871    Calendar {
872        year: u32,
873        month: u8,
874        title: String,
875        weekday_labels: Vec<String>,
876        leading_blanks: u8,
877        selected: Option<u8>,
878        on_day: Vec<ActionToken>,
879        markers: Vec<u8>,
880    },
881    /// A list row that reveals trailing `actions` on horizontal swipe (each tappable). On web the
882    /// actions render inline as a trailing button row (no gesture).
883    SwipeAction { child: Box<Widget>, actions: Vec<SwipeButton> },
884    /// A scrollable list for long/paged feeds, with shell-detected events at both ends: the bottom
885    /// `on_load_more` fires when the user scrolls near the end (infinite scroll), the top
886    /// `on_refresh` fires on pull-to-refresh. `loading`/`refreshing`/`has_more` are app-owned: set
887    /// `loading` while a page loads (shell shows a spinner, stops firing), `has_more=false` when
888    /// exhausted, and `refreshing` while a pull-refresh runs. The app appends to `children` on each
889    /// load-more. `on_refresh` is set via [`with_refresh`](mobiler_core::with_refresh).
890    LazyList {
891        children: Vec<Widget>,
892        on_load_more: Option<ActionToken>,
893        loading: bool,
894        has_more: bool,
895        on_refresh: Option<ActionToken>,
896        refreshing: bool,
897        /// Text shown under an exhausted paged list (`has_more == false` with `on_load_more` set),
898        /// e.g. "You're all caught up" in the app's language. `None` shows nothing. Set with
899        /// `with_end_label`.
900        end_label: Option<String>,
901        /// Fill the rest of the screen instead of the fixed height, when this list is the scaffold
902        /// body or a direct child of the body's column (the first one). Set with `with_fill`.
903        fill: bool,
904    },
905    Spacer { size: Spacing },
906    // Layout
907    Row { children: Vec<Widget> },
908    Column { children: Vec<Widget> },
909    /// Card; tappable when `on_press` is set. Fires `on_long_press` (when set) on a
910    /// press-and-hold (web: a ~500 ms pointer-hold; iOS: `onLongPressGesture`;
911    /// Android: `combinedClickable`'s `onLongClick`).
912    Card {
913        child: Box<Widget>,
914        style: CardStyle,
915        on_press: Option<ActionToken>,
916        on_long_press: Option<ActionToken>,
917    },
918    /// Z-stack: children layered back-to-front, positioned by `align`. With
919    /// `scrim`, the first child is a background image, darkened for legibility,
920    /// and the rest render on top in light content.
921    Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
922    /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
923    /// `columns`: exactly that many equal columns (1–4) at every width; `None` = the adaptive grid
924    /// (2 on a phone, more on a tablet). BREAKING (Moj Termin design release): `columns` was added.
925    Grid { children: Vec<Widget>, columns: Option<u8> },
926    /// Horizontally scrolling row. `edge_fade` fades the trailing edge (plus trailing room so the
927    /// last item clears the fade at scroll-end) to hint there is more to scroll.
928    Scroller { children: Vec<Widget>, edge_fade: bool },
929    /// Two-pane master-detail. On a **wide** screen (tablet / landscape — the shell's regular size
930    /// class) `primary` and `detail` render side-by-side; on a **compact** screen (phone) it shows
931    /// ONE pane: `primary` until `show_detail` is set (the app sets it when a row is selected), then
932    /// `detail` with a back chevron that fires `on_back` (the app clears its selection). On wide,
933    /// `show_detail`/`on_back` are ignored — both panes stay visible, so `detail` should show a
934    /// placeholder until something is selected.
935    Split { primary: Box<Widget>, detail: Box<Widget>, show_detail: bool, on_back: Option<ActionToken> },
936    /// Accessibility wrapper: presents `child`'s subtree as ONE screen-reader element named by `label`
937    /// (so an unlabeled IconButton/Image gets a name, or a Card's children group into one announced
938    /// element). `hint` describes what activation does; `role` is the control type. Shell-applied:
939    /// iOS accessibilityLabel/Hint/Traits, Android contentDescription/role/heading, web aria-label/role.
940    A11y { child: Box<Widget>, label: String, hint: Option<String>, role: Option<A11yRole> },
941    // Input
942    /// A tappable button. `tone` recolors it (`Neutral` = the brand/primary look; `Danger` = the
943    /// error color pair for destructive actions). `icon` draws a leading glyph; `wide` stretches it
944    /// to the available width.
945    Button { label: String, style: ButtonStyle, on_press: ActionToken, tone: Tone, icon: Option<Icon>, wide: bool },
946    IconButton { icon: Icon, on_press: ActionToken },
947    Chip { label: String, selected: bool, on_press: ActionToken },
948    /// A text input. `kind` selects keyboard / secure entry / multiline
949    /// (see [`FieldKind`]); `error`, when `Some`, shows an inline validation
950    /// message below the field and marks it invalid. Emits `Input { id, Text }`.
951    TextField { id: String, placeholder: String, value: String, kind: FieldKind, error: Option<String> },
952    /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
953    SearchField { id: String, placeholder: String, value: String },
954    /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
955    Segmented { segments: Vec<Segment> },
956    Toggle { id: String, label: String, value: bool },
957    Checkbox { id: String, label: String, value: bool },
958    /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
959    Slider { id: String, value: i32, max: i32 },
960    /// Numeric stepper with −/+ controls carrying their own events.
961    Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
962    /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
963    /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
964    /// the whole app from it.
965    ///
966    /// `route` + `depth` drive navigation: the shell animates the body when
967    /// `route` (the current screen's identity) changes — slide for push/pop
968    /// (direction from whether `depth` grew or shrank), crossfade for a lateral
969    /// move at the same depth — and wires the system back button to `back`.
970    Scaffold {
971        title: String,
972        body: Box<Widget>,
973        tabs: Vec<Tab>,
974        back: Option<ActionToken>,
975        dark_mode: bool,
976        /// App branding (brand color, corner, density, font). `None` = framework
977        /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
978        theme: Option<Theme>,
979        /// Optional floating action button (raised primary action over the body).
980        fab: Option<Fab>,
981        /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
982        sheet: Option<Sheet>,
983        /// Pull-to-refresh: when set, the body is pull-refreshable and fires this event on pull.
984        /// The app owns `refreshing` — set it true when the pull fires, clear it when the async
985        /// reload completes (the shell shows a spinner while it's true).
986        on_refresh: Option<ActionToken>,
987        refreshing: bool,
988        route: String,
989        depth: u32,
990        /// App-wide shell text (see [`ShellLabels`]). `None` ⇒ the shells' English defaults.
991        labels: Option<ShellLabels>,
992        /// `Some` overrides `dark_mode` (see [`Appearance`]); `None` = `dark_mode` decides.
993        appearance: Option<Appearance>,
994        /// A screen's main actions pinned above the tabs and the system navigation (equal-width
995        /// row); the body ends above it. `None` / empty = no bar. BREAKING (Moj Termin design
996        /// release): appended — full `Scaffold` literals and patterns need it.
997        bottom_bar: Option<Vec<Widget>>,
998        /// iOS only: a floating Liquid Glass tab bar (iOS 26; a frosted capsule below) and a glass FAB.
999        /// Android and the web keep the standard bar (ADR-0059). BREAKING (mobiler-ui 0.33): appended —
1000        /// full `Scaffold` literals and patterns need it.
1001        ios_glass_tabs: bool,
1002    },
1003    /// A step indicator for a multi-step flow: `total` equal segments, the first `current` filled.
1004    /// Spoken as one element, "Step 2 of 3" (or [`ShellLabels::step_of`]), never as a percentage.
1005    /// `caption` also shows that text above the bar, still as the same single element.
1006    Steps { total: u8, current: u8, caption: bool },
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::*;
1012    use serde::Serialize;
1013    use serde::de::DeserializeOwned;
1014
1015    // Round-trips the ABI without requiring `PartialEq` on the wire types:
1016    // serialize → deserialize → re-serialize, and compare the two encodings.
1017    fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
1018        let a = serde_json::to_string(value).expect("serialize");
1019        let back: T = serde_json::from_str(&a).expect("deserialize");
1020        let b = serde_json::to_string(&back).expect("re-serialize");
1021        assert_eq!(a, b);
1022    }
1023
1024    #[test]
1025    fn action_round_trips() {
1026        round_trips(&Action::Start);
1027        round_trips(&Action::Fired { token: "tok".to_string() });
1028        round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
1029        round_trips(&Action::Restore { data: "{}".to_string() });
1030        round_trips(&Action::AppInfo {
1031            version: "1.0".to_string(),
1032            build: "7".to_string(),
1033            platform: "ios".to_string(),
1034            bundle_id: "rs.x".to_string(),
1035        });
1036    }
1037
1038    #[test]
1039    fn steps_round_trip() {
1040        round_trips(&Widget::Steps { total: 3, current: 2, caption: true });
1041    }
1042
1043    #[test]
1044    fn grid_columns_and_dashed_card_round_trip() {
1045        round_trips(&Widget::Grid { children: vec![], columns: Some(3) });
1046        round_trips(&Widget::Card { child: Box::new(Widget::Spacer { size: Spacing::Md }), style: CardStyle::Dashed, on_press: None, on_long_press: None });
1047    }
1048
1049    #[test]
1050    fn badge_icon_and_avatar_initials_round_trip() {
1051        round_trips(&Widget::Badge { label: "Finished".into(), tone: Tone::Info, icon: Some(Icon::DoneAll) });
1052        round_trips(&Widget::Avatar { source: String::new(), status: None, initials: Some("MJ".into()), size: Some(40) });
1053    }
1054
1055    #[test]
1056    fn extended_fab_round_trips() {
1057        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: Some("Novi termin".into()) });
1058        round_trips(&Fab { icon: Icon::Add, on_press: "\"New\"".into(), label: None });
1059    }
1060
1061    #[test]
1062    fn tab_badge_round_trips() {
1063        let tab = |badge| Tab { label: "Nalog".into(), selected: false, on_select: "\"Account\"".into(), icon: Some(Icon::Person), badge };
1064        round_trips(&tab(Some(TabBadge { text: String::new(), label: "Nove poruke".into() })));
1065        round_trips(&tab(Some(TabBadge { text: "99+".into(), label: "Više od 99 novih poruka".into() })));
1066        round_trips(&tab(None));
1067    }
1068
1069    #[test]
1070    fn shapes_round_trip() {
1071        let shapes = Shapes { card: Some(Radius::Dp(12)), button: Some(Radius::Pill), ..Default::default() };
1072        round_trips(&Theme { shapes: Some(shapes), ..Default::default() });
1073        assert_eq!(Theme::default().shapes, None);
1074    }
1075
1076    #[test]
1077    fn type_scale_and_new_styles_round_trip() {
1078        let ts = TypeScale { display: Some(TypeSpec::new(36, 700, FamilyRole::Display)), ..Default::default() };
1079        round_trips(&Theme { type_scale: Some(ts), ..Default::default() });
1080        round_trips(&Widget::Text { content: "12:00".to_string(), style: TextStyle::Display });
1081        round_trips(&Widget::Text { content: "Booking".to_string(), style: TextStyle::Headline });
1082        assert_eq!(Theme::default().type_scale, None);
1083    }
1084
1085    #[test]
1086    fn custom_font_family_round_trips() {
1087        round_trips(&Theme { font: FontFamily::Custom, ..Default::default() });
1088    }
1089
1090    #[test]
1091    fn rgb_hex_splits_channels() {
1092        assert_eq!(Rgb::hex(0x231f20), Rgb::new(0x23, 0x1f, 0x20));
1093        assert_eq!(Rgb::hex(0xffffff), Rgb::new(255, 255, 255));
1094    }
1095
1096    #[test]
1097    fn theme_default_has_no_palette_and_palette_round_trips() {
1098        assert_eq!(Theme::default().palette, None);
1099        let dark = ColorRoles {
1100            background: Some(Rgb::hex(0x231f20)),
1101            danger: Some(TonePair::new(Rgb::hex(0x4d2626), Rgb::hex(0xffb4ab))),
1102            scrim: Some(Rgba::new(0, 0, 0, 82)),
1103            ..Default::default()
1104        };
1105        let theme = Theme { palette: Some(Palette { light: ColorRoles::default(), dark }), ..Default::default() };
1106        round_trips(&theme);
1107        assert_eq!(ColorRoles::default().surface, None);
1108    }
1109
1110    #[test]
1111    fn selection_and_error_roles_round_trip_and_default_to_none() {
1112        let d = ColorRoles::default();
1113        assert_eq!((d.selection, d.error, d.error_fill, d.on_error_fill), (None, None, None, None));
1114        let dark = ColorRoles {
1115            selection: Some(Rgb::hex(0x4fb3a4)),
1116            error: Some(Rgb::hex(0xff8f85)),
1117            error_fill: Some(Rgb::hex(0xc0392b)),
1118            on_error_fill: Some(Rgb::hex(0xffffff)),
1119            ..Default::default()
1120        };
1121        round_trips(&Theme { palette: Some(Palette { light: ColorRoles::default(), dark }), ..Default::default() });
1122    }
1123
1124    #[test]
1125    fn button_and_segment_roles_round_trip_and_default_to_none() {
1126        let d = ColorRoles::default();
1127        assert_eq!((d.outlined_fill, d.outlined_border, d.segment_selected, d.on_segment_selected), (None, None, None, None));
1128        let light = ColorRoles {
1129            outlined_fill: Some(Rgba { r: 14, g: 159, b: 142, a: 26 }),
1130            outlined_border: Some(Rgba { r: 14, g: 159, b: 142, a: 115 }),
1131            segment_selected: Some(Rgb::hex(0x0e9f8e)),
1132            on_segment_selected: Some(Rgb::hex(0xffffff)),
1133            ..Default::default()
1134        };
1135        round_trips(&Theme { palette: Some(Palette { light, dark: ColorRoles::default() }), ..Default::default() });
1136    }
1137
1138    #[test]
1139    fn new_icons_and_the_ios_glass_tabs_flag_round_trip() {
1140        for icon in [Icon::Ledger, Icon::Chart, Icon::Wallet, Icon::CreditCard, Icon::Lock, Icon::Download, Icon::Upload, Icon::Globe] {
1141            round_trips(&Widget::Badge { label: "x".into(), tone: Tone::Info, icon: Some(icon) });
1142        }
1143        round_trips(&Widget::Scaffold {
1144            title: "t".into(),
1145            body: Box::new(Widget::Text { content: "b".into(), style: TextStyle::Body }),
1146            tabs: vec![],
1147            back: None,
1148            dark_mode: false,
1149            theme: None,
1150            fab: None,
1151            sheet: None,
1152            on_refresh: None,
1153            refreshing: false,
1154            route: "r".into(),
1155            depth: 1,
1156            labels: None,
1157            appearance: None,
1158            bottom_bar: None,
1159            ios_glass_tabs: true,
1160        });
1161    }
1162
1163    #[test]
1164    fn widget_round_trips() {
1165        round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
1166        round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
1167        round_trips(&Widget::Chart {
1168            series: vec![ChartSeries { name: "s".to_string(), values: vec![1.0, 2.5, 3.0], color: None, goal: None }],
1169            labels: vec!["a".to_string()],
1170            style: ChartStyle::Bar,
1171            axis: true,
1172            legend: false,
1173        });
1174        round_trips(&Widget::RegionChart {
1175            regions: vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical(),
1176                          ChartRegion::new(3.0, 21.0, 0.0, 80.0, "CHF 80'000").with_color(Rgb::new(0x8E, 0xC6, 0xBA))],
1177            ticks: vec![ChartTick { at: 3.0, label: "3 Mt.".to_string() }, ChartTick { at: 65.0, label: "65 J.".to_string() }],
1178            x_max: 65.0,
1179            y_max: 80.0,
1180            ref_lines: vec![ChartRefLine { value: 80.0, label: "CHF 80'000".to_string(), dashed: false }],
1181            bracket: Some(ChartBracket { y0: 60.0, y1: 80.0, label: "Ceiling".to_string(), info: true }),
1182            legend: vec![ChartLegendItem { label: "Gap".to_string(), color: Rgb::new(0x5A, 0x7D, 0x9A) }],
1183        });
1184        round_trips(&Widget::PdfView { url: "https://example.com/report.pdf".to_string() });
1185        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 });
1186        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 });
1187        round_trips(&Widget::WebView { url: "https://iframe.mediadelivery.net/embed/1/abc".to_string() });
1188        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 });
1189        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 });
1190        round_trips(&Widget::TextField { id: "email".to_string(), placeholder: "you@co".to_string(), value: "".to_string(), kind: FieldKind::Email, error: None });
1191        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()) });
1192        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] });
1193        round_trips(&Widget::SwipeAction { child: Box::new(Widget::Divider), actions: vec![SwipeButton { label: "Del".to_string(), tone: Tone::Danger, on_tap: "t".to_string() }] });
1194        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 });
1195        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: true, on_back: Some("back".to_string()) });
1196        round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: false, on_back: None });
1197        round_trips(&Widget::Scroller { children: vec![Widget::Divider], edge_fade: true });
1198        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 });
1199        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 });
1200        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 });
1201        // Un-themed scaffold (theme: None) — the default, must round-trip.
1202        round_trips(&Widget::Scaffold {
1203            title: "T".to_string(),
1204            body: Box::new(Widget::Divider),
1205            tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home), badge: None }],
1206            back: Some("b".to_string()),
1207            dark_mode: true,
1208            theme: None,
1209            fab: None,
1210            sheet: None,
1211            on_refresh: None,
1212            refreshing: false,
1213            route: "r".to_string(),
1214            depth: 2,
1215            labels: None,
1216            appearance: None,
1217            bottom_bar: None,
1218            ios_glass_tabs: false,
1219        });
1220        // Themed scaffold — all four theme knobs must round-trip.
1221        round_trips(&Widget::Scaffold {
1222            title: "T".to_string(),
1223            body: Box::new(Widget::Divider),
1224            tabs: vec![],
1225            back: None,
1226            dark_mode: false,
1227            theme: Some(Theme {
1228                seed: Rgb::new(0xC8, 0x5A, 0x3C),
1229                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
1230                corner: Corner::Large,
1231                density: Density::Compact,
1232                font: FontFamily::Rounded,
1233                ..Default::default()
1234            }),
1235            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string(), label: None }),
1236            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
1237            on_refresh: Some("r".to_string()),
1238            refreshing: true,
1239            route: "r".to_string(),
1240            depth: 1,
1241            labels: None,
1242            appearance: None,
1243            bottom_bar: Some(vec![Widget::Divider]),
1244            ios_glass_tabs: false,
1245        });
1246        // Themed scaffold with Density::Large — the big-touch-target density must round-trip.
1247        round_trips(&Widget::Scaffold {
1248            title: "T".to_string(),
1249            body: Box::new(Widget::Divider),
1250            tabs: vec![],
1251            back: None,
1252            dark_mode: false,
1253            theme: Some(Theme {
1254                seed: Rgb::new(0xC8, 0x5A, 0x3C),
1255                accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
1256                corner: Corner::Large,
1257                density: Density::Large,
1258                font: FontFamily::Rounded,
1259                ..Default::default()
1260            }),
1261            fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string(), label: None }),
1262            sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
1263            on_refresh: Some("r".to_string()),
1264            refreshing: true,
1265            route: "r".to_string(),
1266            depth: 1,
1267            labels: None,
1268            appearance: None,
1269            bottom_bar: None,
1270            ios_glass_tabs: false,
1271        });
1272        // Labelled scaffold — every ShellLabels field must round-trip.
1273        round_trips(&Widget::Scaffold {
1274            title: "T".to_string(),
1275            body: Box::new(Widget::Divider),
1276            tabs: vec![],
1277            back: None,
1278            dark_mode: false,
1279            theme: None,
1280            fab: None,
1281            sheet: None,
1282            on_refresh: None,
1283            refreshing: false,
1284            route: "r".to_string(),
1285            depth: 1,
1286            labels: Some(
1287                ShellLabels::new()
1288                    .back("Nazad")
1289                    .load_more("Učitaj još")
1290                    .refresh("Osveži")
1291                    .ok("U redu")
1292                    .cancel("Otkaži")
1293                    .done("Gotovo")
1294                    .pdf_error("Greška")
1295                    .pdf_title("Dokument")
1296                    .web_title("Stranica"),
1297            ),
1298            appearance: Some(Appearance::System),
1299            bottom_bar: None,
1300            ios_glass_tabs: false,
1301        });
1302    }
1303}