Skip to main content

makeover_layout/
lib.rs

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