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