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