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