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