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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
802pub enum Width {
803    /// Takes what it needs and no more.
804    Content,
805    /// A fixed share, the same at every width.
806    Fixed,
807    /// Absorbs whatever is left over.
808    Fill,
809}
810
811/// What a column is worth when there is not room for all of them.
812///
813/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
814/// drops. This replaces addressing columns by position, which is what both
815/// webview apps do today and is a live bug rather than only verbosity. goingson
816/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
817/// inserting a column silently hides the wrong one.
818#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
819pub enum Priority {
820    /// Dropped first.
821    Optional,
822    /// Dropped once the optional columns are gone.
823    Secondary,
824    /// Never dropped. Without it the row does not identify itself.
825    Essential,
826}
827
828/// One column of a table.
829///
830/// Described once. The grid track, the cell order and the drop behaviour are
831/// all derived from this, rather than being three hand-written encodings that
832/// must agree and are never checked against each other.
833#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
834pub struct Column<'a> {
835    /// The heading, and the name the cell is addressed by.
836    pub name: &'a str,
837    /// How much room it asks for.
838    pub width: Width,
839    /// What it is worth when room runs out.
840    pub priority: Priority,
841}
842
843impl<'a> Column<'a> {
844    /// A column that absorbs slack and drops after the optional ones.
845    #[must_use]
846    pub const fn new(name: &'a str) -> Self {
847        Self {
848            name,
849            width: Width::Fill,
850            priority: Priority::Secondary,
851        }
852    }
853
854    /// Whether this column survives at the given cutoff.
855    ///
856    /// A renderer narrows by raising the cutoff, and never by counting
857    /// positions.
858    #[must_use]
859    pub const fn kept_at(&self, cutoff: Priority) -> bool {
860        (self.priority as u8) >= (cutoff as u8)
861    }
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    #[test]
869    fn inset_is_raised_with_the_light_moved() {
870        let (rl, rd) = Bevel::Raised.edges();
871        let (il, id) = Bevel::Inset.edges();
872        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
873        assert_eq!((il, id), (rd, rl));
874    }
875
876    #[test]
877    fn pressing_twice_is_a_no_op() {
878        for b in [Bevel::Raised, Bevel::Inset] {
879            assert_eq!(b.pressed().pressed(), b);
880        }
881    }
882
883    #[test]
884    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
885        // The bug this vocabulary exists to make unrepresentable.
886        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
887        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
888        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
889        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
890    }
891
892    #[test]
893    fn flat_has_neither_edge_nor_fill() {
894        assert_eq!(Depth::Flat.bevel(), None);
895        assert_eq!(Depth::Flat.fill(), None);
896    }
897
898    #[test]
899    fn sunken_is_recessed_by_colour_with_no_edge() {
900        // The one member carrying a fill without a bevel. A renderer that
901        // assumes the two arrive together drops the fill silently, which is
902        // exactly what makeover-webview did before 0.3.0.
903        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
904        assert_eq!(Depth::Sunken.bevel(), None);
905    }
906
907    #[test]
908    fn sunken_and_flat_are_different_claims() {
909        // Both edgeless, and only one of them needs a colour. Collapsing them
910        // is what left an unchosen tab unsayable.
911        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
912        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
913    }
914
915    #[test]
916    fn a_sunken_surface_is_not_a_well() {
917        // Authored in opposite directions: makeover derives surface-well by
918        // inverting against the theme's content colour, while surface-sunken is
919        // authored and may sit darker than raised.
920        assert_ne!(Fill::Sunken, Fill::Well);
921        assert_eq!(Fill::Sunken.token(), "surface-sunken");
922        assert_eq!(Fill::Well.token(), "surface-well");
923    }
924
925    #[test]
926    fn every_selector_describes_both_of_its_states() {
927        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
928        // unchosen option fell through to Flat at every renderer.
929        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
930            assert_ne!(
931                s.chosen(),
932                s.unchosen(),
933                "{s:?} cannot tell picked from unpicked"
934            );
935        }
936    }
937
938    #[test]
939    fn only_a_tab_inverts_the_other_way() {
940        // Tabs recede so the chosen one comes forward; a segment and a toggle
941        // stand up so the chosen one is held in. That inversion is the whole
942        // content of "picked" once colour is deferred, and it is why the three
943        // are not one member with a flag.
944        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
945        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
946
947        for s in [Selector::Segmented, Selector::Toggle] {
948            assert_eq!(s.unchosen(), Depth::Raised);
949            assert_eq!(s.chosen(), Depth::Well);
950            // Held in is what pressing produces: one appearance, two reasons.
951            assert_eq!(s.unchosen().pressed(), s.chosen());
952        }
953    }
954
955    #[test]
956    fn pressing_a_card_makes_a_well() {
957        assert_eq!(Depth::Raised.pressed(), Depth::Well);
958        assert_eq!(
959            Depth::Raised.pressed().bevel(),
960            Depth::Raised.bevel().map(Bevel::pressed)
961        );
962        // Only raised regions respond to being pressed.
963        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
964        assert_eq!(Depth::Well.pressed(), Depth::Well);
965    }
966
967    #[test]
968    fn intents_name_makeover_tokens_and_nothing_else() {
969        assert_eq!(Edge::Light.token(), "bevel-light");
970        assert_eq!(Edge::Dark.token(), "bevel-dark");
971        assert_eq!(Fill::Raised.token(), "surface-raised");
972        assert_eq!(Fill::Well.token(), "surface-well");
973        // No value ever leaves this crate.
974        for t in [
975            Edge::Light.token(),
976            Edge::Dark.token(),
977            Tone::Danger.token(),
978            Tone::Neutral.token(),
979        ] {
980            assert!(!t.starts_with('#'), "{t} looks like a value");
981            assert!(
982                !t.chars().next().unwrap().is_ascii_digit(),
983                "{t} is a value"
984            );
985        }
986    }
987
988    #[test]
989    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
990        // The one line that runs through all three apps' taxonomies.
991        assert!(!Token::Badge.interactive());
992        assert!(Token::Chip { removable: false }.interactive());
993        assert!(Token::Chip { removable: true }.interactive());
994
995        // A badge is a label, so giving it an edge would lie about it.
996        assert_eq!(Token::Badge.depth(false), Depth::Flat);
997        assert_eq!(Token::Badge.depth(true), Depth::Flat);
998
999        // A latched chip wears the same shape a pressed one does.
1000        let chip = Token::Chip { removable: false };
1001        assert_eq!(chip.depth(false), Depth::Raised);
1002        assert_eq!(chip.depth(true), Depth::Raised.pressed());
1003    }
1004
1005    #[test]
1006    fn a_toast_and_a_banner_differ_in_more_than_placement() {
1007        assert!(Notice::Toast.transient());
1008        assert!(!Notice::Banner.transient());
1009        // A toast floats above the page; a banner rests in the flow.
1010        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1011        assert_eq!(Notice::Banner.fill(), Fill::Raised);
1012    }
1013
1014    #[test]
1015    fn only_the_actions_part_hides_until_hovered() {
1016        for p in [RowPart::Primary, RowPart::Secondary, RowPart::Meta] {
1017            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
1018        }
1019        assert!(RowPart::Actions.revealed_on_hover());
1020        // Emphasis falls off down the row, and never rises again.
1021        assert_eq!(RowPart::Primary.intent(), "content");
1022        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
1023        assert_eq!(RowPart::Meta.intent(), "content-muted");
1024    }
1025
1026    #[test]
1027    fn a_separator_is_what_tells_a_section_from_a_subsection() {
1028        assert!(Heading::Section.separated());
1029        assert!(!Heading::Subsection.separated());
1030        assert!(!Heading::Page.separated());
1031    }
1032
1033    #[test]
1034    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
1035        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1036        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1037        // The exception, and the whole folder semantic: the open tab joins its
1038        // pane rather than sinking away from it.
1039        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1040
1041        // A held-in segment is indistinguishable from a pressed raised one,
1042        // which is the economy the light model buys over a colour swap.
1043        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
1044
1045        // A toggle stands alone; the other two are built out of parts that
1046        // touch.
1047        assert!(Selector::Segmented.abutting());
1048        assert!(Selector::Tabs.abutting());
1049        assert!(!Selector::Toggle.abutting());
1050    }
1051
1052    #[test]
1053    fn a_pane_is_looked_into_and_a_band_is_not() {
1054        assert_eq!(Region::Pane.depth(), Depth::Well);
1055        assert_eq!(Region::Modal.depth(), Depth::Raised);
1056        for r in [
1057            Region::Band,
1058            Region::Sidebar,
1059            Region::Split,
1060            Region::TabGroup,
1061        ] {
1062            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
1063        }
1064    }
1065
1066    #[test]
1067    fn exactly_one_region_is_opaque() {
1068        // The escape hatch is one member and stays one member. If a second
1069        // undescribed region ever appears, the description has started
1070        // conceding rather than deferring.
1071        for r in [
1072            Region::Band,
1073            Region::Sidebar,
1074            Region::Pane,
1075            Region::Split,
1076            Region::TabGroup,
1077            Region::Modal,
1078        ] {
1079            assert!(r.described(), "{r:?} should be describable");
1080        }
1081        assert!(!Region::Bespoke { name: "day-plan" }.described());
1082    }
1083
1084    #[test]
1085    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
1086        // The app owns the contents, not the placement. An app that wants its
1087        // timeline in a well frames it in a Pane.
1088        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
1089        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
1090    }
1091
1092    #[test]
1093    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
1094        // The argument the member exists for: goingson's day-plan has to be
1095        // routable, or the description covers only the boring screens and the
1096        // interesting four need a second path beside the router.
1097        let day_plan = [
1098            Region::Band,
1099            Region::Bespoke { name: "day-plan" },
1100            Region::Sidebar,
1101        ];
1102        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
1103        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
1104    }
1105
1106    #[test]
1107    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
1108        let secret = Field::new(FieldKind::Secret, "password", "Password");
1109        assert!(secret.kind.confidential());
1110        assert!(secret.kind.visible());
1111
1112        assert!(!FieldKind::Hidden.visible());
1113        // Nothing else is confidential, or the marker means nothing.
1114        for k in [
1115            FieldKind::Text,
1116            FieldKind::Number,
1117            FieldKind::Textarea,
1118            FieldKind::Select,
1119            FieldKind::Checkbox,
1120            FieldKind::Hidden,
1121        ] {
1122            assert!(!k.confidential(), "{k:?} should not be confidential");
1123        }
1124
1125        // Only a checkbox carries its own label.
1126        assert!(FieldKind::Checkbox.labels_itself());
1127        assert!(!FieldKind::Text.labels_itself());
1128    }
1129
1130    #[test]
1131    fn a_field_reports_its_own_error_state() {
1132        let mut f = Field::new(FieldKind::Text, "title", "Title");
1133        assert!(!f.invalid());
1134        f.error = Some("Required");
1135        assert!(f.invalid());
1136    }
1137
1138    #[test]
1139    fn columns_drop_by_priority_and_never_by_position() {
1140        let cols = [
1141            Column {
1142                name: "Title",
1143                width: Width::Fill,
1144                priority: Priority::Essential,
1145            },
1146            Column {
1147                name: "Due",
1148                width: Width::Fixed,
1149                priority: Priority::Secondary,
1150            },
1151            Column {
1152                name: "Estimate",
1153                width: Width::Fixed,
1154                priority: Priority::Optional,
1155            },
1156        ];
1157
1158        // Widest: everything survives.
1159        assert_eq!(
1160            cols.iter()
1161                .filter(|c| c.kept_at(Priority::Optional))
1162                .count(),
1163            3
1164        );
1165        // Narrower: the optional column goes first.
1166        let kept: Vec<_> = cols
1167            .iter()
1168            .filter(|c| c.kept_at(Priority::Secondary))
1169            .map(|c| c.name)
1170            .collect();
1171        assert_eq!(kept, ["Title", "Due"]);
1172        // Narrowest: only what identifies the row.
1173        let kept: Vec<_> = cols
1174            .iter()
1175            .filter(|c| c.kept_at(Priority::Essential))
1176            .map(|c| c.name)
1177            .collect();
1178        assert_eq!(kept, ["Title"]);
1179    }
1180
1181    #[test]
1182    fn inserting_a_column_does_not_move_what_gets_dropped() {
1183        // The bug the ordinal form has and this form cannot: goingson hides
1184        // `nth-child(n+5)` against a seven-column table, so a column inserted
1185        // anywhere to the left silently hides a different one.
1186        let before = [
1187            Column::new("Title"),
1188            Column {
1189                name: "Estimate",
1190                width: Width::Fixed,
1191                priority: Priority::Optional,
1192            },
1193        ];
1194        let after = [
1195            Column::new("Title"),
1196            Column::new("Project"), // inserted
1197            Column {
1198                name: "Estimate",
1199                width: Width::Fixed,
1200                priority: Priority::Optional,
1201            },
1202        ];
1203
1204        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
1205            cols.iter()
1206                .filter(|c| !c.kept_at(Priority::Secondary))
1207                .map(|c| c.name)
1208                .collect()
1209        }
1210        assert_eq!(dropped(&before), ["Estimate"]);
1211        assert_eq!(dropped(&after), ["Estimate"]);
1212    }
1213
1214    #[test]
1215    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
1216        // goingson uses the tab group inside the content region rather than
1217        // instead of one, so it is not a third arrangement.
1218        let go = Arrangement::ListDetail { tabbed: true };
1219        let plain = Arrangement::ListDetail { tabbed: false };
1220        assert_ne!(go, plain);
1221        assert_ne!(go, Arrangement::SidebarContent);
1222    }
1223
1224    #[test]
1225    fn readiness_names_the_state_and_not_the_shimmer() {
1226        // Two members and no third. If a skeleton ever appears in this enum,
1227        // the deferral rule has been broken.
1228        assert_ne!(Readiness::Ready, Readiness::Pending);
1229    }
1230}