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** was absent on purpose here, on the grounds that neither app
44//! had a shared story. That reasoning is retired — see 0.11.0 below, which is
45//! where the constraints arrived and why the argument did not survive contact
46//! with what the apps were measured to do.
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//! 0.7.0 adds [`State`], the interaction axis, closing the gap that adopting
58//! against three apps rather than one made visible. The description named
59//! rest and, through [`Depth::pressed`], pressed. It named neither focus nor
60//! disabled, so `makeover-webview` emitted a hover rule and stopped, and each
61//! consumer completed the primitive from outside by out-specifying a rule it
62//! did not own: 19 such rules in goingson, 21 in the MNW server, a further set
63//! in Balanced Breakfast, and three focus rings that do not match. The axis is
64//! deliberately two members wide, because hover and pressed belong where they
65//! already are. [`State`]'s own docs carry that argument.
66//!
67//! 0.8.0 finishes [`Field`], which described a field well enough to label it and
68//! not well enough to draw it. Writing `makeover-webview`'s form emitter found
69//! three things missing and the renderer supplied all three from outside: the
70//! current value, a select's options, and the placeholder. Two of those move
71//! here and one does not.
72//!
73//! - [`Field::placeholder`] is user-facing text sitting beside `label` and
74//!   `hint`. There was never a reading on which it was renderer state; it was
75//!   outside only because adding a field to a published struct is breaking.
76//! - [`Field::options`] moves because every renderer needs them and each was
77//!   going to invent its own shape. [`Choice`] is the shape `makeover-webview`
78//!   already arrived at, taken as-is rather than redesigned.
79//! - The current value stays renderer-side and is not coming here. It is the
80//!   one of the three that is genuinely state: a webview reads it out of the
81//!   DOM, an immediate-mode renderer holds a `&mut` to the app's own field, and
82//!   a description that carried it would be a form model.
83//!
84//! 0.9.0 opens [`RowPart`], which was the last closed enum in the vocabulary,
85//! and adds [`RowPart::Tokens`]. Both halves come from the same finding, made
86//! by the first two real screens described through the router rather than by
87//! reading a stylesheet.
88//!
89//! A goingson project card carries two trailing badges, a type and a toned
90//! status; a contact card carries a primary email *and* a strip of tags. `Meta`
91//! is one slot and one string, so both ports joined their facts with a
92//! separator and lost what the second one was: a status reads as text where it
93//! used to read as colour. [`Token`] already says exactly the right thing — a
94//! small labelled thing with a kind, a tone and an optional action — and could
95//! only ever be a node in its own right, never inside a row.
96//!
97//! So the missing thing was permission rather than a concept. `Tokens` is that
98//! permission, and `#[non_exhaustive]` arrives with it so the next member is not
99//! a lockstep event across three renderers. The pairing is the point: this
100//! enum's own consumer in `makeover-webview` carried a comment predicting it
101//! would stop compiling one day, which is a lockstep break written down and
102//! waited for rather than prevented.
103//!
104//! Balanced Breakfast was checked before the member was added, because one
105//! consumer wanting something is not evidence. It packs a count and two icon
106//! buttons into the same single `Meta` slot while leaving `Actions` empty, so
107//! the slot was already straining under a second consumer for a different
108//! reason.
109//!
110//! 0.10.0 adds [`Meter`], a proportion carried as a pair rather than as a
111//! percentage. Its own docs carry the argument; the short form is that the
112//! percentage shape had already been tried in goingson and had already needed a
113//! companion flag to recover what rounding and clamping threw away.
114//!
115//! 0.11.0 is four members from the quasi proving ground, batched into one
116//! release because pre-1.0 a minor is breaking and a cascade is nine repos.
117//! Three findings that arrived with them turned out not to belong here at all:
118//! this crate has no notion of an action, a route or a destination, so anything
119//! asking what a control *calls* was never the vocabulary's to say.
120//!
121//! - [`Figure`], a value with a caption. goingson had five of them across five
122//!   screens with five class vocabularies for the one shape, which is the
123//!   divergence this crate exists to end, sitting in plain sight and counted for
124//!   the first time.
125//! - [`RowPart::Proportion`], so a [`Meter`] can sit in a row. `Meter` reached
126//!   two of its seven sites at 0.10.0 and the other five are row-shaped. Exactly
127//!   [`RowPart::Tokens`]'s problem with a different payload, and it takes
128//!   `Tokens`' answer: the part carries the description of a bar, not a node.
129//! - [`Field::max_length`], [`Field::min`] and [`Field::max`], joining
130//!   [`Field::required`], which had been sitting here as the sole constraint
131//!   while the header above claimed there were none. The set stops before
132//!   `pattern`, which fails the renderer test and is one site in one app.
133//! - [`FieldKind::File`]. Every host has an honest answer — a native picker, an
134//!   `<input type="file">`, a path prompt, an argument — and it carries no
135//!   accepted-types list because `accept` appears at zero sites in either app.
136//!
137//! The evidence rule changed under these, and it is worth recording because four
138//! earlier decisions were made under the old one. The two-app test said a shape
139//! earns a word once a second app wants it. It is backwards: a rule that
140//! withholds a word until a second app has duplicated the code guarantees the
141//! duplication, and app three writes it a third time. The bar is now generic
142//! against bespoke — is this furniture any app would have, or is it this app's
143//! own? Bespoke keeps [`Region::Bespoke`], which already carries a completion
144//! heatmap and is the right answer for a calendar nobody will build twice.
145//!
146//! 0.12.0 is two more from the same proving ground, and the same sorting
147//! happened first: six findings came out of a measurement of goingson's whole
148//! frontend, and four of them turned out to be asking what a control *calls*,
149//! which this crate cannot say. The two that were really here:
150//!
151//! - [`Readiness`] grows from two states to four. It named `Ready` and
152//!   `Pending` and stopped, so a screen whose list came back empty had nothing
153//!   to say about it; goingson draws an empty state at 27 sites and Balanced
154//!   Breakfast at 9. `Empty` and `Failed` are the same axis rather than a new
155//!   member beside it, because a region shows one of the four and never two.
156//!   `#[non_exhaustive]` arrives with them, the pairing [`RowPart`] made at
157//!   0.9.0 and for the same reason.
158//! - [`Column::sortable`], [`Column::sorted`] and [`Sort`]. The one finding in
159//!   the set that completes a member rather than adding one: `Column` shipped
160//!   with a width and a priority and could not say that a table is ordered by a
161//!   column, so a described table could draw no caret and offer no reordering.
162//!
163//! What each of those deliberately leaves out is the address — what pressing a
164//! header calls, and where an empty state's "Add your first project" button
165//! goes. That is the boundary this crate is defined by, and four findings moved
166//! across it rather than being answered here.
167//!
168//! # Where the description stops
169//!
170//! The bespoke widgets, a day-plan timeline and a kanban board and a calendar,
171//! are not describable here and will not become describable. A description
172//! expressive enough to produce a timeline is a widget library wearing a
173//! description's name. Generate the boring 80% so the bespoke 20% gets the
174//! attention.
175//!
176//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
177//! description names the *place* and the app owns the contents, so a screen
178//! containing a timeline is still a whole screen and still routable. Without
179//! it, the four goingson screens that make the app worth using would need a
180//! second, undescribed path beside the router, and two paths is how a
181//! vocabulary starts drifting from its app again.
182
183#![forbid(unsafe_code)]
184
185/// A colour intent this crate refers to but never resolves.
186///
187/// The string is the token name `makeover` publishes, so a renderer can look
188/// it up without this crate knowing what colour came back.
189pub trait Intent {
190    /// The `makeover` intent token this resolves against.
191    fn token(self) -> &'static str;
192}
193
194/// Which way the light falls across a two-tone edge.
195///
196/// The whole content of a bevel, once colour and thickness are deferred. The
197/// light is always assumed to come from the top left: every consumer measured
198/// agreed on that and none of them ever varied it, so it is an invariant here
199/// rather than a parameter.
200///
201/// # The two corners that belong to both edges
202///
203/// Top-right and bottom-left are where the lit run meets the shaded one, and
204/// the description's claim is that they belong to *both*. How a renderer says
205/// that is its own business, because the answer is bounded by resolution and
206/// not by taste:
207///
208/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
209///   to one tone thickens that edge by a cell and reads as one run overrunning
210///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
211///   splits it and recovers real information. Its box-drawing fallback cannot:
212///   a single stroke has no half to give, so there both corners go to dark.
213/// - A pixel bevel is a one-point stroke by default, which makes the corner a
214///   one-point square. There is nothing to divide — a diagonal seam across one
215///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
216///   already produces. So `makeover-immediate` mitres and is *not* diverging;
217///   it is the same rule at a resolution where the split degenerates.
218///
219/// Stated here so the difference reads as a decision rather than as drift. A
220/// renderer with room to divide the corner should; one without should mitre or
221/// pick the shaded tone, and neither is a bug.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223pub enum Bevel {
224    /// Lit from the top left: light on top and left, dark on bottom and right.
225    Raised,
226    /// The same edge inverted, which is also the pressed state of anything
227    /// that draws itself [`Bevel::Raised`].
228    Inset,
229}
230
231impl Bevel {
232    /// The edge intents, as `(top_left, bottom_right)`.
233    ///
234    /// Split out from any painting because the inversion *is* the idea, and
235    /// it is the one part every renderer implements identically.
236    #[must_use]
237    pub const fn edges(self) -> (Edge, Edge) {
238        match self {
239            Self::Raised => (Edge::Light, Edge::Dark),
240            Self::Inset => (Edge::Dark, Edge::Light),
241        }
242    }
243
244    /// Pressing inverts. A raised control reads as inset while held.
245    ///
246    /// Stated here rather than left to each consumer because a cascade can
247    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
248    /// resolves this per call site, eighteen times.
249    #[must_use]
250    pub const fn pressed(self) -> Self {
251        match self {
252            Self::Raised => Self::Inset,
253            Self::Inset => Self::Raised,
254        }
255    }
256}
257
258/// One side of a bevel, named by the intent it takes.
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
260pub enum Edge {
261    /// The lit side.
262    Light,
263    /// The shadowed side.
264    Dark,
265}
266
267impl Intent for Edge {
268    fn token(self) -> &'static str {
269        match self {
270            Self::Light => "bevel-light",
271            Self::Dark => "bevel-dark",
272        }
273    }
274}
275
276/// A surface intent a region is filled with.
277///
278/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
279/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
280/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
281/// `makeover-immediate` at compile time and left neither able to move until
282/// both published. The vocabulary exists to grow and the renderers exist to
283/// disagree about how much of it they answer, so growth must not be a
284/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
285/// resolved through a fallible lookup, and a missing intent is answered with
286/// structure rather than with a substituted colour.
287///
288/// [`Sunken`]: Fill::Sunken
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
290#[non_exhaustive]
291pub enum Fill {
292    /// The page behind everything.
293    Page,
294    /// A surface lifted off the page: cards, controls, menus, toasts.
295    Raised,
296    /// A surface floating above the page rather than resting on it.
297    Overlay,
298    /// The inside of a well.
299    Well,
300    /// A surface set back from the one it sits on, by colour and nothing else.
301    ///
302    /// Not a well. A well is a hole with an edge, and the two are authored in
303    /// opposite directions: `makeover` derives `surface-well` by inverting
304    /// against the theme's own content colour, while `surface-sunken` is
305    /// authored and free to sit darker than raised (goingson's does). Naming
306    /// only the well left the recessed-with-no-edge surface unsayable, which is
307    /// what an unchosen tab is: it recedes so the chosen one can come forward,
308    /// and it carries no bevel of its own.
309    ///
310    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
311    /// and could not delete the line because no member described it.
312    Sunken,
313}
314
315// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
316// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
317// had something to paint. makeover-tui found that wrong within a day: page is
318// the surface a well is usually cut into, so on a terminal that substitution
319// produces exactly the invisibility it was meant to prevent, and the right
320// answer there is a drawn edge rather than a different colour.
321//
322// Substituting one intent for another is renderer policy. The description says
323// what the region is and stops.
324
325impl Intent for Fill {
326    fn token(self) -> &'static str {
327        match self {
328            Self::Page => "surface-page",
329            Self::Raised => "surface-raised",
330            Self::Overlay => "surface-overlay",
331            Self::Well => "surface-well",
332            Self::Sunken => "surface-sunken",
333        }
334    }
335}
336
337/// How a region sits relative to the surface behind it.
338///
339/// Fill and bevel are named together because naming them apart is what let
340/// them disagree. Every consumer measured had at least one region carrying a
341/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
342/// and recorded the bug in its doc comment, and Balanced Breakfast still had
343/// twelve of them a year later. A single name for the pair makes that
344/// unrepresentable.
345/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
346/// release: a depth this renderer has no drawing for should cost it a
347/// wildcard arm, not a compile error and a wait on someone else's publish.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
349#[non_exhaustive]
350pub enum Depth {
351    /// Level with its surroundings. No edge.
352    Flat,
353    /// A card laid on the panel it sits in.
354    Raised,
355    /// A hole in the panel, with content down inside it. For anything the
356    /// user looks *into*: a table body, a tag tree, a text field.
357    Well,
358    /// Set back from what it sits on, by colour alone. No edge.
359    ///
360    /// The one member carrying a fill without a bevel, so a renderer cannot
361    /// assume the two arrive together. That is deliberate and it is still the
362    /// pairing rule: both halves come off the same `Depth`, so they cannot
363    /// disagree, and here one half is legitimately absent.
364    ///
365    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
366    /// Recessed and level-with are different claims, and only one of them
367    /// needs a colour.
368    Sunken,
369}
370
371impl Depth {
372    /// The edge this depth is drawn with, if it has one.
373    #[must_use]
374    pub const fn bevel(self) -> Option<Bevel> {
375        match self {
376            // Sunken joins Flat here, for the opposite reason: Flat has no edge
377            // because nothing separates it from its surroundings, and Sunken has
378            // none because its colour is already doing the separating.
379            Self::Flat | Self::Sunken => None,
380            Self::Raised => Some(Bevel::Raised),
381            Self::Well => Some(Bevel::Inset),
382        }
383    }
384
385    /// The surface this depth is filled with.
386    ///
387    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
388    /// which is the difference between level-with and painted-the-same-colour.
389    #[must_use]
390    pub const fn fill(self) -> Option<Fill> {
391        match self {
392            Self::Flat => None,
393            Self::Raised => Some(Fill::Raised),
394            Self::Well => Some(Fill::Well),
395            Self::Sunken => Some(Fill::Sunken),
396        }
397    }
398
399    /// Pressing a raised region reads as a well, and nothing else moves.
400    #[must_use]
401    pub const fn pressed(self) -> Self {
402        match self {
403            Self::Raised => Self::Well,
404            other => other,
405        }
406    }
407}
408
409/// An interaction state a region can be in, beside whatever [`Depth`] it is.
410///
411/// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
412/// and a disabled field is still a [`Depth::Well`], so folding either member
413/// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
414/// something that is not a depth, and would leave disabled-button and
415/// disabled-field sharing one variant that cannot tell them apart.
416///
417/// # Why hover and pressed are not members
418///
419/// The line is whether every renderer has the state to express, not whether CSS
420/// does. Hover is renderer policy and `makeover-webview` says so in its own
421/// header: a terminal and an immediate-mode painter have no pointer hovering
422/// over anything, and pressed already arrives through [`Bevel::pressed`] and
423/// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
424/// rather than a separate condition.
425///
426/// Focus and disabled are different in kind. A TUI has a focused widget and a
427/// greyed-out one; so does egui. Both were unsayable here, so all three webview
428/// consumers supplied them from outside the primitive by out-specifying rules
429/// they did not own: goingson alone carries 19 of them, and the MNW server
430/// another 21. That is the divergence this crate exists to end, arriving one
431/// layer down.
432///
433/// # The principle this encodes
434///
435/// A primitive owns every state it implies. A renderer that emits a hover rule
436/// for a thing owes disabled, focus and the capability answer for that same
437/// thing, because anything less exports the completion work to N consumers who
438/// will each do it differently.
439///
440/// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
441/// must not be a lockstep event across the three renderers.
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
443#[non_exhaustive]
444pub enum State {
445    /// Keyboard focus, as distinct from the pointer having landed on something.
446    ///
447    /// One ring, not one per primitive. Where the ring sits is [`Depth`]'s
448    /// question and not a per-component choice: a well takes it inside its own
449    /// edge and a raised surface takes it outside. That is one decision with
450    /// two renderings rather than one decision per component, which is how the
451    /// three apps ended up with three rings.
452    Focus,
453    /// Present, visible, and not answering.
454    ///
455    /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
456    /// control keeps the surface it always had and stops responding, so what
457    /// changes is its content and its interactivity rather than what it is.
458    Disabled,
459}
460
461impl State {
462    /// Whether a region in this state stops answering the pointer.
463    ///
464    /// Stated in the description rather than left to each renderer, on the same
465    /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
466    /// immediate-mode renderer resolves it per call site, so leaving it unsaid
467    /// means resolving it once per consumer and disagreeing.
468    #[must_use]
469    pub const fn suppresses_interaction(self) -> bool {
470        match self {
471            Self::Disabled => true,
472            Self::Focus => false,
473        }
474    }
475}
476
477impl Intent for State {
478    fn token(self) -> &'static str {
479        match self {
480            // Already derived by `makeover` from `action.primary`, and unused
481            // until now for the same reason `hover-surface` was: nothing
482            // emitted the rule that would consume it.
483            Self::Focus => "focus-ring",
484            // Reusing the muted content intent rather than minting a
485            // `disabled` colour. Disabled is a reduction and not a status, and
486            // `makeover-webview`'s progress rules already record the reading
487            // that `content-muted` is what disabled looks like.
488            Self::Disabled => "content-muted",
489        }
490    }
491}
492
493/// What a region is saying, when it is saying something.
494///
495/// The one intent family shared by badges, notices and nothing else. Kept
496/// separate from [`Fill`] because a surface is where a thing sits and a tone is
497/// what it means, and the three apps agree on the four statuses:
498/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
499/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
500/// `.toast.error` in Balanced Breakfast.
501///
502/// The per-tag palette (`category-one` through `category-six`) is deliberately
503/// not here. Which colour a *particular* tag takes is app domain, and both
504/// webview apps already carry it as a `data-color` attribute.
505#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
506pub enum Tone {
507    /// No status. Reads as ordinary de-emphasised content.
508    Neutral,
509    /// Something worth knowing and nothing to do about it.
510    Info,
511    /// Something finished and it worked.
512    Success,
513    /// Something the user should look at before continuing.
514    Warning,
515    /// Something broken, or something about to be destroyed.
516    Danger,
517}
518
519impl Intent for Tone {
520    fn token(self) -> &'static str {
521        match self {
522            // Neutral has no status token of its own. It takes the muted
523            // content intent, which is what both webview apps already spell as
524            // `data-color="muted"`.
525            Self::Neutral => "content-muted",
526            Self::Info => "info",
527            Self::Success => "success",
528            Self::Warning => "warning",
529            Self::Danger => "danger",
530        }
531    }
532}
533
534/// A small labelled thing that sits inside something else.
535///
536/// Two members, because the three apps drew three taxonomies and only one line
537/// runs through all of them: does it answer a click. audiofiles has
538/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
539/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
540/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
541/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
542/// to decide which of the two it always was.
543///
544/// The evidence that a chip is a real concept rather than a badge with a
545/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
546/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
547/// holds itself down", which is exactly what [`Depth::pressed`] already says.
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
549pub enum Token {
550    /// Non-interactive status or count. Answers no click.
551    Badge,
552    /// An interactive or removable token. Answers a click, and latches if it
553    /// stands for a filter that is either on or off.
554    Chip {
555        /// Whether it carries its own remove affordance.
556        removable: bool,
557    },
558}
559
560impl Token {
561    /// Whether this answers a click.
562    ///
563    /// The whole difference between the two members, and the reason a renderer
564    /// with no hover (a touch surface, a terminal) can still tell them apart.
565    #[must_use]
566    pub const fn interactive(self) -> bool {
567        matches!(self, Self::Chip { .. })
568    }
569
570    /// How it sits, given whether it is currently latched down.
571    ///
572    /// A badge is flat: it is a label, and giving it an edge would say it can
573    /// be pressed. A chip is raised, and inset while latched.
574    #[must_use]
575    pub const fn depth(self, latched: bool) -> Depth {
576        match self {
577            Self::Badge => Depth::Flat,
578            Self::Chip { .. } if latched => Depth::Well,
579            Self::Chip { .. } => Depth::Raised,
580        }
581    }
582}
583
584/// Something the app is telling the user, unprompted.
585///
586/// Two concepts, not one with a placement. They differ in more than where they
587/// sit: a toast is transient, stacked and self-dismissing, and a banner is
588/// persistent, in flow, one per region, and dismissed by fixing the condition
589/// it reports. Folding them into one member with a placement parameter would
590/// make lifetime, stacking and dismissal all placement-dependent, which is the
591/// description leaking renderer policy.
592///
593/// All three apps have banners: `info_banner` and `warning_banner` in
594/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
595/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
596/// webview apps also have toasts. So neither member is speculative, and no app
597/// gains a concept it lacks except audiofiles, whose renderer may legitimately
598/// decline to draw a toast at all.
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
600pub enum Notice {
601    /// Transient, stacked, dismisses itself.
602    Toast,
603    /// Persistent, in flow, one per region, dismissed by fixing the cause.
604    Banner,
605}
606
607impl Notice {
608    /// Whether it goes away on its own.
609    #[must_use]
610    pub const fn transient(self) -> bool {
611        matches!(self, Self::Toast)
612    }
613
614    /// How it sits.
615    ///
616    /// A toast floats above the page rather than resting on it, which is
617    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
618    /// flow. Both are raised, and they are raised off different things.
619    #[must_use]
620    pub const fn fill(self) -> Fill {
621        match self {
622            Self::Toast => Fill::Overlay,
623            Self::Banner => Fill::Raised,
624        }
625    }
626}
627
628/// The parts of a list row.
629///
630/// Four to begin with, taken from Balanced Breakfast, which was the only
631/// consumer that had all of them (`row-primary`, `row-secondary`, `row-meta`,
632/// `row-actions`). audiofiles has two and no slot structure at all, so it gains
633/// meta and actions as real work rather than a rename; goingson moves off
634/// `task-row` / `task-cell`.
635///
636/// [`Tokens`](Self::Tokens) joined at 0.9.0, and `#[non_exhaustive]` with it.
637/// See the crate header for why the two arrived together.
638///
639/// # Meta against Tokens
640///
641/// The line is whether the thing has its own standing. `Meta` is one short
642/// trailing fact about the row, written as text: a count, a size, a date.
643/// `Tokens` is a set of small labelled things, each of which can be toned and
644/// can answer a click. "3 files" is meta. A status badge that is amber, and a
645/// tag you can click to filter by, are tokens.
646///
647/// Keeping them apart is what a single widened slot would have foreclosed. A
648/// renderer can right-align one string and cannot usefully do the same to a
649/// strip of chips, and a fact that is not clickable should not be drawn as
650/// though it were.
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
652#[non_exhaustive]
653pub enum RowPart {
654    /// The thing itself. What the row is called.
655    Primary,
656    /// Supporting text under the primary.
657    Secondary,
658    /// A short trailing fact: a count, a size, a date.
659    Meta,
660    /// Controls that act on this row.
661    Actions,
662    /// Small labelled things belonging to the row: badges, chips, tags.
663    ///
664    /// Each carries its own [`Token`] kind and [`Tone`], so a renderer with no
665    /// colour still has the kind to work with, and one with no chips still has
666    /// the label. That is the constrained-consumer test this vocabulary exists
667    /// to pass, and it is why the tone lives on the token rather than on the
668    /// part.
669    Tokens,
670    /// How much of a set the row's thing has done: a [`Meter`] in the row.
671    ///
672    /// Added 0.11.0, `da5666ae`, and it is [`Tokens`](Self::Tokens)'s problem
673    /// again with a different payload. [`Meter`] arrived at 0.10.0 and closed
674    /// two of the seven sites that asked for it; the other five sit in rows, and
675    /// a row holds no nodes by the ruling that a row part may not carry an
676    /// arbitrary node — the door through which a description becomes a
677    /// templating language. So the part carries the *description of a bar*
678    /// rather than a node, exactly as `Tokens` carries tags rather than nodes.
679    ///
680    /// Without it a row flattens the proportion into [`Meta`](Self::Meta) as
681    /// "3/7 subtasks", which keeps both numbers and loses the reading, the same
682    /// way a toned status badge read as prose before `Tokens`.
683    Proportion,
684}
685
686impl RowPart {
687    /// Whether the part stays hidden until the row is hovered or focused.
688    ///
689    /// Behaviour of the part, not app policy: Balanced Breakfast and goingson
690    /// grew the same hover-reveal on their actions independently and neither
691    /// applies it to anything else.
692    ///
693    /// A renderer with no hover shows it always. That is a renderer decision
694    /// and this returning `true` does not forbid it.
695    #[must_use]
696    pub const fn revealed_on_hover(self) -> bool {
697        matches!(self, Self::Actions)
698    }
699
700    /// The content intent the part takes.
701    #[must_use]
702    pub const fn intent(self) -> &'static str {
703        match self {
704            Self::Primary => "content",
705            Self::Secondary => "content-secondary",
706            Self::Meta => "content-muted",
707            // Actions carry controls rather than text, so they inherit.
708            Self::Actions => "content",
709            // So do tokens: each one carries its own tone, and a part-level
710            // intent underneath it would fight the token that sits on it.
711            Self::Tokens => "content",
712            // And so does a proportion, for the same reason: the meter carries
713            // the tone, and it is about the ratio rather than about the row.
714            Self::Proportion => "content",
715        }
716    }
717}
718
719/// How far down the heading tree a title sits.
720///
721/// Three, and only the three that are actually headings. The bands those used
722/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
723/// and `.detail-header`) are arrangement, not type, and live at
724/// [`Region::Band`]. One of them contains no text at all.
725#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
726pub enum Heading {
727    /// Names the whole screen. One per screen.
728    Page,
729    /// Names a block within the screen.
730    Section,
731    /// Names a sub-block inside an already-named section.
732    Subsection,
733}
734
735impl Heading {
736    /// Whether a rule follows the heading.
737    ///
738    /// audiofiles' `section_header` draws a separator and its
739    /// `subsection_label` deliberately does not, which is the only thing
740    /// distinguishing the two once weight and colour are deferred.
741    #[must_use]
742    pub const fn separated(self) -> bool {
743        matches!(self, Self::Section)
744    }
745}
746
747/// A control that picks between things.
748///
749/// Three, because three distinct behaviours are in play and collapsing any two
750/// loses something. A segmented control picks a value; a tab picks a pane; a
751/// toggle picks nothing and simply holds itself on or off.
752#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
753pub enum Selector {
754    /// Exactly one of N, and the options abut.
755    Segmented,
756    /// Independent on or off, on its own.
757    Toggle,
758    /// Navigation between panes. The folder semantic.
759    Tabs,
760}
761
762impl Selector {
763    /// How the chosen option sits.
764    ///
765    /// Held in for a segmented control and a toggle, which is the same shape
766    /// pressing produces and the whole economy of the idiom: one appearance,
767    /// two reasons to wear it. A tab is the exception, because the selected
768    /// folder tab comes *forward* to join the pane it opens.
769    #[must_use]
770    pub const fn chosen(self) -> Depth {
771        match self {
772            Self::Segmented | Self::Toggle => Depth::Well,
773            Self::Tabs => Depth::Raised,
774        }
775    }
776
777    /// How the options that were *not* picked sit.
778    ///
779    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
780    /// option falling through to [`Depth::Flat`], which says it is level with
781    /// the strip it sits in, and no renderer emitted anything for it. That is
782    /// wrong in both directions and goingson proved it: its unchosen tabs are
783    /// recessed by hand, and being recessed is *why* the chosen one reads as
784    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
785    /// drawn on the strip's own colour, which is a much weaker folder effect
786    /// than the contrast the idiom is named after.
787    ///
788    /// Each member is the inverse of its chosen state, which is the whole
789    /// content of "picked" once colour is deferred:
790    ///
791    /// - Tabs recede, so the chosen one comes forward.
792    /// - A segment and a toggle stand up, so the chosen one is held in.
793    #[must_use]
794    pub const fn unchosen(self) -> Depth {
795        match self {
796            Self::Tabs => Depth::Sunken,
797            Self::Segmented | Self::Toggle => Depth::Raised,
798        }
799    }
800
801    /// Whether the options touch.
802    ///
803    /// The gap is the entire difference between a segmented control and a row
804    /// of buttons that happen to sit near each other, which is what audiofiles'
805    /// `segmented_control` says in its own comment and why it zeroes the
806    /// spacing by hand.
807    #[must_use]
808    pub const fn abutting(self) -> bool {
809        matches!(self, Self::Segmented | Self::Tabs)
810    }
811}
812
813/// What is in a region right now.
814///
815/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
816/// nothing at all is renderer policy, the same class of decision that got
817/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
818/// each grew a skeleton with differently-named parts; both keep them, as the
819/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
820/// and needs none, because an immediate-mode renderer simply repaints.
821///
822/// # Four states and not two, as of 0.12.0
823///
824/// `703f4cd2`. It named `Ready` and `Pending` and stopped, so a described screen
825/// whose list came back empty had to render an empty region or invent its own
826/// placeholder text, and neither says what it is. goingson draws one at 27 sites
827/// across 12 files and Balanced Breakfast at 9, with a class family that had
828/// already drifted into `empty-state`, `empty-state--error`, `error-state` and
829/// six more.
830///
831/// The four are one axis because they are mutually exclusive: a region shows its
832/// content, or a sign that it is coming, or a sign that there is none, or a sign
833/// that it broke. Never two. That is the test for one enum against several
834/// fields, and it is why this grew rather than a new member arriving beside it.
835///
836/// # What is not here
837///
838/// **The message.** "No projects yet" is content, and this names a state. It
839/// lives with whatever holds the region — in quasi's case a `Slot` — alongside
840/// the action that leads out of the emptiness, since an address is the one thing
841/// this crate never names.
842///
843/// **How much room it gets.** goingson's `--compact`, `--dashboard` and
844/// `--padded` are the same state at three sizes, and a size is
845/// `makeover-geometry`'s question. Naming them here would be this crate stating
846/// values again.
847///
848/// **The icon.** Presentation, and each host has its own answer or none.
849#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
850#[non_exhaustive]
851pub enum Readiness {
852    /// The content is here.
853    Ready,
854    /// The content is on its way.
855    Pending,
856    /// The content arrived and there is none of it.
857    ///
858    /// Not a failure. An empty list is the normal state of a new install, and a
859    /// renderer that drew it in a danger tone would be reporting a fault where
860    /// there is none.
861    Empty,
862    /// The content did not arrive.
863    Failed,
864}
865
866impl Readiness {
867    /// Whether the region draws its own content, or something standing in for
868    /// it.
869    ///
870    /// The question every renderer asks first, so it is answered once here
871    /// rather than by a `matches!` in each. A state added later is a stand-in
872    /// until proven otherwise: falling back to drawing content that may not be
873    /// there is the worse of the two mistakes.
874    #[must_use]
875    pub const fn shows_content(self) -> bool {
876        matches!(self, Self::Ready)
877    }
878
879    /// What the state means, for a renderer choosing a colour.
880    ///
881    /// Derived rather than carried, which is the opposite of [`Meter`] and
882    /// [`Figure`], and the difference is worth stating: a proportion's meaning
883    /// depends on what is being counted and only the app knows it, while
884    /// "nothing here yet" and "this broke" mean the same thing in every app that
885    /// will ever have them.
886    #[must_use]
887    pub const fn tone(self) -> Tone {
888        match self {
889            Self::Failed => Tone::Danger,
890            _ => Tone::Neutral,
891        }
892    }
893}
894
895/// How much of a set is done.
896///
897/// Added 0.10.0. Nine sites across the two webview apps drew a bar and nothing
898/// here named one, so every described screen concatenated the two numbers into
899/// its heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m
900/// est, over". Every fact survives that and the reading does not, which is the
901/// same loss `RowPart::Tokens` closed when a toned status badge became prose.
902///
903/// # Why a pair and not a percentage
904///
905/// Both numbers, not the percentage the apps compute from them. The percentage
906/// was the obvious shape and it had already been tried: goingson's
907/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
908/// away the one case the bar exists to show — 45 minutes tracked against a
909/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
910/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
911/// companion flag, and [`percent`](Meter::percent) is still one call away for a
912/// renderer that wants it.
913///
914/// The pair is also what the apps already have at every site. All seven
915/// determinate bars write the ratio into the accessible layer and never the
916/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
917/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
918/// percentage member would have made [`label`](Meter::label) mandatory at every
919/// call site, which is the concatenated text this member removes, moved one
920/// layer down.
921///
922/// # What this is not
923///
924/// The progress of an *operation*. Two of the nine sites are that — goingson's
925/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
926/// purpose. Both are imperative controllers over a live handle, driven by a tick
927/// or an event stream, and a description is built once and dropped. Holding one
928/// would mean growing a way to update a description between renders, which is a
929/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
930/// honest part.
931///
932/// The two cases are distinguishable in the markup rather than by taste: every
933/// determinate bar in both apps carries a tone, and neither operation bar
934/// carries one. Two codebases drew that line the same way without coordinating.
935#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
936pub struct Meter<'a> {
937    /// How much is done. May exceed [`total`](Self::total), and that is the
938    /// case worth drawing.
939    pub done: u32,
940    /// How much there is to do. Zero means there is no set, not that the set is
941    /// complete.
942    pub total: u32,
943    /// What the proportion means right now.
944    ///
945    /// Carried rather than derived, because no renderer can work it out. The
946    /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
947    /// a time estimate, and goingson picks between them from `is_over_estimate`,
948    /// a fact about the data and not about the number.
949    pub tone: Tone,
950    /// What is being counted, if the bar says so: "subtasks", "tasks".
951    ///
952    /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
953    /// and the two numbers; handing it the assembled string would put the
954    /// sentence order in the description, where a terminal at one line and a
955    /// tooltip want different ones.
956    pub label: Option<&'a str>,
957}
958
959impl<'a> Meter<'a> {
960    /// A proportion with no tone and no label.
961    #[must_use]
962    pub const fn new(done: u32, total: u32) -> Self {
963        Self {
964            done,
965            total,
966            tone: Tone::Neutral,
967            label: None,
968        }
969    }
970
971    /// What the proportion means.
972    #[must_use]
973    pub const fn tone(mut self, tone: Tone) -> Self {
974        self.tone = tone;
975        self
976    }
977
978    /// What is being counted.
979    #[must_use]
980    pub const fn label(mut self, label: &'a str) -> Self {
981        self.label = Some(label);
982        self
983    }
984
985    /// How full the bar is, 0 to 100, clamped.
986    ///
987    /// For drawing, which is the only thing a clamped number is good for. Ask
988    /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
989    /// is `time_progress`'s bug again with the clamp moved.
990    ///
991    /// An empty set reads as 0. Nothing is done, because there is nothing to do
992    /// and no bar to fill; the apps guard on the count before drawing at all.
993    #[must_use]
994    pub const fn percent(&self) -> u8 {
995        if self.total == 0 {
996            return 0;
997        }
998        let scaled = (self.done as u64 * 100) / self.total as u64;
999        if scaled > 100 { 100 } else { scaled as u8 }
1000    }
1001
1002    /// Whether more is done than there was to do.
1003    ///
1004    /// The fact [`percent`](Self::percent) destroys, kept reachable so a
1005    /// renderer can mark the over-run rather than drawing a full bar and
1006    /// implying it landed exactly.
1007    #[must_use]
1008    pub const fn overflowing(&self) -> bool {
1009        self.done > self.total
1010    }
1011
1012    /// Whether there is a set at all.
1013    ///
1014    /// A meter over nothing is sayable on purpose, for the same reason a field
1015    /// with no options is: it is what an app with an unloaded count actually
1016    /// has, and a renderer that shows an empty bar says so on screen rather than
1017    /// dividing by zero.
1018    #[must_use]
1019    pub const fn is_empty(&self) -> bool {
1020        self.total == 0
1021    }
1022}
1023
1024/// One figure with a caption: a number and what it counts.
1025///
1026/// The dashboard shape. A large value over a small caption, several of them in a
1027/// strip: a current streak, a completion rate, a total. Added 0.11.0,
1028/// `93c6a174`, after goingson turned out to have five of them across five
1029/// screens with five class vocabularies for the one shape — `task-overview-stat`,
1030/// `stat-box`, `month-stat-item`, `contact-summary-stat`, `sync-stat`. Four put
1031/// the value above the caption and one inverts it, which is drift inside the
1032/// shape rather than a second shape.
1033///
1034/// # Why the value is text
1035///
1036/// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
1037/// formatted, and the formatting is the app's because only it knows whether the
1038/// number is a percentage, a duration or a ratio. This carries none of the
1039/// arithmetic [`Meter`] carries, and that is the difference between them: a
1040/// meter is a proportion a renderer draws, and a figure is a fact a renderer
1041/// sets in type.
1042///
1043/// # Tone is carried, for [`Meter`]'s reason
1044///
1045/// Three of the five sites tone the figure by their own means — `red`/`blue` on
1046/// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
1047/// sync. So tone is carried at every site that needs it and derived at none, and
1048/// no renderer can work out that a streak of zero is worth colouring.
1049///
1050/// # What is not here
1051///
1052/// Whether the figure answers a click. One of the five is a control — sync's
1053/// "Not Applied: 3" opens the list — and an action is not something this crate
1054/// can name: nothing here knows what a route is. That belongs beside the figure
1055/// in whatever layer holds the actions, the same way a row's activation sits
1056/// beside its parts rather than inside them.
1057///
1058/// The arrangement is not here either. Several figures in a strip is a set, and
1059/// a renderer given them one at a time cannot tell it is looking at one; the
1060/// layer that holds the tree is where the set gets said.
1061#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1062pub struct Figure<'a> {
1063    /// The number, formatted the way the app means it to read.
1064    pub value: &'a str,
1065    /// What it counts. The caption under the value.
1066    pub caption: &'a str,
1067    /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
1068    pub tone: Tone,
1069}
1070
1071impl<'a> Figure<'a> {
1072    /// A figure that is an ordinary fact.
1073    #[must_use]
1074    pub const fn new(value: &'a str, caption: &'a str) -> Self {
1075        Self {
1076            value,
1077            caption,
1078            tone: Tone::Neutral,
1079        }
1080    }
1081
1082    /// What the figure means.
1083    #[must_use]
1084    pub const fn tone(mut self, tone: Tone) -> Self {
1085        self.tone = tone;
1086        self
1087    }
1088}
1089
1090/// A named part of a screen.
1091///
1092/// The thing `makeover-geometry` deliberately does not name: it names the space
1093/// *between* things by relationship, and nothing named the things. Six named
1094/// members, taken from what the two webview apps actually use, plus
1095/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
1096/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
1097/// this layer is absent rather than divergent, which makes it the cheapest of
1098/// the schemas to add and the easiest to over-build.
1099#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1100pub enum Region<'a> {
1101    /// A full-width strip with a title slot and an actions cluster, either of
1102    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
1103    /// `.header` and `.detail-header` are all this, differing only in which
1104    /// slots they fill.
1105    Band,
1106    /// A persistent column beside the content, holding navigation.
1107    Sidebar,
1108    /// A region of content with its own scroll.
1109    Pane,
1110    /// Two panes side by side, where the left chooses what the right shows.
1111    Split,
1112    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
1113    TabGroup,
1114    /// Content over a scrim, taking input until dismissed.
1115    Modal,
1116    /// A region this crate names the *place* of and nothing else. The app owns
1117    /// what goes in it.
1118    ///
1119    /// The escape hatch, and the thing that keeps the description honest about
1120    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
1121    /// paint interaction over the timeline are not describable here and are not
1122    /// going to become describable: a description expressive enough to produce
1123    /// a timeline is a widget library wearing a description's name.
1124    ///
1125    /// But a screen containing one still has to be a screen. Without this
1126    /// member the description covers only the boring screens, and the four that
1127    /// make goingson worth using would need a second, undescribed path beside
1128    /// the router. Two paths is how the vocabulary starts drifting from the app
1129    /// again, which is the exact failure this crate exists to end.
1130    ///
1131    /// So the description says "a thing called `day-plan` goes here" and stops.
1132    /// The name is opaque: this crate never interprets it, and no renderer is
1133    /// expected to know what it means beyond handing the space over.
1134    Bespoke {
1135        /// What the app calls it. Never interpreted here.
1136        name: &'a str,
1137    },
1138}
1139
1140impl Region<'_> {
1141    /// How the region sits on what is behind it.
1142    #[must_use]
1143    pub const fn depth(self) -> Depth {
1144        match self {
1145            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
1146            // A pane is looked into, the same as a table body or a tag tree.
1147            Self::Pane => Depth::Well,
1148            Self::Modal => Depth::Raised,
1149            // Flat because it inherits: a bespoke region takes the depth of
1150            // whatever frames it. An app that wants its timeline in a well puts
1151            // it in a `Pane`, which composes rather than adding a knob here.
1152            Self::Bespoke { .. } => Depth::Flat,
1153        }
1154    }
1155
1156    /// Whether this crate can say anything about the region's contents.
1157    ///
1158    /// A renderer walks the description and hands every region it understands
1159    /// to the right drawing code. This is how it tells the two apart, and the
1160    /// reason it is a method rather than a `matches!` at each renderer: there
1161    /// is exactly one opaque member and there should stay exactly one.
1162    #[must_use]
1163    pub const fn described(self) -> bool {
1164        !matches!(self, Self::Bespoke { .. })
1165    }
1166}
1167
1168/// How a screen is laid out.
1169///
1170/// Two, and the second is not a variant of the first. goingson is list-detail,
1171/// Balanced Breakfast is sidebar plus content, and neither app has a third.
1172/// The tab group is a modifier rather than a member, because goingson uses it
1173/// *inside* the same content region rather than instead of one.
1174///
1175/// This exists at all because the router has to be able to express a screen
1176/// rather than only a control. Discovering the arrangement layer missing after
1177/// the renderers exist is a redesign; naming two now is a morning.
1178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1179pub enum Arrangement {
1180    /// A list that chooses what the detail beside it shows.
1181    ListDetail {
1182        /// Whether the detail side is a [`Region::TabGroup`].
1183        tabbed: bool,
1184    },
1185    /// Navigation down the side, content filling the rest.
1186    SidebarContent,
1187}
1188
1189/// What kind of value a form field takes.
1190///
1191/// The union of the two vocabularies that diverged, which is what triggered
1192/// this crate. They have since converged on their own: both apps now have a
1193/// `renderFormField` emitting the same anatomy, and what is left differing is
1194/// the kind set, the error shape, and whether the return is a string or a node.
1195///
1196/// Validation is deliberately absent. Neither app has a shared story (goingson
1197/// validates after collecting the form data, with per-field transform hooks;
1198/// Balanced Breakfast has `required` and nothing else), and a schema that
1199/// describes fields but not constraints acquires a constraint layer per app,
1200/// which is exactly how the current divergence started. Naming it absent is a
1201/// decision; leaving it unmentioned would not be.
1202/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
1203/// the set keeps growing, so growth must not be a lockstep event. Email, Url
1204/// and Tel arriving in 0.5.0 is the second growth in two releases.
1205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1206#[non_exhaustive]
1207pub enum FieldKind {
1208    /// A single line of text.
1209    Text,
1210    /// A single line of text that must never be echoed, logged or round-tripped
1211    /// through anything that might persist it.
1212    Secret,
1213    /// A number.
1214    Number,
1215    /// An email address.
1216    ///
1217    /// Distinct from [`Text`](Self::Text) because the distinction is not
1218    /// decoration: a webview renderer emits `type="email"`, which on a touch
1219    /// device changes the keyboard that appears and turns on the platform's own
1220    /// validation. goingson ships to iOS, so collapsing this into text costs a
1221    /// keyboard with no `@` on it.
1222    ///
1223    /// Added 0.5.0, from goingson's contact form.
1224    Email,
1225    /// A URL. Same reasoning as [`Email`](Self::Email).
1226    ///
1227    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
1228    Url,
1229    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
1230    /// clearest case of it: the keyboard is a numeric pad rather than letters.
1231    ///
1232    /// Added 0.5.0, from goingson's contact-phone form.
1233    Tel,
1234    /// Several lines of text.
1235    Textarea,
1236    /// One of a fixed set, offered behind a control that shows one at a time.
1237    Select,
1238    /// One of a fixed set, with every option on screen at once.
1239    ///
1240    /// Not a presentation of [`Select`](Self::Select), which is the reading to
1241    /// resist: what differs is a property of the *question*. A choice that is
1242    /// consequential or irreversible has to be readable without opening
1243    /// anything, because a closed control shows one option and hides the rest,
1244    /// and the one it shows is whichever was current before the user had read
1245    /// the alternatives. audiofiles asks whether a library copies samples into
1246    /// its store or references them where they lie — which cannot be changed
1247    /// afterwards — and had already promoted that out of a checkbox by hand,
1248    /// with a comment giving this reason, before the description could say it.
1249    ///
1250    /// It is also the one HTML input type this enum was missing. Everything
1251    /// else here is an `<input type=...>`, a `<select>` or a `<textarea>`, and
1252    /// the hole was `radio`.
1253    ///
1254    /// Added 0.8.1, from audiofiles' Add Library form.
1255    Radio,
1256    /// On or off.
1257    Checkbox,
1258    /// A file the user picks from wherever the host keeps files.
1259    ///
1260    /// Added 0.11.0, `844b5ae0`, from goingson's project-dashboard attachments
1261    /// column. It was filed as a router finding — a control whose destination is
1262    /// a host capability rather than an address — and splitting it is what made
1263    /// it two answers instead of one member satisfying neither. *Opening* a file
1264    /// is a one-way handoff and needs no new API. *Picking* one returns a value
1265    /// into a write, which is a form concern, which is this.
1266    ///
1267    /// The membership test passes on every host and not by a stretch: a Tauri
1268    /// app opens a native picker, a server renders `<input type="file">`, a
1269    /// terminal prompts for a path, a CLI takes an argument. That is closer to
1270    /// [`Email`](Self::Email), which exists because it changes the keyboard,
1271    /// than to anything bespoke.
1272    ///
1273    /// It carries no accepted-types list and no multiple flag, and that is
1274    /// measured rather than deferred: `accept` appears at zero sites in either
1275    /// app. A member added for a case nobody has is a member designed against
1276    /// nothing.
1277    File,
1278    /// Carried through the form and never shown.
1279    Hidden,
1280}
1281
1282impl FieldKind {
1283    /// Whether the field is drawn at all.
1284    #[must_use]
1285    pub const fn visible(self) -> bool {
1286        !matches!(self, Self::Hidden)
1287    }
1288
1289    /// Whether the value must be kept out of logs and diagnostics.
1290    #[must_use]
1291    pub const fn confidential(self) -> bool {
1292        matches!(self, Self::Secret)
1293    }
1294
1295    /// Where the field's own label sits.
1296    ///
1297    /// A checkbox labels itself on the right of the box; everything else takes
1298    /// a label above. Both webview apps already do this and both special-case
1299    /// it inline, which is the tell that it belongs in the description.
1300    ///
1301    /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
1302    /// naming: its *options* each label themselves, but the field still asks a
1303    /// question above them, so the group takes a label like everything else.
1304    #[must_use]
1305    pub const fn labels_itself(self) -> bool {
1306        matches!(self, Self::Checkbox)
1307    }
1308
1309    /// Whether the kind reads [`Field::options`].
1310    ///
1311    /// Two kinds do, so the pair is named once here rather than spelled out at
1312    /// each renderer and again in [`Field::options`]' own doc, where "every
1313    /// kind but `Select`" was true for exactly one release. A third
1314    /// option-taking kind should land here and nowhere else.
1315    #[must_use]
1316    pub const fn offers_options(self) -> bool {
1317        matches!(self, Self::Select | Self::Radio)
1318    }
1319}
1320
1321/// One option offered by a field [`FieldKind::offers_options`] accepts.
1322///
1323/// Two strings, because the submitted value and the read label are different
1324/// facts and every renderer that has tried to collapse them has had to
1325/// un-collapse them later. `makeover-webview` invented this shape writing its
1326/// form emitter and it is taken here unchanged; moving it down rather than
1327/// re-deriving it is the point, since the second and third renderers were each
1328/// going to arrive at a near-miss of it.
1329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1330pub struct Choice<'a> {
1331    /// What is submitted.
1332    pub value: &'a str,
1333    /// What is read.
1334    pub label: &'a str,
1335}
1336
1337impl<'a> Choice<'a> {
1338    /// An option whose submitted value is also its label.
1339    #[must_use]
1340    pub const fn plain(value: &'a str) -> Self {
1341        Self {
1342            value,
1343            label: value,
1344        }
1345    }
1346}
1347
1348/// One field of a form.
1349///
1350/// Borrowed rather than owned: a description is built, read once by a renderer,
1351/// and dropped. Nothing here outlives the screen it describes.
1352///
1353/// # What it carries, and what it does not
1354///
1355/// Stated here so the next renderer does not re-ask, which is what the first
1356/// two both did. It carries everything a renderer needs to *draw* the field:
1357/// its kind, what it is called, what it is asked for, its standing help, what
1358/// is wrong with it now, whether it is compulsory, whether it hides behind a
1359/// disclosure, its ghost text, and the options it offers.
1360///
1361/// It does not carry the **current value**, and it is not going to. That is the
1362/// one thing here that is genuinely renderer state: a webview reads it back out
1363/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
1364/// and writes through it, and a terminal keeps an edit buffer. A description
1365/// that carried the value would have to carry a way to write it back, at which
1366/// point it is a form model and no longer a description.
1367///
1368/// **Constraints** are here and enforcement is not, which is one line rather
1369/// than two. [`required`], [`max_length`], [`min`] and [`max`] are facts about
1370/// the *question*, so a renderer can emit its host's idiom for each — an HTML
1371/// attribute, a marked label, a clamped spinner — and the platform helps the
1372/// user before anything is submitted. Deciding that a value is wrong stays with
1373/// whoever validated, and [`error`] is that decision arriving back.
1374///
1375/// The set stops before `pattern`, and stops there on both tests at once. A
1376/// regex has an honest answer in a webview and none anywhere else: egui would
1377/// have to run it per keystroke and decide what a half-typed value means, which
1378/// is enforcement wearing description's clothes. And it is one site in goingson
1379/// and none in Balanced Breakfast, against 8 and 1 for `maxlength`. Measured
1380/// 2026-08-09, `2cbad3e2`.
1381///
1382/// [`error`]: Field::error
1383/// [`required`]: Field::required
1384/// [`max_length`]: Field::max_length
1385/// [`min`]: Field::min
1386/// [`max`]: Field::max
1387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1388pub struct Field<'a> {
1389    /// What kind of value it takes.
1390    pub kind: FieldKind,
1391    /// The name the value is submitted under.
1392    pub name: &'a str,
1393    /// What the user is asked for.
1394    pub label: &'a str,
1395    /// Standing help, shown whether or not anything is wrong.
1396    pub hint: Option<&'a str>,
1397    /// What is currently wrong with the value.
1398    pub error: Option<&'a str>,
1399    /// Ghost text shown while the field is empty.
1400    ///
1401    /// User-facing text, and it sits with `label` and `hint` rather than with
1402    /// the value because it is a property of the *question* and not of the
1403    /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
1404    /// reason and it was not a reading on where it belonged: adding a field to
1405    /// a published struct is a breaking change.
1406    ///
1407    /// Not a substitute for a label. A field labelled only by its placeholder
1408    /// loses its label the moment anything is typed, and no renderer here can
1409    /// make that not happen, so the description keeps both.
1410    pub placeholder: Option<&'a str>,
1411    /// The options offered, in the order they are offered.
1412    ///
1413    /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
1414    /// described with no options is sayable on purpose: it is what an app with
1415    /// an unfinished-loading option list actually has, and a renderer showing
1416    /// an empty control says so on screen rather than in a log.
1417    ///
1418    /// Which option is *current* is not here. That is the value, and the value
1419    /// is renderer state.
1420    pub options: &'a [Choice<'a>],
1421    /// Whether the form refuses to submit without it.
1422    pub required: bool,
1423    /// The longest the value may be, in characters.
1424    ///
1425    /// Added 0.11.0 with [`min`](Self::min) and [`max`](Self::max), joining
1426    /// [`required`](Self::required), which had been the only constraint here
1427    /// since before the crate wrote down that it carried none.
1428    pub max_length: Option<u32>,
1429    /// The lowest value accepted, as the host would write it.
1430    ///
1431    /// Text rather than a number, because the bound is only a number for some
1432    /// of the kinds that take one. goingson's own sites are `min="1"` on a
1433    /// duration and `min="2026-08-09T14:30"` on a datetime, and a numeric member
1434    /// could say the first and not the second. The [`kind`](Self::kind) already
1435    /// says how to read it, the same way it does for the value.
1436    pub min: Option<&'a str>,
1437    /// The highest value accepted, as the host would write it. See
1438    /// [`min`](Self::min).
1439    pub max: Option<&'a str>,
1440    /// Whether the field lives behind a "more options" disclosure.
1441    pub extended: bool,
1442}
1443
1444impl<'a> Field<'a> {
1445    /// A plain required-nothing field of the given kind.
1446    #[must_use]
1447    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
1448        Self {
1449            kind,
1450            name,
1451            label,
1452            hint: None,
1453            error: None,
1454            placeholder: None,
1455            options: &[],
1456            required: false,
1457            max_length: None,
1458            min: None,
1459            max: None,
1460            extended: false,
1461        }
1462    }
1463
1464    /// A select offering the given options.
1465    ///
1466    /// One of the two kinds under-described by [`Field::new`], so it gets a
1467    /// constructor rather than leaving every call site to remember that a
1468    /// select with an empty `options` renders as an empty select.
1469    #[must_use]
1470    pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1471        Self::offering(FieldKind::Select, name, label, options)
1472    }
1473
1474    /// A radio group offering the given options.
1475    ///
1476    /// The other. Same hazard as [`select`](Self::select) and a worse one: a
1477    /// radio group with no options draws nothing at all, so a call site that
1478    /// forgot them has an empty rectangle rather than a visibly empty control.
1479    #[must_use]
1480    pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1481        Self::offering(FieldKind::Radio, name, label, options)
1482    }
1483
1484    /// The shared body of the two constructors that take options.
1485    ///
1486    /// Private, and keyed on the kind rather than exposed, because the two
1487    /// public names are the point: a call site says which question it is
1488    /// asking, not which flag it is setting.
1489    const fn offering(
1490        kind: FieldKind,
1491        name: &'a str,
1492        label: &'a str,
1493        options: &'a [Choice<'a>],
1494    ) -> Self {
1495        Self {
1496            options,
1497            ..Self::new(kind, name, label)
1498        }
1499    }
1500
1501    /// Whether the field is currently reporting a problem.
1502    ///
1503    /// Read this rather than testing `error.is_some()` at each renderer: the
1504    /// error state has to mark the field's whole group and not only the
1505    /// message, because a renderer with no descendant selectors (egui, a
1506    /// terminal) cannot find the group from the message. goingson already marks
1507    /// the group and Balanced Breakfast does not, so goingson's shape is the
1508    /// one taken here.
1509    #[must_use]
1510    pub const fn invalid(&self) -> bool {
1511        self.error.is_some()
1512    }
1513}
1514
1515/// How much room a column asks for.
1516///
1517/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
1518/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
1519/// only the first three words of that survive deferral.
1520/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
1521/// renderer matches on this and a vocabulary that grows must not break every
1522/// renderer when it does.
1523#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1524#[non_exhaustive]
1525pub enum Width {
1526    /// Takes what it needs and no more.
1527    Content,
1528    /// A fixed share, the same at every width.
1529    Fixed,
1530    /// Absorbs whatever is left over.
1531    Fill,
1532}
1533
1534/// What a column is worth when there is not room for all of them.
1535///
1536/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
1537/// drops. This replaces addressing columns by position, which is what both
1538/// webview apps do today and is a live bug rather than only verbosity. goingson
1539/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
1540/// inserting a column silently hides the wrong one.
1541/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
1542/// whole point of the type, so a new tier has to be declared in its place in
1543/// the sequence rather than appended.
1544#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1545#[non_exhaustive]
1546pub enum Priority {
1547    /// Dropped first.
1548    Optional,
1549    /// Dropped once the optional columns are gone.
1550    Secondary,
1551    /// Never dropped. Without it the row does not identify itself.
1552    Essential,
1553}
1554
1555/// One column of a table.
1556///
1557/// Described once. The grid track, the cell order and the drop behaviour are
1558/// all derived from this, rather than being three hand-written encodings that
1559/// must agree and are never checked against each other.
1560#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1561pub struct Column<'a> {
1562    /// The heading, and the name the cell is addressed by.
1563    pub name: &'a str,
1564    /// How much room it asks for.
1565    pub width: Width,
1566    /// What it is worth when room runs out.
1567    pub priority: Priority,
1568    /// Whether the user can reorder the table by this column.
1569    ///
1570    /// `ce620871`. What reordering *calls* is not here — that is an address, and
1571    /// this crate names none — so a host pairs this with the route the way it
1572    /// pairs a row's parts with the row's activation. This says the affordance
1573    /// exists, which is what a renderer needs to draw a header a user can press
1574    /// rather than a heading they cannot.
1575    pub sortable: bool,
1576    /// Which way the table is ordered by this column, if it is.
1577    ///
1578    /// `None` on every column but the one in force. A renderer draws the caret
1579    /// from this and a webview sets `aria-sort`, which is why it is per column
1580    /// rather than a single fact on the table: the host idiom is a property of
1581    /// the header cell.
1582    ///
1583    /// Independent of [`sortable`](Self::sortable) rather than implied by it,
1584    /// because both combinations mean something. A column sorted and not
1585    /// sortable is a list ordered by a key the user cannot change, which is a
1586    /// real thing to describe and a caret worth drawing.
1587    pub sorted: Option<Sort>,
1588}
1589
1590/// Which way a column is ordered.
1591///
1592/// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
1593/// `None`, and folding it in here would be the same absence said twice.
1594#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1595pub enum Sort {
1596    /// Smallest, earliest or first alphabetically at the top.
1597    Ascending,
1598    /// The other way.
1599    Descending,
1600}
1601
1602impl Sort {
1603    /// The other direction, for a header that flips when pressed.
1604    #[must_use]
1605    pub const fn reversed(self) -> Self {
1606        match self {
1607            Self::Ascending => Self::Descending,
1608            Self::Descending => Self::Ascending,
1609        }
1610    }
1611
1612    /// What a webview writes into `aria-sort`.
1613    ///
1614    /// Named here rather than in the webview renderer because a terminal and an
1615    /// immediate-mode painter both want the same two words for a caret's label,
1616    /// and three renderers picking their own is the drift this crate ends.
1617    #[must_use]
1618    pub const fn as_str(self) -> &'static str {
1619        match self {
1620            Self::Ascending => "ascending",
1621            Self::Descending => "descending",
1622        }
1623    }
1624}
1625
1626impl<'a> Column<'a> {
1627    /// A column that absorbs slack and drops after the optional ones.
1628    #[must_use]
1629    pub const fn new(name: &'a str) -> Self {
1630        Self {
1631            name,
1632            width: Width::Fill,
1633            priority: Priority::Secondary,
1634            sortable: false,
1635            sorted: None,
1636        }
1637    }
1638
1639    /// Whether this column survives at the given cutoff.
1640    ///
1641    /// A renderer narrows by raising the cutoff, and never by counting
1642    /// positions.
1643    #[must_use]
1644    pub const fn kept_at(&self, cutoff: Priority) -> bool {
1645        (self.priority as u8) >= (cutoff as u8)
1646    }
1647}
1648
1649#[cfg(test)]
1650mod tests {
1651    use super::*;
1652
1653    #[test]
1654    fn the_four_readiness_states_are_one_axis_and_only_one_shows_content() {
1655        // Mutually exclusive is the test for one enum against several fields: a
1656        // region shows its content, or that it is coming, or that there is none,
1657        // or that it broke. Never two.
1658        assert!(Readiness::Ready.shows_content());
1659        for state in [Readiness::Pending, Readiness::Empty, Readiness::Failed] {
1660            assert!(!state.shows_content());
1661        }
1662    }
1663
1664    #[test]
1665    fn an_empty_region_is_not_a_broken_one() {
1666        // An empty list is the normal state of a new install. Drawing it in a
1667        // danger tone reports a fault where there is none, and this is the one
1668        // place the distinction is carried.
1669        assert_eq!(Readiness::Empty.tone(), Tone::Neutral);
1670        assert_eq!(Readiness::Failed.tone(), Tone::Danger);
1671        assert_eq!(Readiness::Pending.tone(), Tone::Neutral);
1672    }
1673
1674    #[test]
1675    fn a_column_can_be_sorted_without_being_sortable() {
1676        // Both combinations mean something, which is why the two fields are
1677        // independent rather than one implying the other. A list ordered by a
1678        // key the user cannot change is a real thing with a caret worth drawing.
1679        let fixed = Column {
1680            sorted: Some(Sort::Descending),
1681            ..Column::new("Created")
1682        };
1683
1684        assert!(!fixed.sortable);
1685        assert_eq!(fixed.sorted.map(Sort::as_str), Some("descending"));
1686
1687        let offered = Column {
1688            sortable: true,
1689            ..Column::new("Name")
1690        };
1691        assert_eq!(offered.sorted, None);
1692    }
1693
1694    #[test]
1695    fn a_direction_flips_and_says_what_it_is() {
1696        assert_eq!(Sort::Ascending.reversed(), Sort::Descending);
1697        assert_eq!(Sort::Descending.reversed().reversed(), Sort::Descending);
1698        assert_eq!(Sort::Ascending.as_str(), "ascending");
1699    }
1700
1701    #[test]
1702    fn a_figure_carries_its_tone_because_no_renderer_can_derive_it() {
1703        // Three of goingson's five sites tone the figure by their own means, so
1704        // tone is carried at every site that needs it and derived at none. The
1705        // same reasoning `Meter` reached, from a different direction.
1706        let streak = Figure::new("0", "Current Streak").tone(Tone::Warning);
1707        assert_eq!(streak.tone, Tone::Warning);
1708        assert_eq!(Figure::new("17", "Total").tone, Tone::Neutral);
1709    }
1710
1711    #[test]
1712    fn a_figures_value_is_text_because_only_the_app_knows_what_it_is() {
1713        // "84%", "12/30", "3d". A figure is whatever the app computed, already
1714        // formatted, and that is the line between this and `Meter`: a meter is
1715        // a proportion a renderer draws, a figure is a fact it sets in type.
1716        for value in ["84%", "12/30", "3d"] {
1717            assert_eq!(Figure::new(value, "Rate").value, value);
1718        }
1719    }
1720
1721    #[test]
1722    fn a_proportion_is_a_row_part_and_takes_no_intent_of_its_own() {
1723        // The meter carries the tone, so a part-level intent underneath would
1724        // fight it. Same answer `Tokens` needed, for the same reason.
1725        assert_eq!(RowPart::Proportion.intent(), RowPart::Tokens.intent());
1726        assert!(!RowPart::Proportion.revealed_on_hover());
1727    }
1728
1729    #[test]
1730    fn a_file_field_is_drawn_and_offers_no_options() {
1731        // It is a control the user operates, unlike `Hidden`, and it does not
1732        // pick from a list the description carries, unlike `Select`.
1733        assert!(FieldKind::File.visible());
1734        assert!(!FieldKind::File.offers_options());
1735        assert!(!FieldKind::File.confidential());
1736    }
1737
1738    #[test]
1739    fn a_constraint_is_a_fact_about_the_question_and_not_a_verdict() {
1740        // The whole model: the description carries the rule, the renderer emits
1741        // its host's idiom, and `error` is what arrives back when someone
1742        // validated. Nothing here decides a value is wrong.
1743        let field = Field {
1744            max_length: Some(100),
1745            min: Some("1"),
1746            max: Some("240"),
1747            required: true,
1748            ..Field::new(FieldKind::Number, "minutes", "Minutes")
1749        };
1750        assert!(!field.invalid());
1751
1752        // A bound is text because it is only a number for some of the kinds
1753        // that take one. goingson has both shapes live.
1754        let when = Field {
1755            min: Some("2026-08-09T14:30"),
1756            ..Field::new(FieldKind::Text, "starts", "Starts")
1757        };
1758        assert_eq!(when.min, Some("2026-08-09T14:30"));
1759    }
1760
1761    #[test]
1762    fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
1763        // The whole reason this is a pair. goingson's `Task::time_progress`
1764        // clamps to 100 and then carries `is_over_estimate` beside it to say
1765        // what the clamp dropped; a meter says both from one fact.
1766        let over = Meter::new(45, 30);
1767        assert_eq!(over.percent(), 100);
1768        assert!(over.overflowing());
1769
1770        let exact = Meter::new(30, 30);
1771        assert_eq!(exact.percent(), over.percent());
1772        assert!(!exact.overflowing());
1773    }
1774
1775    #[test]
1776    fn an_empty_set_does_not_divide_by_zero() {
1777        // Sayable on purpose, so it has to be answerable. A meter over an
1778        // unloaded count is what an app actually has for a frame.
1779        let none = Meter::new(0, 0);
1780        assert_eq!(none.percent(), 0);
1781        assert!(none.is_empty());
1782        assert!(!none.overflowing());
1783    }
1784
1785    #[test]
1786    fn the_ratio_survives_where_a_percentage_would_not() {
1787        // Given 43 nothing can recover "3 of 7", which is why the numbers are
1788        // carried and the label names only the noun.
1789        let m = Meter::new(3, 7).label("subtasks");
1790        assert_eq!(m.percent(), 42);
1791        assert_eq!((m.done, m.total), (3, 7));
1792        assert_eq!(m.label, Some("subtasks"));
1793    }
1794
1795    #[test]
1796    fn tone_is_carried_because_no_renderer_can_derive_it() {
1797        // The same fullness means opposite things on two of goingson's bars,
1798        // and only the app knows which.
1799        let subtasks = Meter::new(9, 10).tone(Tone::Success);
1800        let estimate = Meter::new(9, 10).tone(Tone::Danger);
1801        assert_eq!(subtasks.percent(), estimate.percent());
1802        assert_ne!(subtasks.tone, estimate.tone);
1803        // Untoned by default: a bar says nothing about status until something
1804        // says so, the same way a row is not selectable until told.
1805        assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
1806    }
1807
1808    #[test]
1809    fn a_meter_does_not_overflow_on_large_counts() {
1810        // done * 100 in u32 would wrap somewhere past 42 million. Counts that
1811        // size are not tasks, but a description layer that silently reports 3%
1812        // for a full bar is worse than one that is slow.
1813        let big = Meter::new(u32::MAX, u32::MAX);
1814        assert_eq!(big.percent(), 100);
1815        assert!(!big.overflowing());
1816    }
1817
1818    #[test]
1819    fn inset_is_raised_with_the_light_moved() {
1820        let (rl, rd) = Bevel::Raised.edges();
1821        let (il, id) = Bevel::Inset.edges();
1822        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
1823        assert_eq!((il, id), (rd, rl));
1824    }
1825
1826    #[test]
1827    fn pressing_twice_is_a_no_op() {
1828        for b in [Bevel::Raised, Bevel::Inset] {
1829            assert_eq!(b.pressed().pressed(), b);
1830        }
1831    }
1832
1833    #[test]
1834    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
1835        // The bug this vocabulary exists to make unrepresentable.
1836        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1837        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
1838        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
1839        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
1840    }
1841
1842    #[test]
1843    fn state_is_orthogonal_to_depth() {
1844        // The reason State is its own axis and not a Depth member: a disabled
1845        // button and a disabled field are both disabled and are not the same
1846        // shape, which one shared variant could not have said.
1847        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1848        assert_eq!(Depth::Well.fill(), Some(Fill::Well));
1849        assert!(State::Disabled.suppresses_interaction());
1850    }
1851
1852    #[test]
1853    fn only_disabled_stops_answering() {
1854        // Focus is a thing you can still click. Getting this backwards is how
1855        // a focus ring ends up on something inert.
1856        assert!(!State::Focus.suppresses_interaction());
1857        assert!(State::Disabled.suppresses_interaction());
1858    }
1859
1860    #[test]
1861    fn both_states_resolve_against_intents_makeover_already_derives() {
1862        // Neither needs a new token, so this costs no `makeover` release.
1863        assert_eq!(State::Focus.token(), "focus-ring");
1864        assert_eq!(State::Disabled.token(), "content-muted");
1865    }
1866
1867    #[test]
1868    fn flat_has_neither_edge_nor_fill() {
1869        assert_eq!(Depth::Flat.bevel(), None);
1870        assert_eq!(Depth::Flat.fill(), None);
1871    }
1872
1873    #[test]
1874    fn sunken_is_recessed_by_colour_with_no_edge() {
1875        // The one member carrying a fill without a bevel. A renderer that
1876        // assumes the two arrive together drops the fill silently, which is
1877        // exactly what makeover-webview did before 0.3.0.
1878        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
1879        assert_eq!(Depth::Sunken.bevel(), None);
1880    }
1881
1882    #[test]
1883    fn sunken_and_flat_are_different_claims() {
1884        // Both edgeless, and only one of them needs a colour. Collapsing them
1885        // is what left an unchosen tab unsayable.
1886        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
1887        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
1888    }
1889
1890    #[test]
1891    fn a_sunken_surface_is_not_a_well() {
1892        // Authored in opposite directions: makeover derives surface-well by
1893        // inverting against the theme's content colour, while surface-sunken is
1894        // authored and may sit darker than raised.
1895        assert_ne!(Fill::Sunken, Fill::Well);
1896        assert_eq!(Fill::Sunken.token(), "surface-sunken");
1897        assert_eq!(Fill::Well.token(), "surface-well");
1898    }
1899
1900    #[test]
1901    fn every_selector_describes_both_of_its_states() {
1902        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
1903        // unchosen option fell through to Flat at every renderer.
1904        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
1905            assert_ne!(
1906                s.chosen(),
1907                s.unchosen(),
1908                "{s:?} cannot tell picked from unpicked"
1909            );
1910        }
1911    }
1912
1913    #[test]
1914    fn only_a_tab_inverts_the_other_way() {
1915        // Tabs recede so the chosen one comes forward; a segment and a toggle
1916        // stand up so the chosen one is held in. That inversion is the whole
1917        // content of "picked" once colour is deferred, and it is why the three
1918        // are not one member with a flag.
1919        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1920        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1921
1922        for s in [Selector::Segmented, Selector::Toggle] {
1923            assert_eq!(s.unchosen(), Depth::Raised);
1924            assert_eq!(s.chosen(), Depth::Well);
1925            // Held in is what pressing produces: one appearance, two reasons.
1926            assert_eq!(s.unchosen().pressed(), s.chosen());
1927        }
1928    }
1929
1930    #[test]
1931    fn pressing_a_card_makes_a_well() {
1932        assert_eq!(Depth::Raised.pressed(), Depth::Well);
1933        assert_eq!(
1934            Depth::Raised.pressed().bevel(),
1935            Depth::Raised.bevel().map(Bevel::pressed)
1936        );
1937        // Only raised regions respond to being pressed.
1938        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
1939        assert_eq!(Depth::Well.pressed(), Depth::Well);
1940    }
1941
1942    #[test]
1943    fn intents_name_makeover_tokens_and_nothing_else() {
1944        assert_eq!(Edge::Light.token(), "bevel-light");
1945        assert_eq!(Edge::Dark.token(), "bevel-dark");
1946        assert_eq!(Fill::Raised.token(), "surface-raised");
1947        assert_eq!(Fill::Well.token(), "surface-well");
1948        // No value ever leaves this crate.
1949        for t in [
1950            Edge::Light.token(),
1951            Edge::Dark.token(),
1952            Tone::Danger.token(),
1953            Tone::Neutral.token(),
1954            State::Focus.token(),
1955            State::Disabled.token(),
1956        ] {
1957            assert!(!t.starts_with('#'), "{t} looks like a value");
1958            assert!(
1959                !t.chars().next().unwrap().is_ascii_digit(),
1960                "{t} is a value"
1961            );
1962        }
1963    }
1964
1965    #[test]
1966    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
1967        // The one line that runs through all three apps' taxonomies.
1968        assert!(!Token::Badge.interactive());
1969        assert!(Token::Chip { removable: false }.interactive());
1970        assert!(Token::Chip { removable: true }.interactive());
1971
1972        // A badge is a label, so giving it an edge would lie about it.
1973        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1974        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1975
1976        // A latched chip wears the same shape a pressed one does.
1977        let chip = Token::Chip { removable: false };
1978        assert_eq!(chip.depth(false), Depth::Raised);
1979        assert_eq!(chip.depth(true), Depth::Raised.pressed());
1980    }
1981
1982    #[test]
1983    fn a_toast_and_a_banner_differ_in_more_than_placement() {
1984        assert!(Notice::Toast.transient());
1985        assert!(!Notice::Banner.transient());
1986        // A toast floats above the page; a banner rests in the flow.
1987        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1988        assert_eq!(Notice::Banner.fill(), Fill::Raised);
1989    }
1990
1991    #[test]
1992    fn only_the_actions_part_hides_until_hovered() {
1993        for p in [
1994            RowPart::Primary,
1995            RowPart::Secondary,
1996            RowPart::Meta,
1997            RowPart::Tokens,
1998        ] {
1999            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
2000        }
2001        assert!(RowPart::Actions.revealed_on_hover());
2002        // Emphasis falls off down the row, and never rises again.
2003        assert_eq!(RowPart::Primary.intent(), "content");
2004        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
2005        assert_eq!(RowPart::Meta.intent(), "content-muted");
2006    }
2007
2008    #[test]
2009    fn a_token_part_carries_no_intent_of_its_own() {
2010        // Each token carries its own tone, so a part-level intent underneath
2011        // would fight the thing sitting on it. Same reasoning as actions, which
2012        // is why they answer alike.
2013        assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
2014        assert_eq!(RowPart::Tokens.intent(), "content");
2015    }
2016
2017    #[test]
2018    fn a_separator_is_what_tells_a_section_from_a_subsection() {
2019        assert!(Heading::Section.separated());
2020        assert!(!Heading::Subsection.separated());
2021        assert!(!Heading::Page.separated());
2022    }
2023
2024    #[test]
2025    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
2026        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2027        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
2028        // The exception, and the whole folder semantic: the open tab joins its
2029        // pane rather than sinking away from it.
2030        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
2031
2032        // A held-in segment is indistinguishable from a pressed raised one,
2033        // which is the economy the light model buys over a colour swap.
2034        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
2035
2036        // A toggle stands alone; the other two are built out of parts that
2037        // touch.
2038        assert!(Selector::Segmented.abutting());
2039        assert!(Selector::Tabs.abutting());
2040        assert!(!Selector::Toggle.abutting());
2041    }
2042
2043    #[test]
2044    fn a_pane_is_looked_into_and_a_band_is_not() {
2045        assert_eq!(Region::Pane.depth(), Depth::Well);
2046        assert_eq!(Region::Modal.depth(), Depth::Raised);
2047        for r in [
2048            Region::Band,
2049            Region::Sidebar,
2050            Region::Split,
2051            Region::TabGroup,
2052        ] {
2053            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
2054        }
2055    }
2056
2057    #[test]
2058    fn exactly_one_region_is_opaque() {
2059        // The escape hatch is one member and stays one member. If a second
2060        // undescribed region ever appears, the description has started
2061        // conceding rather than deferring.
2062        for r in [
2063            Region::Band,
2064            Region::Sidebar,
2065            Region::Pane,
2066            Region::Split,
2067            Region::TabGroup,
2068            Region::Modal,
2069        ] {
2070            assert!(r.described(), "{r:?} should be describable");
2071        }
2072        assert!(!Region::Bespoke { name: "day-plan" }.described());
2073    }
2074
2075    #[test]
2076    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
2077        // The app owns the contents, not the placement. An app that wants its
2078        // timeline in a well frames it in a Pane.
2079        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
2080        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
2081    }
2082
2083    #[test]
2084    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
2085        // The argument the member exists for: goingson's day-plan has to be
2086        // routable, or the description covers only the boring screens and the
2087        // interesting four need a second path beside the router.
2088        let day_plan = [
2089            Region::Band,
2090            Region::Bespoke { name: "day-plan" },
2091            Region::Sidebar,
2092        ];
2093        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
2094        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
2095    }
2096
2097    #[test]
2098    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
2099        let secret = Field::new(FieldKind::Secret, "password", "Password");
2100        assert!(secret.kind.confidential());
2101        assert!(secret.kind.visible());
2102
2103        assert!(!FieldKind::Hidden.visible());
2104        // Nothing else is confidential, or the marker means nothing.
2105        for k in [
2106            FieldKind::Text,
2107            FieldKind::Number,
2108            FieldKind::Textarea,
2109            FieldKind::Select,
2110            FieldKind::Checkbox,
2111            FieldKind::Hidden,
2112        ] {
2113            assert!(!k.confidential(), "{k:?} should not be confidential");
2114        }
2115
2116        // Only a checkbox carries its own label.
2117        assert!(FieldKind::Checkbox.labels_itself());
2118        assert!(!FieldKind::Text.labels_itself());
2119    }
2120
2121    #[test]
2122    fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
2123        let text = Field::new(FieldKind::Text, "title", "Title");
2124        assert!(text.options.is_empty());
2125        assert_eq!(text.placeholder, None);
2126
2127        let sizes = [Choice::plain("small"), Choice::plain("large")];
2128        let select = Field::select("size", "Size", &sizes);
2129        assert_eq!(select.kind, FieldKind::Select);
2130        assert_eq!(select.options.len(), 2);
2131    }
2132
2133    #[test]
2134    fn a_choice_says_what_submits_and_what_is_read_apart() {
2135        // The whole reason it is two strings. `plain` is the case where they
2136        // coincide, and it is a shorthand rather than the general shape.
2137        let plain = Choice::plain("7");
2138        assert_eq!((plain.value, plain.label), ("7", "7"));
2139
2140        let spelled = Choice {
2141            value: "7",
2142            label: "One week",
2143        };
2144        assert_ne!(spelled.value, spelled.label);
2145    }
2146
2147    #[test]
2148    fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
2149        // Both offer a fixed set and both read `options`, so the two
2150        // constructors differ in exactly one thing. That one thing is the
2151        // point: a renderer decides whether the alternatives are readable
2152        // without opening anything, and it can only decide that if the
2153        // description said which question was asked.
2154        let styles = [
2155            Choice {
2156                value: "copy",
2157                label: "Copy samples in",
2158            },
2159            Choice {
2160                value: "reference",
2161                label: "Reference in place",
2162            },
2163        ];
2164        let radio = Field::radio("storage", "Storage style", &styles);
2165        let select = Field::select("storage", "Storage style", &styles);
2166
2167        assert_eq!(radio.kind, FieldKind::Radio);
2168        assert_ne!(radio.kind, select.kind);
2169        assert_eq!(radio.options, select.options);
2170        assert_eq!(
2171            Field {
2172                kind: select.kind,
2173                ..radio
2174            },
2175            select
2176        );
2177    }
2178
2179    #[test]
2180    fn exactly_the_option_taking_kinds_say_so() {
2181        // The renderers branch on this rather than on a list of their own, so
2182        // a kind added without a decision here renders its options nowhere.
2183        assert!(FieldKind::Select.offers_options());
2184        assert!(FieldKind::Radio.offers_options());
2185        for kind in [
2186            FieldKind::Text,
2187            FieldKind::Secret,
2188            FieldKind::Number,
2189            FieldKind::Email,
2190            FieldKind::Url,
2191            FieldKind::Tel,
2192            FieldKind::Textarea,
2193            FieldKind::Checkbox,
2194            FieldKind::Hidden,
2195        ] {
2196            assert!(!kind.offers_options(), "{kind:?} does not offer options");
2197        }
2198    }
2199
2200    #[test]
2201    fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
2202        // The near-miss: each option is labelled beside its own button, so a
2203        // renderer could plausibly read the group as self-labelling and drop
2204        // the question. Checkbox is the only kind that does that.
2205        assert!(!FieldKind::Radio.labels_itself());
2206        assert!(FieldKind::Checkbox.labels_itself());
2207    }
2208
2209    #[test]
2210    fn a_select_with_no_options_is_sayable() {
2211        // An app whose option list has not loaded has exactly this. Making it
2212        // unrepresentable would push the state somewhere less visible, and a
2213        // renderer drawing an empty select reports it on screen.
2214        let loading = Field::select("project", "Project", &[]);
2215        assert!(loading.options.is_empty());
2216    }
2217
2218    #[test]
2219    fn the_description_carries_the_question_and_never_the_answer() {
2220        // The line 0.8.0 drew. Placeholder and options are properties of what
2221        // is being asked; the current value is what came back, and no field
2222        // here holds one.
2223        let f = Field {
2224            placeholder: Some("yyyy-mm-dd"),
2225            ..Field::new(FieldKind::Text, "due", "Due")
2226        };
2227        assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
2228        // A placeholder is not a label, and having one does not excuse the
2229        // field from carrying the other.
2230        assert_eq!(f.label, "Due");
2231    }
2232
2233    #[test]
2234    fn a_field_reports_its_own_error_state() {
2235        let mut f = Field::new(FieldKind::Text, "title", "Title");
2236        assert!(!f.invalid());
2237        f.error = Some("Required");
2238        assert!(f.invalid());
2239    }
2240
2241    #[test]
2242    fn columns_drop_by_priority_and_never_by_position() {
2243        let cols = [
2244            Column {
2245                width: Width::Fill,
2246                priority: Priority::Essential,
2247                ..Column::new("Title")
2248            },
2249            Column {
2250                width: Width::Fixed,
2251                priority: Priority::Secondary,
2252                ..Column::new("Due")
2253            },
2254            Column {
2255                width: Width::Fixed,
2256                priority: Priority::Optional,
2257                ..Column::new("Estimate")
2258            },
2259        ];
2260
2261        // Widest: everything survives.
2262        assert_eq!(
2263            cols.iter()
2264                .filter(|c| c.kept_at(Priority::Optional))
2265                .count(),
2266            3
2267        );
2268        // Narrower: the optional column goes first.
2269        let kept: Vec<_> = cols
2270            .iter()
2271            .filter(|c| c.kept_at(Priority::Secondary))
2272            .map(|c| c.name)
2273            .collect();
2274        assert_eq!(kept, ["Title", "Due"]);
2275        // Narrowest: only what identifies the row.
2276        let kept: Vec<_> = cols
2277            .iter()
2278            .filter(|c| c.kept_at(Priority::Essential))
2279            .map(|c| c.name)
2280            .collect();
2281        assert_eq!(kept, ["Title"]);
2282    }
2283
2284    #[test]
2285    fn inserting_a_column_does_not_move_what_gets_dropped() {
2286        // The bug the ordinal form has and this form cannot: goingson hides
2287        // `nth-child(n+5)` against a seven-column table, so a column inserted
2288        // anywhere to the left silently hides a different one.
2289        let before = [
2290            Column::new("Title"),
2291            Column {
2292                width: Width::Fixed,
2293                priority: Priority::Optional,
2294                ..Column::new("Estimate")
2295            },
2296        ];
2297        let after = [
2298            Column::new("Title"),
2299            Column::new("Project"), // inserted
2300            Column {
2301                width: Width::Fixed,
2302                priority: Priority::Optional,
2303                ..Column::new("Estimate")
2304            },
2305        ];
2306
2307        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
2308            cols.iter()
2309                .filter(|c| !c.kept_at(Priority::Secondary))
2310                .map(|c| c.name)
2311                .collect()
2312        }
2313        assert_eq!(dropped(&before), ["Estimate"]);
2314        assert_eq!(dropped(&after), ["Estimate"]);
2315    }
2316
2317    #[test]
2318    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
2319        // goingson uses the tab group inside the content region rather than
2320        // instead of one, so it is not a third arrangement.
2321        let go = Arrangement::ListDetail { tabbed: true };
2322        let plain = Arrangement::ListDetail { tabbed: false };
2323        assert_ne!(go, plain);
2324        assert_ne!(go, Arrangement::SidebarContent);
2325    }
2326
2327    #[test]
2328    fn readiness_names_the_state_and_not_the_shimmer() {
2329        // Two members and no third. If a skeleton ever appears in this enum,
2330        // the deferral rule has been broken.
2331        assert_ne!(Readiness::Ready, Readiness::Pending);
2332    }
2333}