Skip to main content

makeover_layout/
lib.rs

1//! The renderer-agnostic half of the make-family design system.
2//!
3//! <!-- wiki: makeover-layout -->
4//!
5//! `makeover` answers *what colour*, and varies by theme. `makeover-geometry`
6//! answers *how much space*, and varies by density and surface. This crate
7//! answers *what the thing is*, and varies by nothing.
8//!
9//! # The deferral rule
10//!
11//! A description names intents and relationships, never values. Say
12//! [`Fill::Raised`], never `#D9DDF4`. Say `Gap::Peer`, never `6px`. What is
13//! left once colour and spacing are deferred is **composition**: which edges
14//! are lit, what inverts on press, what nests in what.
15//!
16//! The constraint that shapes all of it: a renderer that can only paint
17//! rectangles has to be able to express the result. egui has no
18//! `box-shadow: inset` and one stroke per widget with no per-side control; a
19//! terminal has box-drawing characters and one cell of resolution, and cannot
20//! draw a two-tone lit edge at all. A description that assumes per-side edges
21//! is a CSS description wearing a neutral name. So this crate names the
22//! *intent* — this region is a well — and each renderer chooses an expression
23//! it can actually produce, including dropping half of one.
24//!
25//! # Scope
26//!
27//! Depth came first: the bevel and the surfaces it shapes. That much was
28//! settled the hard way — the vocabulary here was read off audiofiles'
29//! `ui::theme` and `ui::widgets`, which are the only implementation written
30//! by a consumer with no CSS, then checked against both webview apps. All
31//! three agreed once Balanced Breakfast's fills were corrected.
32//!
33//! 0.2.0 adds the rest of the description, each member drawn the same way,
34//! from what the three apps already hand-write rather than from a taxonomy:
35//!
36//! - Components. [`Token`] (badge against chip), [`Notice`] (toast against
37//!   banner), [`RowPart`], [`Heading`], [`Selector`], [`Readiness`], and
38//!   [`Tone`], which is the one intent family they share.
39//! - Schemas. [`Field`] for forms and [`Column`] for lists and tables.
40//! - Structure. [`Region`] for the parts of a screen, [`Arrangement`] for how
41//!   a screen is put together.
42//!
43//! **Validation** is absent on purpose rather than pending: neither app has a
44//! shared story, and a schema describing fields but not constraints acquires a
45//! constraint layer per app, which is how the divergence this crate exists to
46//! end got started.
47//!
48//! 0.3.0 closes a gap the first real adoption found, which is what adopting
49//! against goingson first was for. [`Selector`] described only the *chosen*
50//! option, so an unchosen one fell through to [`Depth::Flat`] and no renderer
51//! drew it; goingson's tab strip recesses its unchosen tabs by hand and could
52//! not delete the line, because being recessed is *why* the chosen tab reads as
53//! coming forward. So [`Selector::unchosen`] joins `chosen`, and saying it
54//! needed [`Fill::Sunken`] and [`Depth::Sunken`]: a surface set back by colour
55//! with no edge, which is neither a well nor level-with.
56//!
57//! # Where the description stops
58//!
59//! The bespoke widgets, a day-plan timeline and a kanban board and a calendar,
60//! are not describable here and will not become describable. A description
61//! expressive enough to produce a timeline is a widget library wearing a
62//! description's name. Generate the boring 80% so the bespoke 20% gets the
63//! attention.
64//!
65//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
66//! description names the *place* and the app owns the contents, so a screen
67//! containing a timeline is still a whole screen and still routable. Without
68//! it, the four goingson screens that make the app worth using would need a
69//! second, undescribed path beside the router, and two paths is how a
70//! vocabulary starts drifting from its app again.
71
72#![forbid(unsafe_code)]
73
74/// A colour intent this crate refers to but never resolves.
75///
76/// The string is the token name `makeover` publishes, so a renderer can look
77/// it up without this crate knowing what colour came back.
78pub trait Intent {
79    /// The `makeover` intent token this resolves against.
80    fn token(self) -> &'static str;
81}
82
83/// Which way the light falls across a two-tone edge.
84///
85/// The whole content of a bevel, once colour and thickness are deferred. The
86/// light is always assumed to come from the top left: every consumer measured
87/// agreed on that and none of them ever varied it, so it is an invariant here
88/// rather than a parameter.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum Bevel {
91    /// Lit from the top left: light on top and left, dark on bottom and right.
92    Raised,
93    /// The same edge inverted, which is also the pressed state of anything
94    /// that draws itself [`Bevel::Raised`].
95    Inset,
96}
97
98impl Bevel {
99    /// The edge intents, as `(top_left, bottom_right)`.
100    ///
101    /// Split out from any painting because the inversion *is* the idea, and
102    /// it is the one part every renderer implements identically.
103    #[must_use]
104    pub const fn edges(self) -> (Edge, Edge) {
105        match self {
106            Self::Raised => (Edge::Light, Edge::Dark),
107            Self::Inset => (Edge::Dark, Edge::Light),
108        }
109    }
110
111    /// Pressing inverts. A raised control reads as inset while held.
112    ///
113    /// Stated here rather than left to each consumer because a cascade can
114    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
115    /// resolves this per call site, eighteen times.
116    #[must_use]
117    pub const fn pressed(self) -> Self {
118        match self {
119            Self::Raised => Self::Inset,
120            Self::Inset => Self::Raised,
121        }
122    }
123}
124
125/// One side of a bevel, named by the intent it takes.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127pub enum Edge {
128    /// The lit side.
129    Light,
130    /// The shadowed side.
131    Dark,
132}
133
134impl Intent for Edge {
135    fn token(self) -> &'static str {
136        match self {
137            Self::Light => "bevel-light",
138            Self::Dark => "bevel-dark",
139        }
140    }
141}
142
143/// A surface intent a region is filled with.
144///
145/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
146/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
147/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
148/// `makeover-immediate` at compile time and left neither able to move until
149/// both published. The vocabulary exists to grow and the renderers exist to
150/// disagree about how much of it they answer, so growth must not be a
151/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
152/// resolved through a fallible lookup, and a missing intent is answered with
153/// structure rather than with a substituted colour.
154///
155/// [`Sunken`]: Fill::Sunken
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
157#[non_exhaustive]
158pub enum Fill {
159    /// The page behind everything.
160    Page,
161    /// A surface lifted off the page: cards, controls, menus, toasts.
162    Raised,
163    /// A surface floating above the page rather than resting on it.
164    Overlay,
165    /// The inside of a well.
166    Well,
167    /// A surface set back from the one it sits on, by colour and nothing else.
168    ///
169    /// Not a well. A well is a hole with an edge, and the two are authored in
170    /// opposite directions: `makeover` derives `surface-well` by inverting
171    /// against the theme's own content colour, while `surface-sunken` is
172    /// authored and free to sit darker than raised (goingson's does). Naming
173    /// only the well left the recessed-with-no-edge surface unsayable, which is
174    /// what an unchosen tab is: it recedes so the chosen one can come forward,
175    /// and it carries no bevel of its own.
176    ///
177    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
178    /// and could not delete the line because no member described it.
179    Sunken,
180}
181
182// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
183// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
184// had something to paint. makeover-tui found that wrong within a day: page is
185// the surface a well is usually cut into, so on a terminal that substitution
186// produces exactly the invisibility it was meant to prevent, and the right
187// answer there is a drawn edge rather than a different colour.
188//
189// Substituting one intent for another is renderer policy. The description says
190// what the region is and stops.
191
192impl Intent for Fill {
193    fn token(self) -> &'static str {
194        match self {
195            Self::Page => "surface-page",
196            Self::Raised => "surface-raised",
197            Self::Overlay => "surface-overlay",
198            Self::Well => "surface-well",
199            Self::Sunken => "surface-sunken",
200        }
201    }
202}
203
204/// How a region sits relative to the surface behind it.
205///
206/// Fill and bevel are named together because naming them apart is what let
207/// them disagree. Every consumer measured had at least one region carrying a
208/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
209/// and recorded the bug in its doc comment, and Balanced Breakfast still had
210/// twelve of them a year later. A single name for the pair makes that
211/// unrepresentable.
212/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
213/// release: a depth this renderer has no drawing for should cost it a
214/// wildcard arm, not a compile error and a wait on someone else's publish.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
216#[non_exhaustive]
217pub enum Depth {
218    /// Level with its surroundings. No edge.
219    Flat,
220    /// A card laid on the panel it sits in.
221    Raised,
222    /// A hole in the panel, with content down inside it. For anything the
223    /// user looks *into*: a table body, a tag tree, a text field.
224    Well,
225    /// Set back from what it sits on, by colour alone. No edge.
226    ///
227    /// The one member carrying a fill without a bevel, so a renderer cannot
228    /// assume the two arrive together. That is deliberate and it is still the
229    /// pairing rule: both halves come off the same `Depth`, so they cannot
230    /// disagree, and here one half is legitimately absent.
231    ///
232    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
233    /// Recessed and level-with are different claims, and only one of them
234    /// needs a colour.
235    Sunken,
236}
237
238impl Depth {
239    /// The edge this depth is drawn with, if it has one.
240    #[must_use]
241    pub const fn bevel(self) -> Option<Bevel> {
242        match self {
243            // Sunken joins Flat here, for the opposite reason: Flat has no edge
244            // because nothing separates it from its surroundings, and Sunken has
245            // none because its colour is already doing the separating.
246            Self::Flat | Self::Sunken => None,
247            Self::Raised => Some(Bevel::Raised),
248            Self::Well => Some(Bevel::Inset),
249        }
250    }
251
252    /// The surface this depth is filled with.
253    ///
254    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
255    /// which is the difference between level-with and painted-the-same-colour.
256    #[must_use]
257    pub const fn fill(self) -> Option<Fill> {
258        match self {
259            Self::Flat => None,
260            Self::Raised => Some(Fill::Raised),
261            Self::Well => Some(Fill::Well),
262            Self::Sunken => Some(Fill::Sunken),
263        }
264    }
265
266    /// Pressing a raised region reads as a well, and nothing else moves.
267    #[must_use]
268    pub const fn pressed(self) -> Self {
269        match self {
270            Self::Raised => Self::Well,
271            other => other,
272        }
273    }
274}
275
276/// What a region is saying, when it is saying something.
277///
278/// The one intent family shared by badges, notices and nothing else. Kept
279/// separate from [`Fill`] because a surface is where a thing sits and a tone is
280/// what it means, and the three apps agree on the four statuses:
281/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
282/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
283/// `.toast.error` in Balanced Breakfast.
284///
285/// The per-tag palette (`category-one` through `category-six`) is deliberately
286/// not here. Which colour a *particular* tag takes is app domain, and both
287/// webview apps already carry it as a `data-color` attribute.
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
289pub enum Tone {
290    /// No status. Reads as ordinary de-emphasised content.
291    Neutral,
292    /// Something worth knowing and nothing to do about it.
293    Info,
294    /// Something finished and it worked.
295    Success,
296    /// Something the user should look at before continuing.
297    Warning,
298    /// Something broken, or something about to be destroyed.
299    Danger,
300}
301
302impl Intent for Tone {
303    fn token(self) -> &'static str {
304        match self {
305            // Neutral has no status token of its own. It takes the muted
306            // content intent, which is what both webview apps already spell as
307            // `data-color="muted"`.
308            Self::Neutral => "content-muted",
309            Self::Info => "info",
310            Self::Success => "success",
311            Self::Warning => "warning",
312            Self::Danger => "danger",
313        }
314    }
315}
316
317/// A small labelled thing that sits inside something else.
318///
319/// Two members, because the three apps drew three taxonomies and only one line
320/// runs through all of them: does it answer a click. audiofiles has
321/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
322/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
323/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
324/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
325/// to decide which of the two it always was.
326///
327/// The evidence that a chip is a real concept rather than a badge with a
328/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
329/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
330/// holds itself down", which is exactly what [`Depth::pressed`] already says.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
332pub enum Token {
333    /// Non-interactive status or count. Answers no click.
334    Badge,
335    /// An interactive or removable token. Answers a click, and latches if it
336    /// stands for a filter that is either on or off.
337    Chip {
338        /// Whether it carries its own remove affordance.
339        removable: bool,
340    },
341}
342
343impl Token {
344    /// Whether this answers a click.
345    ///
346    /// The whole difference between the two members, and the reason a renderer
347    /// with no hover (a touch surface, a terminal) can still tell them apart.
348    #[must_use]
349    pub const fn interactive(self) -> bool {
350        matches!(self, Self::Chip { .. })
351    }
352
353    /// How it sits, given whether it is currently latched down.
354    ///
355    /// A badge is flat: it is a label, and giving it an edge would say it can
356    /// be pressed. A chip is raised, and inset while latched.
357    #[must_use]
358    pub const fn depth(self, latched: bool) -> Depth {
359        match self {
360            Self::Badge => Depth::Flat,
361            Self::Chip { .. } if latched => Depth::Well,
362            Self::Chip { .. } => Depth::Raised,
363        }
364    }
365}
366
367/// Something the app is telling the user, unprompted.
368///
369/// Two concepts, not one with a placement. They differ in more than where they
370/// sit: a toast is transient, stacked and self-dismissing, and a banner is
371/// persistent, in flow, one per region, and dismissed by fixing the condition
372/// it reports. Folding them into one member with a placement parameter would
373/// make lifetime, stacking and dismissal all placement-dependent, which is the
374/// description leaking renderer policy.
375///
376/// All three apps have banners: `info_banner` and `warning_banner` in
377/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
378/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
379/// webview apps also have toasts. So neither member is speculative, and no app
380/// gains a concept it lacks except audiofiles, whose renderer may legitimately
381/// decline to draw a toast at all.
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
383pub enum Notice {
384    /// Transient, stacked, dismisses itself.
385    Toast,
386    /// Persistent, in flow, one per region, dismissed by fixing the cause.
387    Banner,
388}
389
390impl Notice {
391    /// Whether it goes away on its own.
392    #[must_use]
393    pub const fn transient(self) -> bool {
394        matches!(self, Self::Toast)
395    }
396
397    /// How it sits.
398    ///
399    /// A toast floats above the page rather than resting on it, which is
400    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
401    /// flow. Both are raised, and they are raised off different things.
402    #[must_use]
403    pub const fn fill(self) -> Fill {
404        match self {
405            Self::Toast => Fill::Overlay,
406            Self::Banner => Fill::Raised,
407        }
408    }
409}
410
411/// The parts of a list row.
412///
413/// Four, taken from Balanced Breakfast, which is the only consumer that had all
414/// of them (`row-primary`, `row-secondary`, `row-meta`, `row-actions`).
415/// audiofiles has two and no slot structure at all, so it gains meta and
416/// actions as real work rather than a rename; goingson moves off
417/// `task-row` / `task-cell`.
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
419pub enum RowPart {
420    /// The thing itself. What the row is called.
421    Primary,
422    /// Supporting text under the primary.
423    Secondary,
424    /// A short trailing fact: a count, a size, a date.
425    Meta,
426    /// Controls that act on this row.
427    Actions,
428}
429
430impl RowPart {
431    /// Whether the part stays hidden until the row is hovered or focused.
432    ///
433    /// Behaviour of the part, not app policy: Balanced Breakfast and goingson
434    /// grew the same hover-reveal on their actions independently and neither
435    /// applies it to anything else.
436    ///
437    /// A renderer with no hover shows it always. That is a renderer decision
438    /// and this returning `true` does not forbid it.
439    #[must_use]
440    pub const fn revealed_on_hover(self) -> bool {
441        matches!(self, Self::Actions)
442    }
443
444    /// The content intent the part takes.
445    #[must_use]
446    pub const fn intent(self) -> &'static str {
447        match self {
448            Self::Primary => "content",
449            Self::Secondary => "content-secondary",
450            Self::Meta => "content-muted",
451            // Actions carry controls rather than text, so they inherit.
452            Self::Actions => "content",
453        }
454    }
455}
456
457/// How far down the heading tree a title sits.
458///
459/// Three, and only the three that are actually headings. The bands those used
460/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
461/// and `.detail-header`) are arrangement, not type, and live at
462/// [`Region::Band`]. One of them contains no text at all.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
464pub enum Heading {
465    /// Names the whole screen. One per screen.
466    Page,
467    /// Names a block within the screen.
468    Section,
469    /// Names a sub-block inside an already-named section.
470    Subsection,
471}
472
473impl Heading {
474    /// Whether a rule follows the heading.
475    ///
476    /// audiofiles' `section_header` draws a separator and its
477    /// `subsection_label` deliberately does not, which is the only thing
478    /// distinguishing the two once weight and colour are deferred.
479    #[must_use]
480    pub const fn separated(self) -> bool {
481        matches!(self, Self::Section)
482    }
483}
484
485/// A control that picks between things.
486///
487/// Three, because three distinct behaviours are in play and collapsing any two
488/// loses something. A segmented control picks a value; a tab picks a pane; a
489/// toggle picks nothing and simply holds itself on or off.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub enum Selector {
492    /// Exactly one of N, and the options abut.
493    Segmented,
494    /// Independent on or off, on its own.
495    Toggle,
496    /// Navigation between panes. The folder semantic.
497    Tabs,
498}
499
500impl Selector {
501    /// How the chosen option sits.
502    ///
503    /// Held in for a segmented control and a toggle, which is the same shape
504    /// pressing produces and the whole economy of the idiom: one appearance,
505    /// two reasons to wear it. A tab is the exception, because the selected
506    /// folder tab comes *forward* to join the pane it opens.
507    #[must_use]
508    pub const fn chosen(self) -> Depth {
509        match self {
510            Self::Segmented | Self::Toggle => Depth::Well,
511            Self::Tabs => Depth::Raised,
512        }
513    }
514
515    /// How the options that were *not* picked sit.
516    ///
517    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
518    /// option falling through to [`Depth::Flat`], which says it is level with
519    /// the strip it sits in, and no renderer emitted anything for it. That is
520    /// wrong in both directions and goingson proved it: its unchosen tabs are
521    /// recessed by hand, and being recessed is *why* the chosen one reads as
522    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
523    /// drawn on the strip's own colour, which is a much weaker folder effect
524    /// than the contrast the idiom is named after.
525    ///
526    /// Each member is the inverse of its chosen state, which is the whole
527    /// content of "picked" once colour is deferred:
528    ///
529    /// - Tabs recede, so the chosen one comes forward.
530    /// - A segment and a toggle stand up, so the chosen one is held in.
531    #[must_use]
532    pub const fn unchosen(self) -> Depth {
533        match self {
534            Self::Tabs => Depth::Sunken,
535            Self::Segmented | Self::Toggle => Depth::Raised,
536        }
537    }
538
539    /// Whether the options touch.
540    ///
541    /// The gap is the entire difference between a segmented control and a row
542    /// of buttons that happen to sit near each other, which is what audiofiles'
543    /// `segmented_control` says in its own comment and why it zeroes the
544    /// spacing by hand.
545    #[must_use]
546    pub const fn abutting(self) -> bool {
547        matches!(self, Self::Segmented | Self::Tabs)
548    }
549}
550
551/// Whether the content of a region has arrived.
552///
553/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
554/// nothing at all is renderer policy, the same class of decision that got
555/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
556/// each grew a skeleton with differently-named parts; both keep them, as the
557/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
558/// and needs none, because an immediate-mode renderer simply repaints.
559#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
560pub enum Readiness {
561    /// The content is here.
562    Ready,
563    /// The content is on its way.
564    Pending,
565}
566
567/// A named part of a screen.
568///
569/// The thing `makeover-geometry` deliberately does not name: it names the space
570/// *between* things by relationship, and nothing named the things. Six named
571/// members, taken from what the two webview apps actually use, plus
572/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
573/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
574/// this layer is absent rather than divergent, which makes it the cheapest of
575/// the schemas to add and the easiest to over-build.
576#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
577pub enum Region<'a> {
578    /// A full-width strip with a title slot and an actions cluster, either of
579    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
580    /// `.header` and `.detail-header` are all this, differing only in which
581    /// slots they fill.
582    Band,
583    /// A persistent column beside the content, holding navigation.
584    Sidebar,
585    /// A region of content with its own scroll.
586    Pane,
587    /// Two panes side by side, where the left chooses what the right shows.
588    Split,
589    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
590    TabGroup,
591    /// Content over a scrim, taking input until dismissed.
592    Modal,
593    /// A region this crate names the *place* of and nothing else. The app owns
594    /// what goes in it.
595    ///
596    /// The escape hatch, and the thing that keeps the description honest about
597    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
598    /// paint interaction over the timeline are not describable here and are not
599    /// going to become describable: a description expressive enough to produce
600    /// a timeline is a widget library wearing a description's name.
601    ///
602    /// But a screen containing one still has to be a screen. Without this
603    /// member the description covers only the boring screens, and the four that
604    /// make goingson worth using would need a second, undescribed path beside
605    /// the router. Two paths is how the vocabulary starts drifting from the app
606    /// again, which is the exact failure this crate exists to end.
607    ///
608    /// So the description says "a thing called `day-plan` goes here" and stops.
609    /// The name is opaque: this crate never interprets it, and no renderer is
610    /// expected to know what it means beyond handing the space over.
611    Bespoke {
612        /// What the app calls it. Never interpreted here.
613        name: &'a str,
614    },
615}
616
617impl Region<'_> {
618    /// How the region sits on what is behind it.
619    #[must_use]
620    pub const fn depth(self) -> Depth {
621        match self {
622            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
623            // A pane is looked into, the same as a table body or a tag tree.
624            Self::Pane => Depth::Well,
625            Self::Modal => Depth::Raised,
626            // Flat because it inherits: a bespoke region takes the depth of
627            // whatever frames it. An app that wants its timeline in a well puts
628            // it in a `Pane`, which composes rather than adding a knob here.
629            Self::Bespoke { .. } => Depth::Flat,
630        }
631    }
632
633    /// Whether this crate can say anything about the region's contents.
634    ///
635    /// A renderer walks the description and hands every region it understands
636    /// to the right drawing code. This is how it tells the two apart, and the
637    /// reason it is a method rather than a `matches!` at each renderer: there
638    /// is exactly one opaque member and there should stay exactly one.
639    #[must_use]
640    pub const fn described(self) -> bool {
641        !matches!(self, Self::Bespoke { .. })
642    }
643}
644
645/// How a screen is laid out.
646///
647/// Two, and the second is not a variant of the first. goingson is list-detail,
648/// Balanced Breakfast is sidebar plus content, and neither app has a third.
649/// The tab group is a modifier rather than a member, because goingson uses it
650/// *inside* the same content region rather than instead of one.
651///
652/// This exists at all because the router has to be able to express a screen
653/// rather than only a control. Discovering the arrangement layer missing after
654/// the renderers exist is a redesign; naming two now is a morning.
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
656pub enum Arrangement {
657    /// A list that chooses what the detail beside it shows.
658    ListDetail {
659        /// Whether the detail side is a [`Region::TabGroup`].
660        tabbed: bool,
661    },
662    /// Navigation down the side, content filling the rest.
663    SidebarContent,
664}
665
666/// What kind of value a form field takes.
667///
668/// The union of the two vocabularies that diverged, which is what triggered
669/// this crate. They have since converged on their own: both apps now have a
670/// `renderFormField` emitting the same anatomy, and what is left differing is
671/// the kind set, the error shape, and whether the return is a string or a node.
672///
673/// Validation is deliberately absent. Neither app has a shared story (goingson
674/// validates after collecting the form data, with per-field transform hooks;
675/// Balanced Breakfast has `required` and nothing else), and a schema that
676/// describes fields but not constraints acquires a constraint layer per app,
677/// which is exactly how the current divergence started. Naming it absent is a
678/// decision; leaving it unmentioned would not be.
679/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
680/// the set keeps growing, so growth must not be a lockstep event. Email, Url
681/// and Tel arriving in 0.5.0 is the second growth in two releases.
682#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
683#[non_exhaustive]
684pub enum FieldKind {
685    /// A single line of text.
686    Text,
687    /// A single line of text that must never be echoed, logged or round-tripped
688    /// through anything that might persist it.
689    Secret,
690    /// A number.
691    Number,
692    /// An email address.
693    ///
694    /// Distinct from [`Text`](Self::Text) because the distinction is not
695    /// decoration: a webview renderer emits `type="email"`, which on a touch
696    /// device changes the keyboard that appears and turns on the platform's own
697    /// validation. goingson ships to iOS, so collapsing this into text costs a
698    /// keyboard with no `@` on it.
699    ///
700    /// Added 0.5.0, from goingson's contact form.
701    Email,
702    /// A URL. Same reasoning as [`Email`](Self::Email).
703    ///
704    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
705    Url,
706    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
707    /// clearest case of it: the keyboard is a numeric pad rather than letters.
708    ///
709    /// Added 0.5.0, from goingson's contact-phone form.
710    Tel,
711    /// Several lines of text.
712    Textarea,
713    /// One of a fixed set.
714    Select,
715    /// On or off.
716    Checkbox,
717    /// Carried through the form and never shown.
718    Hidden,
719}
720
721impl FieldKind {
722    /// Whether the field is drawn at all.
723    #[must_use]
724    pub const fn visible(self) -> bool {
725        !matches!(self, Self::Hidden)
726    }
727
728    /// Whether the value must be kept out of logs and diagnostics.
729    #[must_use]
730    pub const fn confidential(self) -> bool {
731        matches!(self, Self::Secret)
732    }
733
734    /// Where the field's own label sits.
735    ///
736    /// A checkbox labels itself on the right of the box; everything else takes
737    /// a label above. Both webview apps already do this and both special-case
738    /// it inline, which is the tell that it belongs in the description.
739    #[must_use]
740    pub const fn labels_itself(self) -> bool {
741        matches!(self, Self::Checkbox)
742    }
743}
744
745/// One field of a form.
746///
747/// Borrowed rather than owned: a description is built, read once by a renderer,
748/// and dropped. Nothing here outlives the screen it describes.
749#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
750pub struct Field<'a> {
751    /// What kind of value it takes.
752    pub kind: FieldKind,
753    /// The name the value is submitted under.
754    pub name: &'a str,
755    /// What the user is asked for.
756    pub label: &'a str,
757    /// Standing help, shown whether or not anything is wrong.
758    pub hint: Option<&'a str>,
759    /// What is currently wrong with the value.
760    pub error: Option<&'a str>,
761    /// Whether the form refuses to submit without it.
762    pub required: bool,
763    /// Whether the field lives behind a "more options" disclosure.
764    pub extended: bool,
765}
766
767impl<'a> Field<'a> {
768    /// A plain required-nothing field of the given kind.
769    #[must_use]
770    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
771        Self {
772            kind,
773            name,
774            label,
775            hint: None,
776            error: None,
777            required: false,
778            extended: false,
779        }
780    }
781
782    /// Whether the field is currently reporting a problem.
783    ///
784    /// Read this rather than testing `error.is_some()` at each renderer: the
785    /// error state has to mark the field's whole group and not only the
786    /// message, because a renderer with no descendant selectors (egui, a
787    /// terminal) cannot find the group from the message. goingson already marks
788    /// the group and Balanced Breakfast does not, so goingson's shape is the
789    /// one taken here.
790    #[must_use]
791    pub const fn invalid(&self) -> bool {
792        self.error.is_some()
793    }
794}
795
796/// How much room a column asks for.
797///
798/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
799/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
800/// only the first three words of that survive deferral.
801/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
802/// renderer matches on this and a vocabulary that grows must not break every
803/// renderer when it does.
804#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
805#[non_exhaustive]
806pub enum Width {
807    /// Takes what it needs and no more.
808    Content,
809    /// A fixed share, the same at every width.
810    Fixed,
811    /// Absorbs whatever is left over.
812    Fill,
813}
814
815/// What a column is worth when there is not room for all of them.
816///
817/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
818/// drops. This replaces addressing columns by position, which is what both
819/// webview apps do today and is a live bug rather than only verbosity. goingson
820/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
821/// inserting a column silently hides the wrong one.
822/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
823/// whole point of the type, so a new tier has to be declared in its place in
824/// the sequence rather than appended.
825#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
826#[non_exhaustive]
827pub enum Priority {
828    /// Dropped first.
829    Optional,
830    /// Dropped once the optional columns are gone.
831    Secondary,
832    /// Never dropped. Without it the row does not identify itself.
833    Essential,
834}
835
836/// One column of a table.
837///
838/// Described once. The grid track, the cell order and the drop behaviour are
839/// all derived from this, rather than being three hand-written encodings that
840/// must agree and are never checked against each other.
841#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
842pub struct Column<'a> {
843    /// The heading, and the name the cell is addressed by.
844    pub name: &'a str,
845    /// How much room it asks for.
846    pub width: Width,
847    /// What it is worth when room runs out.
848    pub priority: Priority,
849}
850
851impl<'a> Column<'a> {
852    /// A column that absorbs slack and drops after the optional ones.
853    #[must_use]
854    pub const fn new(name: &'a str) -> Self {
855        Self {
856            name,
857            width: Width::Fill,
858            priority: Priority::Secondary,
859        }
860    }
861
862    /// Whether this column survives at the given cutoff.
863    ///
864    /// A renderer narrows by raising the cutoff, and never by counting
865    /// positions.
866    #[must_use]
867    pub const fn kept_at(&self, cutoff: Priority) -> bool {
868        (self.priority as u8) >= (cutoff as u8)
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875
876    #[test]
877    fn inset_is_raised_with_the_light_moved() {
878        let (rl, rd) = Bevel::Raised.edges();
879        let (il, id) = Bevel::Inset.edges();
880        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
881        assert_eq!((il, id), (rd, rl));
882    }
883
884    #[test]
885    fn pressing_twice_is_a_no_op() {
886        for b in [Bevel::Raised, Bevel::Inset] {
887            assert_eq!(b.pressed().pressed(), b);
888        }
889    }
890
891    #[test]
892    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
893        // The bug this vocabulary exists to make unrepresentable.
894        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
895        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
896        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
897        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
898    }
899
900    #[test]
901    fn flat_has_neither_edge_nor_fill() {
902        assert_eq!(Depth::Flat.bevel(), None);
903        assert_eq!(Depth::Flat.fill(), None);
904    }
905
906    #[test]
907    fn sunken_is_recessed_by_colour_with_no_edge() {
908        // The one member carrying a fill without a bevel. A renderer that
909        // assumes the two arrive together drops the fill silently, which is
910        // exactly what makeover-webview did before 0.3.0.
911        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
912        assert_eq!(Depth::Sunken.bevel(), None);
913    }
914
915    #[test]
916    fn sunken_and_flat_are_different_claims() {
917        // Both edgeless, and only one of them needs a colour. Collapsing them
918        // is what left an unchosen tab unsayable.
919        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
920        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
921    }
922
923    #[test]
924    fn a_sunken_surface_is_not_a_well() {
925        // Authored in opposite directions: makeover derives surface-well by
926        // inverting against the theme's content colour, while surface-sunken is
927        // authored and may sit darker than raised.
928        assert_ne!(Fill::Sunken, Fill::Well);
929        assert_eq!(Fill::Sunken.token(), "surface-sunken");
930        assert_eq!(Fill::Well.token(), "surface-well");
931    }
932
933    #[test]
934    fn every_selector_describes_both_of_its_states() {
935        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
936        // unchosen option fell through to Flat at every renderer.
937        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
938            assert_ne!(
939                s.chosen(),
940                s.unchosen(),
941                "{s:?} cannot tell picked from unpicked"
942            );
943        }
944    }
945
946    #[test]
947    fn only_a_tab_inverts_the_other_way() {
948        // Tabs recede so the chosen one comes forward; a segment and a toggle
949        // stand up so the chosen one is held in. That inversion is the whole
950        // content of "picked" once colour is deferred, and it is why the three
951        // are not one member with a flag.
952        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
953        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
954
955        for s in [Selector::Segmented, Selector::Toggle] {
956            assert_eq!(s.unchosen(), Depth::Raised);
957            assert_eq!(s.chosen(), Depth::Well);
958            // Held in is what pressing produces: one appearance, two reasons.
959            assert_eq!(s.unchosen().pressed(), s.chosen());
960        }
961    }
962
963    #[test]
964    fn pressing_a_card_makes_a_well() {
965        assert_eq!(Depth::Raised.pressed(), Depth::Well);
966        assert_eq!(
967            Depth::Raised.pressed().bevel(),
968            Depth::Raised.bevel().map(Bevel::pressed)
969        );
970        // Only raised regions respond to being pressed.
971        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
972        assert_eq!(Depth::Well.pressed(), Depth::Well);
973    }
974
975    #[test]
976    fn intents_name_makeover_tokens_and_nothing_else() {
977        assert_eq!(Edge::Light.token(), "bevel-light");
978        assert_eq!(Edge::Dark.token(), "bevel-dark");
979        assert_eq!(Fill::Raised.token(), "surface-raised");
980        assert_eq!(Fill::Well.token(), "surface-well");
981        // No value ever leaves this crate.
982        for t in [
983            Edge::Light.token(),
984            Edge::Dark.token(),
985            Tone::Danger.token(),
986            Tone::Neutral.token(),
987        ] {
988            assert!(!t.starts_with('#'), "{t} looks like a value");
989            assert!(
990                !t.chars().next().unwrap().is_ascii_digit(),
991                "{t} is a value"
992            );
993        }
994    }
995
996    #[test]
997    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
998        // The one line that runs through all three apps' taxonomies.
999        assert!(!Token::Badge.interactive());
1000        assert!(Token::Chip { removable: false }.interactive());
1001        assert!(Token::Chip { removable: true }.interactive());
1002
1003        // A badge is a label, so giving it an edge would lie about it.
1004        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1005        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1006
1007        // A latched chip wears the same shape a pressed one does.
1008        let chip = Token::Chip { removable: false };
1009        assert_eq!(chip.depth(false), Depth::Raised);
1010        assert_eq!(chip.depth(true), Depth::Raised.pressed());
1011    }
1012
1013    #[test]
1014    fn a_toast_and_a_banner_differ_in_more_than_placement() {
1015        assert!(Notice::Toast.transient());
1016        assert!(!Notice::Banner.transient());
1017        // A toast floats above the page; a banner rests in the flow.
1018        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1019        assert_eq!(Notice::Banner.fill(), Fill::Raised);
1020    }
1021
1022    #[test]
1023    fn only_the_actions_part_hides_until_hovered() {
1024        for p in [RowPart::Primary, RowPart::Secondary, RowPart::Meta] {
1025            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
1026        }
1027        assert!(RowPart::Actions.revealed_on_hover());
1028        // Emphasis falls off down the row, and never rises again.
1029        assert_eq!(RowPart::Primary.intent(), "content");
1030        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
1031        assert_eq!(RowPart::Meta.intent(), "content-muted");
1032    }
1033
1034    #[test]
1035    fn a_separator_is_what_tells_a_section_from_a_subsection() {
1036        assert!(Heading::Section.separated());
1037        assert!(!Heading::Subsection.separated());
1038        assert!(!Heading::Page.separated());
1039    }
1040
1041    #[test]
1042    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
1043        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1044        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1045        // The exception, and the whole folder semantic: the open tab joins its
1046        // pane rather than sinking away from it.
1047        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1048
1049        // A held-in segment is indistinguishable from a pressed raised one,
1050        // which is the economy the light model buys over a colour swap.
1051        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
1052
1053        // A toggle stands alone; the other two are built out of parts that
1054        // touch.
1055        assert!(Selector::Segmented.abutting());
1056        assert!(Selector::Tabs.abutting());
1057        assert!(!Selector::Toggle.abutting());
1058    }
1059
1060    #[test]
1061    fn a_pane_is_looked_into_and_a_band_is_not() {
1062        assert_eq!(Region::Pane.depth(), Depth::Well);
1063        assert_eq!(Region::Modal.depth(), Depth::Raised);
1064        for r in [
1065            Region::Band,
1066            Region::Sidebar,
1067            Region::Split,
1068            Region::TabGroup,
1069        ] {
1070            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
1071        }
1072    }
1073
1074    #[test]
1075    fn exactly_one_region_is_opaque() {
1076        // The escape hatch is one member and stays one member. If a second
1077        // undescribed region ever appears, the description has started
1078        // conceding rather than deferring.
1079        for r in [
1080            Region::Band,
1081            Region::Sidebar,
1082            Region::Pane,
1083            Region::Split,
1084            Region::TabGroup,
1085            Region::Modal,
1086        ] {
1087            assert!(r.described(), "{r:?} should be describable");
1088        }
1089        assert!(!Region::Bespoke { name: "day-plan" }.described());
1090    }
1091
1092    #[test]
1093    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
1094        // The app owns the contents, not the placement. An app that wants its
1095        // timeline in a well frames it in a Pane.
1096        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
1097        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
1098    }
1099
1100    #[test]
1101    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
1102        // The argument the member exists for: goingson's day-plan has to be
1103        // routable, or the description covers only the boring screens and the
1104        // interesting four need a second path beside the router.
1105        let day_plan = [
1106            Region::Band,
1107            Region::Bespoke { name: "day-plan" },
1108            Region::Sidebar,
1109        ];
1110        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
1111        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
1112    }
1113
1114    #[test]
1115    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
1116        let secret = Field::new(FieldKind::Secret, "password", "Password");
1117        assert!(secret.kind.confidential());
1118        assert!(secret.kind.visible());
1119
1120        assert!(!FieldKind::Hidden.visible());
1121        // Nothing else is confidential, or the marker means nothing.
1122        for k in [
1123            FieldKind::Text,
1124            FieldKind::Number,
1125            FieldKind::Textarea,
1126            FieldKind::Select,
1127            FieldKind::Checkbox,
1128            FieldKind::Hidden,
1129        ] {
1130            assert!(!k.confidential(), "{k:?} should not be confidential");
1131        }
1132
1133        // Only a checkbox carries its own label.
1134        assert!(FieldKind::Checkbox.labels_itself());
1135        assert!(!FieldKind::Text.labels_itself());
1136    }
1137
1138    #[test]
1139    fn a_field_reports_its_own_error_state() {
1140        let mut f = Field::new(FieldKind::Text, "title", "Title");
1141        assert!(!f.invalid());
1142        f.error = Some("Required");
1143        assert!(f.invalid());
1144    }
1145
1146    #[test]
1147    fn columns_drop_by_priority_and_never_by_position() {
1148        let cols = [
1149            Column {
1150                name: "Title",
1151                width: Width::Fill,
1152                priority: Priority::Essential,
1153            },
1154            Column {
1155                name: "Due",
1156                width: Width::Fixed,
1157                priority: Priority::Secondary,
1158            },
1159            Column {
1160                name: "Estimate",
1161                width: Width::Fixed,
1162                priority: Priority::Optional,
1163            },
1164        ];
1165
1166        // Widest: everything survives.
1167        assert_eq!(
1168            cols.iter()
1169                .filter(|c| c.kept_at(Priority::Optional))
1170                .count(),
1171            3
1172        );
1173        // Narrower: the optional column goes first.
1174        let kept: Vec<_> = cols
1175            .iter()
1176            .filter(|c| c.kept_at(Priority::Secondary))
1177            .map(|c| c.name)
1178            .collect();
1179        assert_eq!(kept, ["Title", "Due"]);
1180        // Narrowest: only what identifies the row.
1181        let kept: Vec<_> = cols
1182            .iter()
1183            .filter(|c| c.kept_at(Priority::Essential))
1184            .map(|c| c.name)
1185            .collect();
1186        assert_eq!(kept, ["Title"]);
1187    }
1188
1189    #[test]
1190    fn inserting_a_column_does_not_move_what_gets_dropped() {
1191        // The bug the ordinal form has and this form cannot: goingson hides
1192        // `nth-child(n+5)` against a seven-column table, so a column inserted
1193        // anywhere to the left silently hides a different one.
1194        let before = [
1195            Column::new("Title"),
1196            Column {
1197                name: "Estimate",
1198                width: Width::Fixed,
1199                priority: Priority::Optional,
1200            },
1201        ];
1202        let after = [
1203            Column::new("Title"),
1204            Column::new("Project"), // inserted
1205            Column {
1206                name: "Estimate",
1207                width: Width::Fixed,
1208                priority: Priority::Optional,
1209            },
1210        ];
1211
1212        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
1213            cols.iter()
1214                .filter(|c| !c.kept_at(Priority::Secondary))
1215                .map(|c| c.name)
1216                .collect()
1217        }
1218        assert_eq!(dropped(&before), ["Estimate"]);
1219        assert_eq!(dropped(&after), ["Estimate"]);
1220    }
1221
1222    #[test]
1223    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
1224        // goingson uses the tab group inside the content region rather than
1225        // instead of one, so it is not a third arrangement.
1226        let go = Arrangement::ListDetail { tabbed: true };
1227        let plain = Arrangement::ListDetail { tabbed: false };
1228        assert_ne!(go, plain);
1229        assert_ne!(go, Arrangement::SidebarContent);
1230    }
1231
1232    #[test]
1233    fn readiness_names_the_state_and_not_the_shimmer() {
1234        // Two members and no third. If a skeleton ever appears in this enum,
1235        // the deferral rule has been broken.
1236        assert_ne!(Readiness::Ready, Readiness::Pending);
1237    }
1238}