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 }
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)]
65pub enum CardStyle { Elevated, Outlined, Filled, Brand }
66
67/// Accessibility role for [`Widget::A11y`] — the control type announced to a screen reader. Maps
68/// best-effort per platform: iOS accessibility traits, Android semantics role / `heading()`, web ARIA role.
69#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
70#[repr(C)]
71pub enum A11yRole { Button, Link, Image, Header, Adjustable }
72
73/// What a [`Widget::TextField`] accepts — selects the on-screen keyboard,
74/// secure (masked) entry, and single- vs multi-line layout in one axis.
75///
76/// `Text` is the plain default. `Secure` masks input (passwords). `Email`,
77/// `Number` (integer), `Decimal`, `Phone`, and `Url` pick the matching native
78/// keyboard / input mode without masking. `Multiline` is a growable multi-row
79/// text area (plain keyboard).
80#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
81#[repr(C)]
82pub enum FieldKind { Text, Secure, Email, Number, Decimal, Phone, Url, Multiline }
83
84/// Semantic status color (distinct from brand/identity color).
85#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
86#[repr(C)]
87pub enum Tone { Neutral, Success, Warning, Danger, Info }
88
89/// How a `Chart` draws its series.
90///
91/// **Cartesian** styles plot every series over the shared `labels` x-axis:
92/// `Bar`/`Line` (grouped bars / one polyline per series), `StackedBar` (series stack to a total
93/// per x-slot), `StackedBar100` (each x-slot fills to 100% — series as proportions).
94///
95/// **Circular** styles ignore the x-axis and the `axis` flag: `Pie`/`Donut` turn **each series**
96/// into one wedge sized by its magnitude (`Donut` leaves a center hole); `Rings` draws concentric
97/// progress arcs (Apple-Watch fitness style), one per series, swept by `sum(values) / goal`;
98/// `Gauge` draws a single arc for the first series' `value / goal` with the number in the center.
99#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
100#[repr(C)]
101pub enum ChartStyle { Bar, Line, StackedBar, StackedBar100, Pie, Donut, Rings, Gauge }
102
103/// One named data series in a [`Widget::Chart`]. Cartesian styles plot `values` across the chart's
104/// x-axis `labels`; circular styles (pie/donut/rings/gauge) collapse the series to a single
105/// magnitude (`values` summed). `color` overrides the auto-assigned palette slot; `goal` is the
106/// denominator for `Rings`/`Gauge` progress (ignored by the other styles).
107#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
108#[repr(C)]
109pub struct ChartSeries {
110 pub name: String,
111 pub values: Vec<f32>,
112 pub color: Option<Rgb>,
113 pub goal: Option<f32>,
114}
115
116impl ChartSeries {
117 /// A named series carrying `values`. Color falls back to the chart palette; no goal.
118 #[must_use]
119 pub fn new(name: impl Into<String>, values: Vec<f32>) -> Self {
120 Self { name: name.into(), values, color: None, goal: None }
121 }
122 /// Override the auto-assigned palette color for this series.
123 #[must_use]
124 pub fn with_color(mut self, color: Rgb) -> Self {
125 self.color = Some(color);
126 self
127 }
128 /// Set the denominator for `Rings`/`Gauge` progress (`sum(values) / goal`). Ignored by
129 /// cartesian and pie/donut styles.
130 #[must_use]
131 pub fn with_goal(mut self, goal: f32) -> Self {
132 self.goal = Some(goal);
133 self
134 }
135}
136
137// ----------------------------- region chart -----------------------------
138//
139// A [`Widget::RegionChart`] is a variable-width stacked-region ("Marimekko" / coverage-gap)
140// chart: arbitrary colored rectangles placed in a 2-D `[0, x_max] × [0, y_max]` plane, each with
141// an in-cell label, plus horizontal reference lines, an irregular x-axis, an optional right-side
142// bracket annotation, and a legend. The app computes the geometry; the shells map domain→pixels.
143
144/// One rectangle in a [`Widget::RegionChart`], spanning `[x0, x1]` horizontally and `[y0, y1]`
145/// vertically in the chart's domain. `label` is centered inside (empty = none); `vertical` rotates
146/// it 90° for narrow columns. `color` overrides the auto-assigned palette slot.
147#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
148#[repr(C)]
149pub struct ChartRegion {
150 pub x0: f32,
151 pub x1: f32,
152 pub y0: f32,
153 pub y1: f32,
154 pub color: Option<Rgb>,
155 pub label: String,
156 pub vertical: bool,
157}
158
159/// A horizontal reference line across a [`Widget::RegionChart`] at `value`, with a right-edge
160/// `label` chip. `dashed` draws it dashed (e.g. a "max insured" ceiling) vs solid (a target).
161#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
162#[repr(C)]
163pub struct ChartRefLine {
164 pub value: f32,
165 pub label: String,
166 pub dashed: bool,
167}
168
169/// A right-side bracket annotation spanning `[y0, y1]` with a `label` note (e.g. a ceiling band).
170#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
171#[repr(C)]
172pub struct ChartBracket {
173 pub y0: f32,
174 pub y1: f32,
175 pub label: String,
176 /// Show an ⓘ info marker above the label (e.g. a "Ceiling max …" note). `label` may contain
177 /// `\n` for multiple lines.
178 pub info: bool,
179}
180
181/// An x-axis tick on a [`Widget::RegionChart`] at domain position `at`, labelled `label`. Ticks
182/// are irregular (the app places them), so shells position them by fraction, not even spacing.
183#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
184#[repr(C)]
185pub struct ChartTick {
186 pub at: f32,
187 pub label: String,
188}
189
190/// One legend entry (swatch + name) for a [`Widget::RegionChart`].
191#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
192#[repr(C)]
193pub struct ChartLegendItem {
194 pub label: String,
195 pub color: Rgb,
196}
197
198impl ChartRegion {
199 /// A region spanning `[x0,x1] × [y0,y1]` with a centered `label` (palette color, horizontal).
200 #[must_use]
201 pub fn new(x0: f32, x1: f32, y0: f32, y1: f32, label: impl Into<String>) -> Self {
202 Self { x0, x1, y0, y1, color: None, label: label.into(), vertical: false }
203 }
204 /// Override the fill color.
205 #[must_use]
206 pub fn with_color(mut self, color: Rgb) -> Self {
207 self.color = Some(color);
208 self
209 }
210 /// Render the label rotated 90° (for tall, narrow regions).
211 #[must_use]
212 pub fn vertical(mut self) -> Self {
213 self.vertical = true;
214 self
215 }
216}
217
218impl ChartRefLine {
219 /// A solid target line at `value` with a right-edge chip.
220 #[must_use]
221 pub fn target(value: f32, label: impl Into<String>) -> Self {
222 Self { value, label: label.into(), dashed: false }
223 }
224 /// A dashed "max"/ceiling line at `value`.
225 #[must_use]
226 pub fn max(value: f32, label: impl Into<String>) -> Self {
227 Self { value, label: label.into(), dashed: true }
228 }
229}
230
231impl ChartTick {
232 #[must_use]
233 pub fn new(at: f32, label: impl Into<String>) -> Self {
234 Self { at, label: label.into() }
235 }
236}
237
238impl ChartLegendItem {
239 #[must_use]
240 pub fn new(label: impl Into<String>, color: Rgb) -> Self {
241 Self { label: label.into(), color }
242 }
243}
244
245impl ChartBracket {
246 #[must_use]
247 pub fn new(y0: f32, y1: f32, label: impl Into<String>) -> Self {
248 Self { y0, y1, label: label.into(), info: false }
249 }
250 /// Show an ⓘ info marker above the label.
251 #[must_use]
252 pub fn with_info(mut self) -> Self {
253 self.info = true;
254 self
255 }
256}
257
258#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
259#[repr(C)]
260pub enum Spacing { Xs, Sm, Md, Lg, Xl }
261
262/// A finite icon set (maps to Material icons / SF Symbols / web glyphs per shell).
263/// Grouped: editing, navigation/chrome, content, and domain icons.
264#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
265#[repr(C)]
266pub enum Icon {
267 // editing / status
268 Delete, Add, Edit, Close, Settings, Check, Star, Info,
269 // navigation / chrome
270 Home, Search, Menu, Filter, Back, Forward, Down, Bell, Cart, Share, Heart, HeartFilled,
271 // people / contact
272 Person, People, Phone, Mail, Calendar, Clock, MapPin,
273 // content / media
274 Camera, Photo, Play,
275 // domain
276 Scissors,
277}
278
279#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
280#[repr(C)]
281pub enum ImageShape { Square, Rounded, Circle }
282
283#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
284#[repr(C)]
285pub enum ImageRatio { Wide, Square, Tall }
286
287#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
288#[repr(C)]
289pub enum BoxAlign { TopStart, TopEnd, Center, BottomStart, BottomCenter, BottomEnd }
290
291/// Project-identity colors (distinct from semantic `Tone`). Concrete RGB decided
292/// in the render layer.
293#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
294#[repr(C)]
295pub enum ProjectColor { Indigo, Teal, Coral, Amber, Lime, Pink }
296
297// ------------------------------- theme -------------------------------
298
299/// A 24-bit RGB color. Used for a theme's brand/seed color — the one place an app
300/// supplies an arbitrary color (everything else is intent tokens).
301#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
302#[repr(C)]
303pub struct Rgb {
304 pub r: u8,
305 pub g: u8,
306 pub b: u8,
307}
308
309impl Rgb {
310 pub const fn new(r: u8, g: u8, b: u8) -> Self {
311 Self { r, g, b }
312 }
313}
314
315/// Global corner-radius scale. `Medium` ≈ the current (un-themed) look.
316#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
317#[repr(C)]
318pub enum Corner { None, Small, Medium, Large }
319
320/// Global density. `Comfortable` ≈ the current (un-themed) look; `Compact` tightens spacing.
321/// `Large` is for hurried / wet / gloved hands: bigger controls (56 buttons & segmented, 48 chips
322/// & calendar days, 56 icon-button targets), 16 control labels, ≥ 12 between adjacent tappables.
323/// Body text stays on the platform's font-scale setting.
324#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
325#[repr(C)]
326pub enum Density { Compact, Comfortable, Large }
327
328/// A finite, cross-platform font family (maps to each platform's nearest system
329/// font design — no bundled font files). `System` ≈ the current look.
330#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
331#[repr(C)]
332pub enum FontFamily { System, Rounded, Serif, Monospace }
333
334/// App branding as data — the visual twin of `dark_mode`. Set on a [`Widget::Scaffold`]
335/// (`theme: None` = the framework defaults, i.e. no visual change). The shell maps these
336/// to its native theming: `seed` → the brand/primary color (Android M3 scheme / iOS tint /
337/// web `--primary`), plus a global corner, spacing, and font choice.
338#[derive(Facet, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
339#[repr(C)]
340pub struct Theme {
341 pub seed: Rgb,
342 /// Optional secondary brand color. `None` ⇒ derived from `seed`. Used for the
343 /// gradient on `CardStyle::Brand` (seed → accent) and as a secondary accent.
344 pub accent: Option<Rgb>,
345 pub corner: Corner,
346 pub density: Density,
347 pub font: FontFamily,
348}
349
350/// `Theme::default()` matches the framework's un-themed look as closely as a theme can
351/// (medium corners, comfortable spacing, system font) with a neutral indigo seed — so an
352/// app can override just the bits it cares about: `Theme { seed: brand, ..Default::default() }`.
353impl Default for Theme {
354 fn default() -> Self {
355 Theme {
356 seed: Rgb::new(0x5C, 0x6B, 0xC0), // indigo — matches the legacy default accent
357 accent: None,
358 corner: Corner::Medium,
359 density: Density::Comfortable,
360 font: FontFamily::System,
361 }
362 }
363}
364
365/// Text the shells draw themselves (back buttons, web list controls, dialog/picker defaults), in the
366/// app's language. Set once on the scaffold with `with_labels`; every field is optional and falls
367/// back to the shell's built-in English. A label passed to a specific call (`confirm_with`,
368/// `Picker`) still wins over these.
369#[derive(Facet, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
370#[repr(C)]
371pub struct ShellLabels {
372 /// `Split` back-button text on every shell; the Scaffold back button's accessible name.
373 pub back: Option<String>,
374 /// Web `LazyList` "Load more" button.
375 pub load_more: Option<String>,
376 /// Web `LazyList` refresh button (shown after a ↻) and the web scaffold refresh button's name.
377 pub refresh: Option<String>,
378 /// Confirm dialog: the confirming button when the call gives no label.
379 pub ok: Option<String>,
380 /// Confirm dialog and pickers: the dismissing button when the call gives no label.
381 pub cancel: Option<String>,
382 /// Pickers: the accepting button when the call gives no label.
383 pub done: Option<String>,
384 /// Android PdfView error text.
385 pub pdf_error: Option<String>,
386 /// Web PDF iframe title (accessibility).
387 pub pdf_title: Option<String>,
388 /// Web WebView iframe title (accessibility).
389 pub web_title: Option<String>,
390}
391
392impl ShellLabels {
393 #[must_use]
394 pub fn new() -> Self {
395 Self::default()
396 }
397 #[must_use]
398 pub fn back(mut self, l: impl Into<String>) -> Self {
399 self.back = Some(l.into());
400 self
401 }
402 #[must_use]
403 pub fn load_more(mut self, l: impl Into<String>) -> Self {
404 self.load_more = Some(l.into());
405 self
406 }
407 #[must_use]
408 pub fn refresh(mut self, l: impl Into<String>) -> Self {
409 self.refresh = Some(l.into());
410 self
411 }
412 #[must_use]
413 pub fn ok(mut self, l: impl Into<String>) -> Self {
414 self.ok = Some(l.into());
415 self
416 }
417 #[must_use]
418 pub fn cancel(mut self, l: impl Into<String>) -> Self {
419 self.cancel = Some(l.into());
420 self
421 }
422 #[must_use]
423 pub fn done(mut self, l: impl Into<String>) -> Self {
424 self.done = Some(l.into());
425 self
426 }
427 #[must_use]
428 pub fn pdf_error(mut self, l: impl Into<String>) -> Self {
429 self.pdf_error = Some(l.into());
430 self
431 }
432 #[must_use]
433 pub fn pdf_title(mut self, l: impl Into<String>) -> Self {
434 self.pdf_title = Some(l.into());
435 self
436 }
437 #[must_use]
438 pub fn web_title(mut self, l: impl Into<String>) -> Self {
439 self.web_title = Some(l.into());
440 self
441 }
442}
443
444/// A bottom-navigation tab. `selected` marks the active one; tapping sends
445/// `on_select`. `icon` (optional) renders above the label for an icon tab bar.
446#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
447#[repr(C)]
448pub struct Tab {
449 pub label: String,
450 pub selected: bool,
451 pub on_select: ActionToken,
452 /// Optional leading icon (icon tab bar). `None` = label-only (the original look).
453 pub icon: Option<Icon>,
454}
455
456/// A floating action button anchored over the scaffold body (the raised primary action).
457#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
458#[repr(C)]
459pub struct Fab {
460 pub icon: Icon,
461 pub on_press: ActionToken,
462}
463
464/// One option in a [`Widget::Segmented`] control (mirrors [`Tab`]). `selected` marks the
465/// active segment; tapping sends `on_select`.
466#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
467#[repr(C)]
468pub struct Segment {
469 pub label: String,
470 pub selected: bool,
471 pub on_select: ActionToken,
472}
473
474/// A modal bottom sheet anchored over the scaffold body (a scrim behind, a panel rising from
475/// the bottom). Present (`Some`) ⇒ open; tapping the scrim/handle sends `on_dismiss`.
476#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
477#[repr(C)]
478pub struct Sheet {
479 pub title: String,
480 pub child: Box<Widget>,
481 pub on_dismiss: ActionToken,
482}
483
484/// One revealed action in a `SwipeAction` row (swipe to reveal, tap to fire).
485#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
486#[repr(C)]
487pub struct SwipeButton {
488 pub label: String,
489 pub tone: Tone,
490 pub on_tap: ActionToken,
491}
492
493/// One subtitle/caption track for a [`Widget::Video`]. `url` points at a WebVTT (`.vtt`) file,
494/// `language` is a BCP-47 tag (e.g. `"en"`), `label` is the human-readable menu entry, and
495/// `default_on` selects it by default. Sidecar tracks work on web (`<track>`) and Android
496/// (Media3 subtitle configuration); on iOS only captions already embedded in an HLS manifest are
497/// selectable (AVPlayer can't attach a sidecar VTT to an MP4 — a documented v1 gap).
498#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
499#[repr(C)]
500pub struct Caption {
501 pub url: String,
502 pub label: String,
503 pub language: String,
504 pub default_on: bool,
505}
506
507/// A pin on a [`Widget::Map`]. `id` is echoed back when the marker is tapped
508/// (`Action::Input { id: "{map_id}.marker", value: Text(marker.id) }`).
509#[derive(Facet, Serialize, Deserialize, Clone, Debug, PartialEq)]
510#[repr(C)]
511pub struct MapMarker {
512 pub id: String,
513 pub lat: f64,
514 pub lng: f64,
515 pub title: Option<String>,
516}
517
518// ------------------------------- widgets -------------------------------
519
520/// The app-agnostic widget tree the shell renders. **Fixed across all apps.**
521// `Scaffold`'s `ShellLabels` (nine `Option<String>` fields) makes it the largest variant by a wide
522// margin; boxing it would ripple through every `with_labels`/scaffold call site for no runtime
523// benefit on a wire type that is rebuilt per-render, not stored in bulk.
524#[allow(clippy::large_enum_variant)]
525#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
526#[repr(C)]
527pub enum Widget {
528 // Content
529 Text { content: String, style: TextStyle },
530 Image { source: String, shape: ImageShape, ratio: ImageRatio },
531 Badge { label: String, tone: Tone },
532 /// A circular avatar image with an optional colored status dot.
533 Avatar { source: String, status: Option<Tone> },
534 /// An in-app PDF viewer showing the document at `url` (a remote https URL or a local
535 /// file URI). Each shell uses its native renderer — PDFKit on iOS, a paged `PdfRenderer`
536 /// on Android, an `<iframe>` on web — so the app only supplies the URL (e.g. a
537 /// backend-generated report). Fills its width; give it room (place in a sized container).
538 PdfView { url: String },
539 /// An in-app native video player for the stream/file at `url` (MP4 everywhere; HLS `.m3u8` on
540 /// iOS/Android natively + Safari on web; or a local file URI). Native player per shell — AVPlayer
541 /// (iOS), Media3/ExoPlayer (Android), a `<video>` element (web). **Controllable:** `playing` drives
542 /// play/pause (app-owned, like a `Toggle`); set `seek_to_ms` to jump (the shell seeks when the value
543 /// CHANGES; `-1` = no seek). The shell reports the current position ~once/second via
544 /// `Action::Input { id, value: Int(position_ms) }` (handle it in [`MobilerApp::input`]), and fires
545 /// `on_ended` when the clip finishes. `controls` shows the native transport bar; `looping` restarts
546 /// on end; `muted` starts muted (needed for reliable autoplay). Fills its width; give it room.
547 ///
548 /// v2 fields: `poster` shows a thumbnail image before the first play; `start_at_ms` resumes at an
549 /// offset (applied once on load, `-1` = start). `captions` adds subtitle tracks (see [`Caption`]).
550 /// `rate` sets playback speed (`1.0` = normal) and `volume` the level (`0.0`–`1.0`). For a playlist,
551 /// set `urls` (non-empty takes precedence over `url`) with `start_index`; the shell auto-advances
552 /// and reports the current track ~as it changes via `Action::Input { id: "{id}.index", … }`, and
553 /// `seek_index` jumps to a track when it CHANGES (`-1` = none). The shell also reports
554 /// `"{id}.duration"`, `"{id}.state"` (0 idle / 1 buffering / 2 ready-paused / 3 playing / 4 ended)
555 /// and `"{id}.buffered"` via the same `Input` path (handle them in [`MobilerApp::input`]). Set
556 /// `allow_pip` to enable Picture-in-Picture (the shell adds a PiP affordance).
557 Video {
558 url: String,
559 id: String,
560 playing: bool,
561 seek_to_ms: i64,
562 controls: bool,
563 looping: bool,
564 muted: bool,
565 on_ended: Option<ActionToken>,
566 poster: Option<String>,
567 start_at_ms: i64,
568 captions: Vec<Caption>,
569 rate: f32,
570 volume: f32,
571 urls: Vec<String>,
572 start_index: i64,
573 seek_index: i64,
574 allow_pip: bool,
575 },
576 /// Displays the web page / embedded player at `url` in a native web view — `WKWebView` on iOS,
577 /// `android.webkit.WebView` on Android, an `<iframe>` on web. General-purpose: docs, dashboards,
578 /// or a hosted player embed (e.g. a Bunny.net / YouTube embed URL, which brings its own
579 /// captions/quality/thumbnails). JavaScript and inline media autoplay are enabled so hosted
580 /// players work. This is NOT the default way to play video — use [`Widget::Video`] for a
581 /// controllable native player. Fills its width; give it room (place in a sized container).
582 WebView { url: String },
583 /// An interactive map (a "live native view" like [`Widget::Video`]): iOS MapKit, Android MapLibre
584 /// Native, web MapLibre-GL — no API key. The app drives the camera (`center_lat`/`center_lng`/`zoom`)
585 /// and `markers`; the user pans/zooms when `interactive`. Taps report back via `Action::Input`:
586 /// a map tap → `{ id: "{id}.tap", value: Text("lat,lng") }`, a marker tap → `{ id: "{id}.marker",
587 /// value: Text(marker.id) }` (handle in [`MobilerApp::input`] by id-suffix). `style_url` selects the
588 /// MapLibre vector style on Android/web (None → a free default); iOS MapKit uses Apple Maps and
589 /// ignores it. Fills its width; give it a height (place in a sized container).
590 Map {
591 id: String,
592 center_lat: f64,
593 center_lng: f64,
594 zoom: f64,
595 markers: Vec<MapMarker>,
596 style_url: Option<String>,
597 interactive: bool,
598 },
599 /// A star rating. `value` is in tenths (e.g. `48` = 4.8 of `max` stars). When `on_rate`
600 /// is set (one token per star), the stars are tappable — star *i* fires `on_rate[i]`.
601 Rating { value: u32, max: u8, on_rate: Option<Vec<ActionToken>> },
602 /// Small non-interactive colored dot — a project/identity hint.
603 ColorDot { color: ProjectColor },
604 Divider,
605 /// Progress indicator: `value` 0.0–1.0 for a determinate bar, `None` for an indeterminate spinner.
606 Progress { value: Option<f32> },
607 /// Shimmer placeholder shown while content loads.
608 Skeleton,
609 /// A data chart drawing one or more named `series` in the given `style` (see [`ChartStyle`]).
610 /// `labels` (optional) annotate the x-axis for cartesian styles. `axis` shows y gridlines +
611 /// tick values (cartesian only); `legend` shows a series swatch+name row. Non-interactive.
612 Chart { series: Vec<ChartSeries>, labels: Vec<String>, style: ChartStyle, axis: bool, legend: bool },
613 /// A variable-width stacked-region ("Marimekko" / coverage-gap) chart: `regions` are arbitrary
614 /// colored rectangles in the `[0, x_max] × [0, y_max]` plane (each with an in-cell label),
615 /// `ticks` annotate the irregular x-axis, `ref_lines` are horizontal target/max lines with
616 /// right-edge chips, `bracket` is an optional right-side range annotation, and `legend` names
617 /// the colors. The app supplies all geometry; shells map domain→pixels. Non-interactive.
618 RegionChart {
619 regions: Vec<ChartRegion>,
620 ticks: Vec<ChartTick>,
621 x_max: f32,
622 y_max: f32,
623 ref_lines: Vec<ChartRefLine>,
624 bracket: Option<ChartBracket>,
625 legend: Vec<ChartLegendItem>,
626 },
627 /// An inline month calendar. The core pre-computes everything locale-dependent so shells only
628 /// draw: `title` (e.g. "Septembar 2026"), the 7 `weekday_labels` in column order (week start
629 /// first), and `leading_blanks` (empty cells before day 1). `on_day[d-1]` fires when day `d` is
630 /// tapped (length = days in the month); `selected` highlights a day. `markers` is empty (no
631 /// markers) or one level per day, `0..=3`, drawn as that many small dots under the day number.
632 Calendar {
633 year: u32,
634 month: u8,
635 title: String,
636 weekday_labels: Vec<String>,
637 leading_blanks: u8,
638 selected: Option<u8>,
639 on_day: Vec<ActionToken>,
640 markers: Vec<u8>,
641 },
642 /// A list row that reveals trailing `actions` on horizontal swipe (each tappable). On web the
643 /// actions render inline as a trailing button row (no gesture).
644 SwipeAction { child: Box<Widget>, actions: Vec<SwipeButton> },
645 /// A scrollable list for long/paged feeds, with shell-detected events at both ends: the bottom
646 /// `on_load_more` fires when the user scrolls near the end (infinite scroll), the top
647 /// `on_refresh` fires on pull-to-refresh. `loading`/`refreshing`/`has_more` are app-owned: set
648 /// `loading` while a page loads (shell shows a spinner, stops firing), `has_more=false` when
649 /// exhausted, and `refreshing` while a pull-refresh runs. The app appends to `children` on each
650 /// load-more. `on_refresh` is set via [`with_refresh`](mobiler_core::with_refresh).
651 LazyList {
652 children: Vec<Widget>,
653 on_load_more: Option<ActionToken>,
654 loading: bool,
655 has_more: bool,
656 on_refresh: Option<ActionToken>,
657 refreshing: bool,
658 /// Text shown under an exhausted paged list (`has_more == false` with `on_load_more` set),
659 /// e.g. "You're all caught up" in the app's language. `None` shows nothing. Set with
660 /// `with_end_label`.
661 end_label: Option<String>,
662 /// Fill the rest of the screen instead of the fixed height, when this list is the scaffold
663 /// body or a direct child of the body's column (the first one). Set with `with_fill`.
664 fill: bool,
665 },
666 Spacer { size: Spacing },
667 // Layout
668 Row { children: Vec<Widget> },
669 Column { children: Vec<Widget> },
670 /// Card; tappable when `on_press` is set. Fires `on_long_press` (when set) on a
671 /// press-and-hold (web: a ~500 ms pointer-hold; iOS: `onLongPressGesture`;
672 /// Android: `combinedClickable`'s `onLongClick`).
673 Card {
674 child: Box<Widget>,
675 style: CardStyle,
676 on_press: Option<ActionToken>,
677 on_long_press: Option<ActionToken>,
678 },
679 /// Z-stack: children layered back-to-front, positioned by `align`. With
680 /// `scrim`, the first child is a background image, darkened for legibility,
681 /// and the rest render on top in light content.
682 Box { children: Vec<Widget>, align: BoxAlign, scrim: bool },
683 /// Fixed 2-column grid; children flow left-to-right, top-to-bottom.
684 Grid { children: Vec<Widget> },
685 /// Horizontally scrolling row. `edge_fade` fades the trailing edge (plus trailing room so the
686 /// last item clears the fade at scroll-end) to hint there is more to scroll.
687 Scroller { children: Vec<Widget>, edge_fade: bool },
688 /// Two-pane master-detail. On a **wide** screen (tablet / landscape — the shell's regular size
689 /// class) `primary` and `detail` render side-by-side; on a **compact** screen (phone) it shows
690 /// ONE pane: `primary` until `show_detail` is set (the app sets it when a row is selected), then
691 /// `detail` with a back chevron that fires `on_back` (the app clears its selection). On wide,
692 /// `show_detail`/`on_back` are ignored — both panes stay visible, so `detail` should show a
693 /// placeholder until something is selected.
694 Split { primary: Box<Widget>, detail: Box<Widget>, show_detail: bool, on_back: Option<ActionToken> },
695 /// Accessibility wrapper: presents `child`'s subtree as ONE screen-reader element named by `label`
696 /// (so an unlabeled IconButton/Image gets a name, or a Card's children group into one announced
697 /// element). `hint` describes what activation does; `role` is the control type. Shell-applied:
698 /// iOS accessibilityLabel/Hint/Traits, Android contentDescription/role/heading, web aria-label/role.
699 A11y { child: Box<Widget>, label: String, hint: Option<String>, role: Option<A11yRole> },
700 // Input
701 /// A tappable button. `tone` recolors it (`Neutral` = the brand/primary look; `Danger` = the
702 /// error color pair for destructive actions). `icon` draws a leading glyph; `wide` stretches it
703 /// to the available width.
704 Button { label: String, style: ButtonStyle, on_press: ActionToken, tone: Tone, icon: Option<Icon>, wide: bool },
705 IconButton { icon: Icon, on_press: ActionToken },
706 Chip { label: String, selected: bool, on_press: ActionToken },
707 /// A text input. `kind` selects keyboard / secure entry / multiline
708 /// (see [`FieldKind`]); `error`, when `Some`, shows an inline validation
709 /// message below the field and marks it invalid. Emits `Input { id, Text }`.
710 TextField { id: String, placeholder: String, value: String, kind: FieldKind, error: Option<String> },
711 /// A search input (leading magnifier, pill shape); emits `Input { id, Text }` like `TextField`.
712 SearchField { id: String, placeholder: String, value: String },
713 /// A single-choice segmented control — exclusive options in a pill (e.g. Men/Women/Kids).
714 Segmented { segments: Vec<Segment> },
715 Toggle { id: String, label: String, value: bool },
716 Checkbox { id: String, label: String, value: bool },
717 /// Continuous 0..=`max` slider; emits `Input { id, Int }`.
718 Slider { id: String, value: i32, max: i32 },
719 /// Numeric stepper with −/+ controls carrying their own events.
720 Stepper { value: i32, on_decrement: ActionToken, on_increment: ActionToken },
721 /// App shell: a top bar (`title` + optional `back`), a scrollable `body`,
722 /// and bottom-nav `tabs`. `dark_mode` is theme-as-data — the shell themes
723 /// the whole app from it.
724 ///
725 /// `route` + `depth` drive navigation: the shell animates the body when
726 /// `route` (the current screen's identity) changes — slide for push/pop
727 /// (direction from whether `depth` grew or shrank), crossfade for a lateral
728 /// move at the same depth — and wires the system back button to `back`.
729 Scaffold {
730 title: String,
731 body: Box<Widget>,
732 tabs: Vec<Tab>,
733 back: Option<ActionToken>,
734 dark_mode: bool,
735 /// App branding (brand color, corner, density, font). `None` = framework
736 /// defaults (no visual change) — theme-as-data, the visual twin of `dark_mode`.
737 theme: Option<Theme>,
738 /// Optional floating action button (raised primary action over the body).
739 fab: Option<Fab>,
740 /// Optional modal bottom sheet over the body (a scrim + a panel from the bottom).
741 sheet: Option<Sheet>,
742 /// Pull-to-refresh: when set, the body is pull-refreshable and fires this event on pull.
743 /// The app owns `refreshing` — set it true when the pull fires, clear it when the async
744 /// reload completes (the shell shows a spinner while it's true).
745 on_refresh: Option<ActionToken>,
746 refreshing: bool,
747 route: String,
748 depth: u32,
749 /// App-wide shell text (see [`ShellLabels`]). `None` ⇒ the shells' English defaults.
750 labels: Option<ShellLabels>,
751 },
752}
753
754#[cfg(test)]
755mod tests {
756 use super::*;
757 use serde::Serialize;
758 use serde::de::DeserializeOwned;
759
760 // Round-trips the ABI without requiring `PartialEq` on the wire types:
761 // serialize → deserialize → re-serialize, and compare the two encodings.
762 fn round_trips<T: Serialize + DeserializeOwned>(value: &T) {
763 let a = serde_json::to_string(value).expect("serialize");
764 let back: T = serde_json::from_str(&a).expect("deserialize");
765 let b = serde_json::to_string(&back).expect("re-serialize");
766 assert_eq!(a, b);
767 }
768
769 #[test]
770 fn action_round_trips() {
771 round_trips(&Action::Start);
772 round_trips(&Action::Fired { token: "tok".to_string() });
773 round_trips(&Action::Input { id: "field".to_string(), value: InputValue::Bool(true) });
774 round_trips(&Action::Restore { data: "{}".to_string() });
775 round_trips(&Action::AppInfo {
776 version: "1.0".to_string(),
777 build: "7".to_string(),
778 platform: "ios".to_string(),
779 bundle_id: "rs.x".to_string(),
780 });
781 }
782
783 #[test]
784 fn widget_round_trips() {
785 round_trips(&Widget::Text { content: "hi".to_string(), style: TextStyle::Title });
786 round_trips(&Widget::ColorDot { color: ProjectColor::Teal });
787 round_trips(&Widget::Chart {
788 series: vec![ChartSeries { name: "s".to_string(), values: vec![1.0, 2.5, 3.0], color: None, goal: None }],
789 labels: vec!["a".to_string()],
790 style: ChartStyle::Bar,
791 axis: true,
792 legend: false,
793 });
794 round_trips(&Widget::RegionChart {
795 regions: vec![ChartRegion::new(0.0, 3.0, 0.0, 80.0, "80%").vertical(),
796 ChartRegion::new(3.0, 21.0, 0.0, 80.0, "CHF 80'000").with_color(Rgb::new(0x8E, 0xC6, 0xBA))],
797 ticks: vec![ChartTick { at: 3.0, label: "3 Mt.".to_string() }, ChartTick { at: 65.0, label: "65 J.".to_string() }],
798 x_max: 65.0,
799 y_max: 80.0,
800 ref_lines: vec![ChartRefLine { value: 80.0, label: "CHF 80'000".to_string(), dashed: false }],
801 bracket: Some(ChartBracket { y0: 60.0, y1: 80.0, label: "Ceiling".to_string(), info: true }),
802 legend: vec![ChartLegendItem { label: "Gap".to_string(), color: Rgb::new(0x5A, 0x7D, 0x9A) }],
803 });
804 round_trips(&Widget::PdfView { url: "https://example.com/report.pdf".to_string() });
805 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 });
806 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 });
807 round_trips(&Widget::WebView { url: "https://iframe.mediadelivery.net/embed/1/abc".to_string() });
808 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 });
809 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 });
810 round_trips(&Widget::TextField { id: "email".to_string(), placeholder: "you@co".to_string(), value: "".to_string(), kind: FieldKind::Email, error: None });
811 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()) });
812 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] });
813 round_trips(&Widget::SwipeAction { child: Box::new(Widget::Divider), actions: vec![SwipeButton { label: "Del".to_string(), tone: Tone::Danger, on_tap: "t".to_string() }] });
814 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 });
815 round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: true, on_back: Some("back".to_string()) });
816 round_trips(&Widget::Split { primary: Box::new(Widget::Divider), detail: Box::new(Widget::Divider), show_detail: false, on_back: None });
817 round_trips(&Widget::Scroller { children: vec![Widget::Divider], edge_fade: true });
818 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 });
819 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 });
820 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 });
821 // Un-themed scaffold (theme: None) — the default, must round-trip.
822 round_trips(&Widget::Scaffold {
823 title: "T".to_string(),
824 body: Box::new(Widget::Divider),
825 tabs: vec![Tab { label: "A".to_string(), selected: true, on_select: "t".to_string(), icon: Some(Icon::Home) }],
826 back: Some("b".to_string()),
827 dark_mode: true,
828 theme: None,
829 fab: None,
830 sheet: None,
831 on_refresh: None,
832 refreshing: false,
833 route: "r".to_string(),
834 depth: 2,
835 labels: None,
836 });
837 // Themed scaffold — all four theme knobs must round-trip.
838 round_trips(&Widget::Scaffold {
839 title: "T".to_string(),
840 body: Box::new(Widget::Divider),
841 tabs: vec![],
842 back: None,
843 dark_mode: false,
844 theme: Some(Theme {
845 seed: Rgb::new(0xC8, 0x5A, 0x3C),
846 accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
847 corner: Corner::Large,
848 density: Density::Compact,
849 font: FontFamily::Rounded,
850 }),
851 fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string() }),
852 sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
853 on_refresh: Some("r".to_string()),
854 refreshing: true,
855 route: "r".to_string(),
856 depth: 1,
857 labels: None,
858 });
859 // Themed scaffold with Density::Large — the big-touch-target density must round-trip.
860 round_trips(&Widget::Scaffold {
861 title: "T".to_string(),
862 body: Box::new(Widget::Divider),
863 tabs: vec![],
864 back: None,
865 dark_mode: false,
866 theme: Some(Theme {
867 seed: Rgb::new(0xC8, 0x5A, 0x3C),
868 accent: Some(Rgb::new(0xE0, 0x6A, 0x2C)),
869 corner: Corner::Large,
870 density: Density::Large,
871 font: FontFamily::Rounded,
872 }),
873 fab: Some(Fab { icon: Icon::Calendar, on_press: "f".to_string() }),
874 sheet: Some(Sheet { title: "S".to_string(), child: Box::new(Widget::Divider), on_dismiss: "d".to_string() }),
875 on_refresh: Some("r".to_string()),
876 refreshing: true,
877 route: "r".to_string(),
878 depth: 1,
879 labels: None,
880 });
881 // Labelled scaffold — every ShellLabels field must round-trip.
882 round_trips(&Widget::Scaffold {
883 title: "T".to_string(),
884 body: Box::new(Widget::Divider),
885 tabs: vec![],
886 back: None,
887 dark_mode: false,
888 theme: None,
889 fab: None,
890 sheet: None,
891 on_refresh: None,
892 refreshing: false,
893 route: "r".to_string(),
894 depth: 1,
895 labels: Some(
896 ShellLabels::new()
897 .back("Nazad")
898 .load_more("Učitaj još")
899 .refresh("Osveži")
900 .ok("U redu")
901 .cancel("Otkaži")
902 .done("Gotovo")
903 .pdf_error("Greška")
904 .pdf_title("Dokument")
905 .web_title("Stranica"),
906 ),
907 });
908 }
909}