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//! 0.15.0 adds [`FieldKind::Date`] and [`FieldKind::DateTime`], on the argument
182//! [`FieldKind::Email`] was admitted on: a webview emits a different `type=`,
183//! which is a native picker, the platform's validation and a different keyboard
184//! on a touch device. Described as text with a "YYYY-MM-DD" hint, all three are
185//! lost.
186//!
187//! Two members and not one or five, from a count rather than from symmetry: 13
188//! sites of `date` and 13 of `datetime-local` across the MNW server and
189//! goingson, and zero of `time`, `month` or `week`. The wire format each takes
190//! is named here as [`DATE_FORMAT`] and [`DATETIME_FORMAT`], because a host
191//! left to pick its own would disagree with a server silently, and
192//! [`FieldKind::temporal`] is the pair asked about once rather than at each
193//! renderer. `FieldKind`'s own comment claiming `radio` was the last HTML input
194//! type missing was already false when 0.8.1 wrote it; these are what it was
195//! missing.
196//!
197//! What each of the 0.12.0 findings deliberately leaves out is the address — what pressing a
198//! header calls, and where an empty state's "Add your first project" button
199//! goes. That is the boundary this crate is defined by, and four findings moved
200//! across it rather than being answered here.
201//!
202//! 0.19.0 narrows [`State`] to [`State::Disabled`] alone. `State::Focus` is
203//! gone: a description never states what has focus, because what focus *is*
204//! differs per host and every renderer had already decided for itself — the
205//! webview draws it from `:focus-visible`, egui refused the variant outright,
206//! and quasi-tui honoured it once at startup and overrode it thereafter.
207//!
208//! 0.20.0 adds [`Region::Widget`], the third tier, and `#[non_exhaustive]` to
209//! [`Region`] with it. Every vocabulary finding until now had two answers
210//! available — grow the primitive set, or [`Region::Bespoke`] — and a whole
211//! class of thing is wrong for both. A carousel is not a primitive, because a
212//! terminal has none and that is the test `Node::Html` failed. It is not
213//! bespoke either, because bespoke is what one app owns and every part of a
214//! carousel is furniture plus members this crate already has.
215//!
216//! The cost of the binary was that refusing a primitive was expensive: the app
217//! hand-rolls the thing forever, so the pressure always ran toward growing the
218//! primitive set with one host's idioms. A named assembly changes what "no"
219//! costs without changing what the vocabulary can say.
220//!
221//! MNW's carousel is the first consumer and was the finding that started it: one
222//! partial, three pages, an ordered set of frames with a position, prev/next and
223//! a dot strip, all of it sayable already and none of it nameable. See wiki
224//! `widget-tier` for the ownership model, which is why this member carries a
225//! name a renderer may decline to know.
226//!
227//! 0.21.0 adds [`Image`] and [`Fit`], found by trying to describe MNW's
228//! carousel under 0.20.0's widget tier and getting one step in. Nothing named a
229//! picture. The vocabulary could say a number with a caption, a badge, a meter
230//! and a table, and could not say the thing three of MNW's public pages are
231//! mostly made of.
232//!
233//! It reads as an oversight and is a measurement: 24 `<img>` sites across 22
234//! MNW templates, against one in goingson and none in Balanced Breakfast or
235//! audiofiles. A picture is furniture a *content platform* has, and MNW is the
236//! only one in the tree, so the evidence never arrived from the two-app
237//! direction the earlier rule looked in. Under the generic-against-bespoke bar
238//! it is not close: a picture is not one app's own.
239//!
240//! A primitive rather than a widget, which is worth stating now that the tier
241//! makes it a real question. A widget is an assembly of things already sayable
242//! and a picture is a leaf, assembled from nothing. It also passes the test
243//! `Node::Html` failed — every host has an honest answer, including a terminal,
244//! which has a graphics protocol or has [`Image::alt`].
245//!
246//! [`Image`] carries no source, the split [`Act`] already makes: an address is
247//! not this crate's to hold. See its own docs, which is where the argument is.
248//!
249//! # Reach, focus and the focus ring
250//!
251//! Three terms, and no others, for what 0.19.0 moved out of the description.
252//! **Reach** is which things can take focus and in what order; a browser reads
253//! it off the document, a TUI derives it from draw order, egui from its own id
254//! stack. **Focus** is which reached thing has the keyboard right now: the
255//! renderer's, live, never described and never round-tripped through a
256//! description. The **focus ring** is the visible cue; the token (`focus-ring`,
257//! derived by `makeover` from the action colour) is the one shared artifact and
258//! the drawing is the renderer's. Retired as names for any of this: "focus
259//! stroke", "focus cue", "wants focus". "Caret" is a different thing — the text
260//! cursor inside a field — and keeps its name.
261//!
262//! # Where the description stops
263//!
264//! A day-plan timeline, a kanban board and a calendar are not describable here
265//! and will not become describable. A description expressive enough to produce
266//! a timeline is a component library wearing a description's name. Generate the
267//! boring 80% so the bespoke 20% gets the attention.
268//!
269//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
270//! description names the *place* and the app owns the contents, so a screen
271//! containing a timeline is still a whole screen and still routable. Without
272//! it, the four goingson screens that make the app worth using would need a
273//! second, undescribed path beside the router, and two paths is how a
274//! vocabulary starts drifting from its app again.
275//!
276//! [`Region::Widget`] sits between that limit and the primitives, and it does
277//! not move the limit. A widget is an assembly of members this crate *already*
278//! has, under a name a renderer may or may not recognise. Anything that needs a
279//! member the vocabulary does not have is still a finding about the vocabulary
280//! or still bespoke; naming an assembly buys no new expressive power, which is
281//! exactly why it is safe to let the set grow outside this crate.
282
283#![forbid(unsafe_code)]
284
285/// A colour intent this crate refers to but never resolves.
286///
287/// The string is the token name `makeover` publishes, so a renderer can look
288/// it up without this crate knowing what colour came back.
289pub trait Intent {
290    /// The `makeover` intent token this resolves against.
291    fn token(self) -> &'static str;
292}
293
294/// Which way the light falls across a two-tone edge.
295///
296/// The whole content of a bevel, once colour and thickness are deferred. The
297/// light is always assumed to come from the top left: every consumer measured
298/// agreed on that and none of them ever varied it, so it is an invariant here
299/// rather than a parameter.
300///
301/// # The two corners that belong to both edges
302///
303/// Top-right and bottom-left are where the lit run meets the shaded one, and
304/// the description's claim is that they belong to *both*. How a renderer says
305/// that is its own business, because the answer is bounded by resolution and
306/// not by taste:
307///
308/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
309///   to one tone thickens that edge by a cell and reads as one run overrunning
310///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
311///   splits it and recovers real information. Its box-drawing fallback cannot:
312///   a single stroke has no half to give, so there both corners go to dark.
313/// - A pixel bevel is a one-point stroke by default, which makes the corner a
314///   one-point square. There is nothing to divide — a diagonal seam across one
315///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
316///   already produces. So `makeover-immediate` mitres and is *not* diverging;
317///   it is the same rule at a resolution where the split degenerates.
318///
319/// Stated here so the difference reads as a decision rather than as drift. A
320/// renderer with room to divide the corner should; one without should mitre or
321/// pick the shaded tone, and neither is a bug.
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
323pub enum Bevel {
324    /// Lit from the top left: light on top and left, dark on bottom and right.
325    Raised,
326    /// The same edge inverted, which is also the pressed state of anything
327    /// that draws itself [`Bevel::Raised`].
328    Inset,
329}
330
331impl Bevel {
332    /// The edge intents, as `(top_left, bottom_right)`.
333    ///
334    /// Split out from any painting because the inversion *is* the idea, and
335    /// it is the one part every renderer implements identically.
336    #[must_use]
337    pub const fn edges(self) -> (Edge, Edge) {
338        match self {
339            Self::Raised => (Edge::Light, Edge::Dark),
340            Self::Inset => (Edge::Dark, Edge::Light),
341        }
342    }
343
344    /// Pressing inverts. A raised control reads as inset while held.
345    ///
346    /// Stated here rather than left to each consumer because a cascade can
347    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
348    /// resolves this per call site, eighteen times.
349    #[must_use]
350    pub const fn pressed(self) -> Self {
351        match self {
352            Self::Raised => Self::Inset,
353            Self::Inset => Self::Raised,
354        }
355    }
356}
357
358/// One side of a bevel, named by the intent it takes.
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
360pub enum Edge {
361    /// The lit side.
362    Light,
363    /// The shadowed side.
364    Dark,
365}
366
367impl Intent for Edge {
368    fn token(self) -> &'static str {
369        match self {
370            Self::Light => "bevel-light",
371            Self::Dark => "bevel-dark",
372        }
373    }
374}
375
376/// A surface intent a region is filled with.
377///
378/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
379/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
380/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
381/// `makeover-immediate` at compile time and left neither able to move until
382/// both published. The vocabulary exists to grow and the renderers exist to
383/// disagree about how much of it they answer, so growth must not be a
384/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
385/// resolved through a fallible lookup, and a missing intent is answered with
386/// structure rather than with a substituted colour.
387///
388/// [`Sunken`]: Fill::Sunken
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
390#[non_exhaustive]
391pub enum Fill {
392    /// The page behind everything.
393    Page,
394    /// A surface lifted off the page: cards, controls, menus, toasts.
395    Raised,
396    /// A surface floating above the page rather than resting on it.
397    Overlay,
398    /// The inside of a well.
399    Well,
400    /// A surface set back from the one it sits on, by colour and nothing else.
401    ///
402    /// Not a well. A well is a hole with an edge, and the two are authored in
403    /// opposite directions: `makeover` derives `surface-well` by inverting
404    /// against the theme's own content colour, while `surface-sunken` is
405    /// authored and free to sit darker than raised (goingson's does). Naming
406    /// only the well left the recessed-with-no-edge surface unsayable, which is
407    /// what an unchosen tab is: it recedes so the chosen one can come forward,
408    /// and it carries no bevel of its own.
409    ///
410    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
411    /// and could not delete the line because no member described it.
412    Sunken,
413}
414
415// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
416// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
417// had something to paint. makeover-tui found that wrong within a day: page is
418// the surface a well is usually cut into, so on a terminal that substitution
419// produces exactly the invisibility it was meant to prevent, and the right
420// answer there is a drawn edge rather than a different colour.
421//
422// Substituting one intent for another is renderer policy. The description says
423// what the region is and stops.
424
425impl Intent for Fill {
426    fn token(self) -> &'static str {
427        match self {
428            Self::Page => "surface-page",
429            Self::Raised => "surface-raised",
430            Self::Overlay => "surface-overlay",
431            Self::Well => "surface-well",
432            Self::Sunken => "surface-sunken",
433        }
434    }
435}
436
437/// How a region sits relative to the surface behind it.
438///
439/// Fill and bevel are named together because naming them apart is what let
440/// them disagree. Every consumer measured had at least one region carrying a
441/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
442/// and recorded the bug in its doc comment, and Balanced Breakfast still had
443/// twelve of them a year later. A single name for the pair makes that
444/// unrepresentable.
445/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
446/// release: a depth this renderer has no drawing for should cost it a
447/// wildcard arm, not a compile error and a wait on someone else's publish.
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
449#[non_exhaustive]
450pub enum Depth {
451    /// Level with its surroundings. No edge.
452    Flat,
453    /// A card laid on the panel it sits in.
454    Raised,
455    /// A hole in the panel, with content down inside it. For anything the
456    /// user looks *into*: a table body, a tag tree, a text field.
457    Well,
458    /// Set back from what it sits on, by colour alone. No edge.
459    ///
460    /// The one member carrying a fill without a bevel, so a renderer cannot
461    /// assume the two arrive together. That is deliberate and it is still the
462    /// pairing rule: both halves come off the same `Depth`, so they cannot
463    /// disagree, and here one half is legitimately absent.
464    ///
465    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
466    /// Recessed and level-with are different claims, and only one of them
467    /// needs a colour.
468    Sunken,
469    /// A surface sitting *over* the page rather than in it. A modal, a popover,
470    /// a menu.
471    ///
472    /// Takes elevation and no bevel: a surface overlaying the page is lifted
473    /// off it, and a surface in the page is cut into it. That is the same
474    /// pairing rule the rest of the enum holds, applied to the one case where
475    /// the separation is not an edge at all — the lift and the scrim behind it
476    /// are already saying where the surface is.
477    ///
478    /// Every renderer had the surface before it had this variant.
479    /// `makeover-tui` carries `Palette::overlay`, `makeover-immediate` gained
480    /// `Palette::elevation` at 0.10.0, and `makeover-webview` emits
481    /// `--elevation-overlay`. What was missing was the route from a description
482    /// to any of them, which is why this is one variant rather than a feature.
483    Overlay,
484}
485
486impl Depth {
487    /// The edge this depth is drawn with, if it has one.
488    #[must_use]
489    pub const fn bevel(self) -> Option<Bevel> {
490        match self {
491            // Sunken joins Flat here, for the opposite reason: Flat has no edge
492            // because nothing separates it from its surroundings, and Sunken has
493            // none because its colour is already doing the separating.
494            Self::Flat | Self::Sunken => None,
495            // A third reason to have no edge, which is why it gets its own arm
496            // rather than joining the two above: an overlay is separated by the
497            // lift and by the scrim behind it, so an edge would be a second
498            // answer to a question already answered.
499            Self::Overlay => None,
500            Self::Raised => Some(Bevel::Raised),
501            Self::Well => Some(Bevel::Inset),
502        }
503    }
504
505    /// The surface this depth is filled with.
506    ///
507    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
508    /// which is the difference between level-with and painted-the-same-colour.
509    #[must_use]
510    pub const fn fill(self) -> Option<Fill> {
511        match self {
512            Self::Flat => None,
513            Self::Raised => Some(Fill::Raised),
514            Self::Well => Some(Fill::Well),
515            Self::Sunken => Some(Fill::Sunken),
516            Self::Overlay => Some(Fill::Overlay),
517        }
518    }
519
520    /// Pressing a raised region reads as a well, and nothing else moves.
521    ///
522    /// [`Depth::Overlay`] is untouched along with the rest: an overlay is a
523    /// surface, not a control, so there is nothing there to press.
524    #[must_use]
525    pub const fn pressed(self) -> Self {
526        match self {
527            Self::Raised => Self::Well,
528            other => other,
529        }
530    }
531}
532
533/// An interaction state a region can be in, beside whatever [`Depth`] it is.
534///
535/// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
536/// and a disabled field is still a [`Depth::Well`], so folding either member
537/// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
538/// something that is not a depth, and would leave disabled-button and
539/// disabled-field sharing one variant that cannot tell them apart.
540///
541/// # Why hover and pressed are not members
542///
543/// The line is whether every renderer has the state to express, not whether CSS
544/// does. Hover is renderer policy and `makeover-webview` says so in its own
545/// header: a terminal and an immediate-mode painter have no pointer hovering
546/// over anything, and pressed already arrives through [`Bevel::pressed`] and
547/// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
548/// rather than a separate condition.
549///
550/// Focus and disabled are different in kind. A TUI has a focused widget and a
551/// greyed-out one; so does egui. Both were unsayable here, so all three webview
552/// consumers supplied them from outside the primitive by out-specifying rules
553/// they did not own: goingson alone carries 19 of them, and the MNW server
554/// another 21. That is the divergence this crate exists to end, arriving one
555/// layer down.
556///
557/// # The principle this encodes
558///
559/// A primitive owns every state it implies. A renderer that emits a hover rule
560/// for a thing owes disabled and the capability answer for that same thing,
561/// because anything less exports the completion work to N consumers who will
562/// each do it differently.
563///
564/// Focus is not on that list and was removed from this axis in 0.19.0. It is
565/// the renderer's, decided after the description; see the crate header, "Reach,
566/// focus and the focus ring", for the three terms and who owns each.
567///
568/// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
569/// must not be a lockstep event across the three renderers.
570#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
571#[non_exhaustive]
572pub enum State {
573    /// Present, visible, and not answering.
574    ///
575    /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
576    /// control keeps the surface it always had and stops responding, so what
577    /// changes is its content and its interactivity rather than what it is.
578    Disabled,
579}
580
581impl State {
582    /// Whether a region in this state stops answering the pointer.
583    ///
584    /// Stated in the description rather than left to each renderer, on the same
585    /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
586    /// immediate-mode renderer resolves it per call site, so leaving it unsaid
587    /// means resolving it once per consumer and disagreeing.
588    #[must_use]
589    pub const fn suppresses_interaction(self) -> bool {
590        // A match rather than a bare `true`, so a member added to this
591        // `#[non_exhaustive]` axis has to answer the question rather than
592        // inheriting an answer.
593        match self {
594            Self::Disabled => true,
595        }
596    }
597}
598
599impl Intent for State {
600    fn token(self) -> &'static str {
601        match self {
602            // Reusing the muted content intent rather than minting a
603            // `disabled` colour. Disabled is a reduction and not a status, and
604            // `makeover-webview`'s progress rules already record the reading
605            // that `content-muted` is what disabled looks like.
606            Self::Disabled => "content-muted",
607        }
608    }
609}
610
611/// What a region is saying, when it is saying something.
612///
613/// The one intent family shared by badges, notices and nothing else. Kept
614/// separate from [`Fill`] because a surface is where a thing sits and a tone is
615/// what it means, and the three apps agree on the four statuses:
616/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
617/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
618/// `.toast.error` in Balanced Breakfast.
619///
620/// The per-tag palette (`category-one` through `category-six`) is deliberately
621/// not here. Which colour a *particular* tag takes is app domain, and both
622/// webview apps already carry it as a `data-color` attribute.
623#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
624pub enum Tone {
625    /// No status. Reads as ordinary de-emphasised content.
626    Neutral,
627    /// Something worth knowing and nothing to do about it.
628    Info,
629    /// Something finished and it worked.
630    Success,
631    /// Something the user should look at before continuing.
632    Warning,
633    /// Something broken, or something about to be destroyed.
634    Danger,
635}
636
637impl Intent for Tone {
638    fn token(self) -> &'static str {
639        match self {
640            // Neutral has no status token of its own. It takes the muted
641            // content intent, which is what both webview apps already spell as
642            // `data-color="muted"`.
643            Self::Neutral => "content-muted",
644            Self::Info => "info",
645            Self::Success => "success",
646            Self::Warning => "warning",
647            Self::Danger => "danger",
648        }
649    }
650}
651
652/// A small labelled thing that sits inside something else.
653///
654/// Two members, because the three apps drew three taxonomies and only one line
655/// runs through all of them: does it answer a click. audiofiles has
656/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
657/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
658/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
659/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
660/// to decide which of the two it always was.
661///
662/// The evidence that a chip is a real concept rather than a badge with a
663/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
664/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
665/// holds itself down", which is exactly what [`Depth::pressed`] already says.
666#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
667pub enum Token {
668    /// Non-interactive status or count. Answers no click.
669    Badge,
670    /// An interactive or removable token. Answers a click, and latches if it
671    /// stands for a filter that is either on or off.
672    Chip {
673        /// Whether it carries its own remove affordance.
674        removable: bool,
675    },
676}
677
678impl Token {
679    /// Whether this answers a click.
680    ///
681    /// The whole difference between the two members, and the reason a renderer
682    /// with no hover (a touch surface, a terminal) can still tell them apart.
683    #[must_use]
684    pub const fn interactive(self) -> bool {
685        matches!(self, Self::Chip { .. })
686    }
687
688    /// How it sits, given whether it is currently latched down.
689    ///
690    /// A badge is flat: it is a label, and giving it an edge would say it can
691    /// be pressed. A chip is raised, and inset while latched.
692    #[must_use]
693    pub const fn depth(self, latched: bool) -> Depth {
694        match self {
695            Self::Badge => Depth::Flat,
696            Self::Chip { .. } if latched => Depth::Well,
697            Self::Chip { .. } => Depth::Raised,
698        }
699    }
700}
701
702/// Something the app is telling the user, unprompted.
703///
704/// Two concepts, not one with a placement. They differ in more than where they
705/// sit: a toast is transient, stacked and self-dismissing, and a banner is
706/// persistent, in flow, one per region, and dismissed by fixing the condition
707/// it reports. Folding them into one member with a placement parameter would
708/// make lifetime, stacking and dismissal all placement-dependent, which is the
709/// description leaking renderer policy.
710///
711/// All three apps have banners: `info_banner` and `warning_banner` in
712/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
713/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
714/// webview apps also have toasts. So neither member is speculative, and no app
715/// gains a concept it lacks except audiofiles, whose renderer may legitimately
716/// decline to draw a toast at all.
717#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
718pub enum Notice {
719    /// Transient, stacked, dismisses itself.
720    Toast,
721    /// Persistent, in flow, one per region, dismissed by fixing the cause.
722    Banner,
723}
724
725impl Notice {
726    /// Whether it goes away on its own.
727    #[must_use]
728    pub const fn transient(self) -> bool {
729        matches!(self, Self::Toast)
730    }
731
732    /// How it sits.
733    ///
734    /// A toast floats above the page rather than resting on it, which is
735    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
736    /// flow. Both are raised, and they are raised off different things.
737    #[must_use]
738    pub const fn fill(self) -> Fill {
739        match self {
740            Self::Toast => Fill::Overlay,
741            Self::Banner => Fill::Raised,
742        }
743    }
744}
745
746/// The parts of a list row.
747///
748/// Four to begin with, taken from Balanced Breakfast, which was the only
749/// consumer that had all of them (`row-primary`, `row-secondary`, `row-meta`,
750/// `row-actions`). audiofiles has two and no slot structure at all, so it gains
751/// meta and actions as real work rather than a rename; goingson moves off
752/// `task-row` / `task-cell`.
753///
754/// [`Tokens`](Self::Tokens) joined at 0.9.0, and `#[non_exhaustive]` with it.
755/// See the crate header for why the two arrived together.
756///
757/// # Meta against Tokens
758///
759/// The line is whether the thing has its own standing. `Meta` is one short
760/// trailing fact about the row, written as text: a count, a size, a date.
761/// `Tokens` is a set of small labelled things, each of which can be toned and
762/// can answer a click. "3 files" is meta. A status badge that is amber, and a
763/// tag you can click to filter by, are tokens.
764///
765/// Keeping them apart is what a single widened slot would have foreclosed. A
766/// renderer can right-align one string and cannot usefully do the same to a
767/// strip of chips, and a fact that is not clickable should not be drawn as
768/// though it were.
769#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
770#[non_exhaustive]
771pub enum RowPart {
772    /// The thing itself. What the row is called.
773    Primary,
774    /// Supporting text under the primary.
775    Secondary,
776    /// A short trailing fact: a count, a size, a date.
777    Meta,
778    /// Controls that act on this row.
779    Actions,
780    /// Small labelled things belonging to the row: badges, chips, tags.
781    ///
782    /// Each carries its own [`Token`] kind and [`Tone`], so a renderer with no
783    /// colour still has the kind to work with, and one with no chips still has
784    /// the label. That is the constrained-consumer test this vocabulary exists
785    /// to pass, and it is why the tone lives on the token rather than on the
786    /// part.
787    Tokens,
788    /// How much of a set the row's thing has done: a [`Meter`] in the row.
789    ///
790    /// Added 0.11.0, `da5666ae`, and it is [`Tokens`](Self::Tokens)'s problem
791    /// again with a different payload. [`Meter`] arrived at 0.10.0 and closed
792    /// two of the seven sites that asked for it; the other five sit in rows, and
793    /// a row holds no nodes by the ruling that a row part may not carry an
794    /// arbitrary node — the door through which a description becomes a
795    /// templating language. So the part carries the *description of a bar*
796    /// rather than a node, exactly as `Tokens` carries tags rather than nodes.
797    ///
798    /// Without it a row flattens the proportion into [`Meta`](Self::Meta) as
799    /// "3/7 subtasks", which keeps both numbers and loses the reading, the same
800    /// way a toned status badge read as prose before `Tokens`.
801    Proportion,
802}
803
804impl RowPart {
805    /// The content intent the part takes.
806    #[must_use]
807    pub const fn intent(self) -> &'static str {
808        match self {
809            Self::Primary => "content",
810            Self::Secondary => "content-secondary",
811            Self::Meta => "content-muted",
812            // Actions carry controls rather than text, so they inherit.
813            Self::Actions => "content",
814            // So do tokens: each one carries its own tone, and a part-level
815            // intent underneath it would fight the token that sits on it.
816            Self::Tokens => "content",
817            // And so does a proportion, for the same reason: the meter carries
818            // the tone, and it is about the ratio rather than about the row.
819            Self::Proportion => "content",
820        }
821    }
822}
823
824/// How far down the heading tree a title sits.
825///
826/// Three, and only the three that are actually headings. The bands those used
827/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
828/// and `.detail-header`) are arrangement, not type, and live at
829/// [`Region::Band`]. One of them contains no text at all.
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
831pub enum Heading {
832    /// Names the whole screen. One per screen.
833    Page,
834    /// Names a block within the screen.
835    Section,
836    /// Names a sub-block inside an already-named section.
837    Subsection,
838}
839
840impl Heading {
841    /// Whether a rule follows the heading.
842    ///
843    /// audiofiles' `section_header` draws a separator and its
844    /// `subsection_label` deliberately does not, which is the only thing
845    /// distinguishing the two once weight and colour are deferred.
846    #[must_use]
847    pub const fn separated(self) -> bool {
848        matches!(self, Self::Section)
849    }
850}
851
852/// A control that picks between things.
853///
854/// Three, because three distinct behaviours are in play and collapsing any two
855/// loses something. A segmented control picks a value; a tab picks a pane; a
856/// toggle picks nothing and simply holds itself on or off.
857#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
858pub enum Selector {
859    /// Exactly one of N, and the options abut.
860    Segmented,
861    /// Independent on or off, on its own.
862    Toggle,
863    /// Navigation between panes. The folder semantic.
864    Tabs,
865}
866
867impl Selector {
868    /// How the chosen option sits.
869    ///
870    /// Held in for a segmented control and a toggle, which is the same shape
871    /// pressing produces and the whole economy of the idiom: one appearance,
872    /// two reasons to wear it. A tab is the exception, because the selected
873    /// folder tab comes *forward* to join the pane it opens.
874    #[must_use]
875    pub const fn chosen(self) -> Depth {
876        match self {
877            Self::Segmented | Self::Toggle => Depth::Well,
878            Self::Tabs => Depth::Raised,
879        }
880    }
881
882    /// How the options that were *not* picked sit.
883    ///
884    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
885    /// option falling through to [`Depth::Flat`], which says it is level with
886    /// the strip it sits in, and no renderer emitted anything for it. That is
887    /// wrong in both directions and goingson proved it: its unchosen tabs are
888    /// recessed by hand, and being recessed is *why* the chosen one reads as
889    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
890    /// drawn on the strip's own colour, which is a much weaker folder effect
891    /// than the contrast the idiom is named after.
892    ///
893    /// Each member is the inverse of its chosen state, which is the whole
894    /// content of "picked" once colour is deferred:
895    ///
896    /// - Tabs recede, so the chosen one comes forward.
897    /// - A segment and a toggle stand up, so the chosen one is held in.
898    #[must_use]
899    pub const fn unchosen(self) -> Depth {
900        match self {
901            Self::Tabs => Depth::Sunken,
902            Self::Segmented | Self::Toggle => Depth::Raised,
903        }
904    }
905
906    /// Whether the options touch.
907    ///
908    /// The gap is the entire difference between a segmented control and a row
909    /// of buttons that happen to sit near each other, which is what audiofiles'
910    /// `segmented_control` says in its own comment and why it zeroes the
911    /// spacing by hand.
912    #[must_use]
913    pub const fn abutting(self) -> bool {
914        matches!(self, Self::Segmented | Self::Tabs)
915    }
916}
917
918/// What is in a region right now.
919///
920/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
921/// nothing at all is renderer policy, the same class of decision that got
922/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
923/// each grew a skeleton with differently-named parts; both keep them, as the
924/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
925/// and needs none, because an immediate-mode renderer simply repaints.
926///
927/// # Four states and not two, as of 0.12.0
928///
929/// `703f4cd2`. It named `Ready` and `Pending` and stopped, so a described screen
930/// whose list came back empty had to render an empty region or invent its own
931/// placeholder text, and neither says what it is. goingson draws one at 27 sites
932/// across 12 files and Balanced Breakfast at 9, with a class family that had
933/// already drifted into `empty-state`, `empty-state--error`, `error-state` and
934/// six more.
935///
936/// The four are one axis because they are mutually exclusive: a region shows its
937/// content, or a sign that it is coming, or a sign that there is none, or a sign
938/// that it broke. Never two. That is the test for one enum against several
939/// fields, and it is why this grew rather than a new member arriving beside it.
940///
941/// # What is not here
942///
943/// **The message.** "No projects yet" is content, and this names a state. It
944/// lives with whatever holds the region — in quasi's case a `Slot` — alongside
945/// the action that leads out of the emptiness, since an address is the one thing
946/// this crate never names.
947///
948/// **How much room it gets.** goingson's `--compact`, `--dashboard` and
949/// `--padded` are the same state at three sizes, and a size is
950/// `makeover-geometry`'s question. Naming them here would be this crate stating
951/// values again.
952///
953/// **The icon.** Presentation, and each host has its own answer or none.
954#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
955#[non_exhaustive]
956pub enum Readiness {
957    /// The content is here.
958    Ready,
959    /// The content is on its way.
960    Pending,
961    /// The content arrived and there is none of it.
962    ///
963    /// Not a failure. An empty list is the normal state of a new install, and a
964    /// renderer that drew it in a danger tone would be reporting a fault where
965    /// there is none.
966    Empty,
967    /// The content did not arrive.
968    Failed,
969}
970
971impl Readiness {
972    /// Whether the region draws its own content, or something standing in for
973    /// it.
974    ///
975    /// The question every renderer asks first, so it is answered once here
976    /// rather than by a `matches!` in each. A state added later is a stand-in
977    /// until proven otherwise: falling back to drawing content that may not be
978    /// there is the worse of the two mistakes.
979    #[must_use]
980    pub const fn shows_content(self) -> bool {
981        matches!(self, Self::Ready)
982    }
983
984    /// What the state means, for a renderer choosing a colour.
985    ///
986    /// Derived rather than carried, which is the opposite of [`Meter`] and
987    /// [`Figure`], and the difference is worth stating: a proportion's meaning
988    /// depends on what is being counted and only the app knows it, while
989    /// "nothing here yet" and "this broke" mean the same thing in every app that
990    /// will ever have them.
991    #[must_use]
992    pub const fn tone(self) -> Tone {
993        match self {
994            Self::Failed => Tone::Danger,
995            _ => Tone::Neutral,
996        }
997    }
998}
999
1000/// How much of a set is done.
1001///
1002/// Added 0.10.0. Nine sites across the two webview apps drew a bar and nothing
1003/// here named one, so every described screen concatenated the two numbers into
1004/// its heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m
1005/// est, over". Every fact survives that and the reading does not, which is the
1006/// same loss `RowPart::Tokens` closed when a toned status badge became prose.
1007///
1008/// # Why a pair and not a percentage
1009///
1010/// Both numbers, not the percentage the apps compute from them. The percentage
1011/// was the obvious shape and it had already been tried: goingson's
1012/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
1013/// away the one case the bar exists to show — 45 minutes tracked against a
1014/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
1015/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
1016/// companion flag, and [`percent`](Meter::percent) is still one call away for a
1017/// renderer that wants it.
1018///
1019/// The pair is also what the apps already have at every site. All seven
1020/// determinate bars write the ratio into the accessible layer and never the
1021/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
1022/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
1023/// percentage member would have made [`label`](Meter::label) mandatory at every
1024/// call site, which is the concatenated text this member removes, moved one
1025/// layer down.
1026///
1027/// # What this is not
1028///
1029/// The progress of an *operation*. Two of the nine sites are that — goingson's
1030/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
1031/// purpose. Both are imperative controllers over a live handle, driven by a tick
1032/// or an event stream, and a description is built once and dropped. Holding one
1033/// would mean growing a way to update a description between renders, which is a
1034/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
1035/// honest part.
1036///
1037/// The two cases are distinguishable in the markup rather than by taste: every
1038/// determinate bar in both apps carries a tone, and neither operation bar
1039/// carries one. Two codebases drew that line the same way without coordinating.
1040#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1041pub struct Meter<'a> {
1042    /// How much is done. May exceed [`total`](Self::total), and that is the
1043    /// case worth drawing.
1044    pub done: u32,
1045    /// How much there is to do. Zero means there is no set, not that the set is
1046    /// complete.
1047    pub total: u32,
1048    /// What the proportion means right now.
1049    ///
1050    /// Carried rather than derived, because no renderer can work it out. The
1051    /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
1052    /// a time estimate, and goingson picks between them from `is_over_estimate`,
1053    /// a fact about the data and not about the number.
1054    pub tone: Tone,
1055    /// What is being counted, if the bar says so: "subtasks", "tasks".
1056    ///
1057    /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
1058    /// and the two numbers; handing it the assembled string would put the
1059    /// sentence order in the description, where a terminal at one line and a
1060    /// tooltip want different ones.
1061    pub label: Option<&'a str>,
1062}
1063
1064impl<'a> Meter<'a> {
1065    /// A proportion with no tone and no label.
1066    #[must_use]
1067    pub const fn new(done: u32, total: u32) -> Self {
1068        Self {
1069            done,
1070            total,
1071            tone: Tone::Neutral,
1072            label: None,
1073        }
1074    }
1075
1076    /// What the proportion means.
1077    #[must_use]
1078    pub const fn tone(mut self, tone: Tone) -> Self {
1079        self.tone = tone;
1080        self
1081    }
1082
1083    /// What is being counted.
1084    #[must_use]
1085    pub const fn label(mut self, label: &'a str) -> Self {
1086        self.label = Some(label);
1087        self
1088    }
1089
1090    /// How full the bar is, 0 to 100, clamped.
1091    ///
1092    /// For drawing, which is the only thing a clamped number is good for. Ask
1093    /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
1094    /// is `time_progress`'s bug again with the clamp moved.
1095    ///
1096    /// An empty set reads as 0. Nothing is done, because there is nothing to do
1097    /// and no bar to fill; the apps guard on the count before drawing at all.
1098    #[must_use]
1099    pub const fn percent(&self) -> u8 {
1100        if self.total == 0 {
1101            return 0;
1102        }
1103        let scaled = (self.done as u64 * 100) / self.total as u64;
1104        if scaled > 100 { 100 } else { scaled as u8 }
1105    }
1106
1107    /// Whether more is done than there was to do.
1108    ///
1109    /// The fact [`percent`](Self::percent) destroys, kept reachable so a
1110    /// renderer can mark the over-run rather than drawing a full bar and
1111    /// implying it landed exactly.
1112    #[must_use]
1113    pub const fn overflowing(&self) -> bool {
1114        self.done > self.total
1115    }
1116
1117    /// Whether there is a set at all.
1118    ///
1119    /// A meter over nothing is sayable on purpose, for the same reason a field
1120    /// with no options is: it is what an app with an unloaded count actually
1121    /// has, and a renderer that shows an empty bar says so on screen rather than
1122    /// dividing by zero.
1123    #[must_use]
1124    pub const fn is_empty(&self) -> bool {
1125        self.total == 0
1126    }
1127}
1128
1129/// One figure with a caption: a number and what it counts.
1130///
1131/// The dashboard shape. A large value over a small caption, several of them in a
1132/// strip: a current streak, a completion rate, a total. Added 0.11.0,
1133/// `93c6a174`, after goingson turned out to have five of them across five
1134/// screens with five class vocabularies for the one shape — `task-overview-stat`,
1135/// `stat-box`, `month-stat-item`, `contact-summary-stat`, `sync-stat`. Four put
1136/// the value above the caption and one inverts it, which is drift inside the
1137/// shape rather than a second shape.
1138///
1139/// # Why the value is text
1140///
1141/// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
1142/// formatted, and the formatting is the app's because only it knows whether the
1143/// number is a percentage, a duration or a ratio. This carries none of the
1144/// arithmetic [`Meter`] carries, and that is the difference between them: a
1145/// meter is a proportion a renderer draws, and a figure is a fact a renderer
1146/// sets in type.
1147///
1148/// # Tone is carried, for [`Meter`]'s reason
1149///
1150/// Three of the five sites tone the figure by their own means — `red`/`blue` on
1151/// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
1152/// sync. So tone is carried at every site that needs it and derived at none, and
1153/// no renderer can work out that a streak of zero is worth colouring.
1154///
1155/// # What is not here
1156///
1157/// Whether the figure answers a click. One of the five is a control — sync's
1158/// "Not Applied: 3" opens the list — and an action is not something this crate
1159/// can name: nothing here knows what a route is. That belongs beside the figure
1160/// in whatever layer holds the actions, the same way a row's activation sits
1161/// beside its parts rather than inside them.
1162///
1163/// The arrangement is not here either. Several figures in a strip is a set, and
1164/// a renderer given them one at a time cannot tell it is looking at one; the
1165/// layer that holds the tree is where the set gets said.
1166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1167pub struct Figure<'a> {
1168    /// The number, formatted the way the app means it to read.
1169    pub value: &'a str,
1170    /// What it counts. The caption under the value.
1171    pub caption: &'a str,
1172    /// How the value has moved, if the app is tracking that.
1173    ///
1174    /// Added 0.13.0. Text, for [`value`](Self::value)'s reason: only the app
1175    /// knows whether a move reads as `+12.5%`, `+3` or `2x`, and a renderer
1176    /// handed a number would have to guess.
1177    ///
1178    /// This is what [`tone`](Self::tone) was for and had no consumer of. The MNW
1179    /// server has four screens whose stat card is a label, a value and a delta,
1180    /// and the delta is the toned part: the figure itself is an ordinary fact
1181    /// and it is the movement that reads as good or bad. Without this the delta
1182    /// has to be folded into the caption, which loses the tone and reads as a
1183    /// longer caption rather than as a second, smaller line.
1184    pub change: Option<&'a str>,
1185    /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
1186    ///
1187    /// Applies to [`change`](Self::change) where there is one, since that is the
1188    /// part that carries the judgement, and to the value where there is not.
1189    pub tone: Tone,
1190}
1191
1192impl<'a> Figure<'a> {
1193    /// A figure that is an ordinary fact.
1194    #[must_use]
1195    pub const fn new(value: &'a str, caption: &'a str) -> Self {
1196        Self {
1197            value,
1198            caption,
1199            change: None,
1200            tone: Tone::Neutral,
1201        }
1202    }
1203
1204    /// How the value has moved.
1205    #[must_use]
1206    pub const fn change(mut self, change: &'a str) -> Self {
1207        self.change = Some(change);
1208        self
1209    }
1210
1211    /// What the figure means.
1212    #[must_use]
1213    pub const fn tone(mut self, tone: Tone) -> Self {
1214        self.tone = tone;
1215        self
1216    }
1217}
1218
1219/// Something the user can do, and what it costs to say so.
1220///
1221/// Added 0.17.0, out of `quasi-tui`: the terminal renderer had drawn one of
1222/// these for months and every other consumer that wanted a button had written
1223/// its own, because this layer named [`RowPart::Actions`] as a *slot* and never
1224/// named the thing that goes in it. Beside [`Meter`] and [`Figure`] for the
1225/// reason those are here: a renderer that is handed the parts has to decide how
1226/// to say them, and a renderer that is handed a finished string has already had
1227/// the decision made for it.
1228///
1229/// No address. Where a control goes is the app's business and every host
1230/// follows it differently — an `hx-get`, a protocol URL, a function call — so
1231/// the description says what the control *is* and the caller keeps what it
1232/// does. That is the same split [`Choice`] makes.
1233///
1234/// No confirmation flag either, and that one is a finding rather than an
1235/// omission: a question asked *after* a control is pressed belongs to whatever
1236/// is holding the interaction, and a renderer that drew it would be asking
1237/// before there was anything to answer.
1238/// How a picture sits in the box it is given.
1239///
1240/// An intent rather than a value, so a renderer picks the expression it has:
1241/// `object-fit` in a webview, a texture's UV rect in egui, and in a terminal a
1242/// choice about how many cells the blit gets. Named because MNW already makes
1243/// the distinction deliberately at 17 sites and makes it three different ways,
1244/// which is a policy the app decided rather than one a shared crate would be
1245/// picking by accident.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1247#[non_exhaustive]
1248pub enum Fit {
1249    /// The picture's own proportions, and the box takes the height they imply.
1250    ///
1251    /// The default because it is the only one that shows the whole picture at
1252    /// its own shape, so a renderer that ignores this enum entirely is still
1253    /// right about the common case. A screenshot wants this; the shipped MNW
1254    /// carousel sets no `object-fit` at all, which is this.
1255    #[default]
1256    Natural,
1257    /// Fill the box and crop whatever does not fit.
1258    ///
1259    /// For a picture in a slot whose shape the layout fixed: a thumbnail, an
1260    /// avatar, cover art. 15 of MNW's 17 sites.
1261    Cover,
1262    /// Fit inside the box whole, leaving space on two sides.
1263    ///
1264    /// The letterbox. For when the whole picture matters more than filling the
1265    /// space, and the space is not the picture's shape.
1266    Contain,
1267}
1268
1269/// A picture, and what it says to someone who is not looking at it.
1270///
1271/// # No source
1272///
1273/// [`Act`]'s split, for [`Act`]'s reason. A source is an address, and this
1274/// crate has no notion of an address: it says what a thing *is* and the caller
1275/// keeps what it points at. The three findings dropped from 0.11.0 were all
1276/// this same shape.
1277///
1278/// It matters more here than it does for a control, because a picture is the
1279/// one member where the address is most of what a webview needs and *none* of
1280/// what the description knows. `quasi_router::Node::Image` carries the URL, the
1281/// way it carries an `Action` for a control.
1282///
1283/// # Why [`alt`](Self::alt) is not optional
1284///
1285/// Every other host has to draw something, and for two of the three the alt
1286/// text is not a fallback but the whole rendering: a terminal without a
1287/// graphics protocol has the words and nothing else. Making it optional would
1288/// make "this picture is invisible on a terminal" the default, and the
1289/// description would be carrying a webview assumption in its shape.
1290///
1291/// An image that genuinely says nothing — a rule, a spacer, a decoration
1292/// repeating what the text beside it already said — is an empty `alt`, which is
1293/// the same thing HTML means by it and is a claim rather than an oversight.
1294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1295pub struct Image<'a> {
1296    /// What the picture says, for anything not showing it.
1297    ///
1298    /// Empty means the picture is decorative and adds nothing to the text
1299    /// around it. See the type's own docs on why this is not an `Option`.
1300    pub alt: &'a str,
1301    /// A visible line under the picture, where the app wants one.
1302    ///
1303    /// Distinct from [`alt`](Self::alt) and the difference is who it is for: a
1304    /// caption is content everybody reads, alt text is what stands in for the
1305    /// picture. A screenshot captioned "The library view" still needs alt text
1306    /// describing what is in the shot.
1307    pub caption: Option<&'a str>,
1308    /// How it sits in the box it is given.
1309    pub fit: Fit,
1310}
1311
1312impl<'a> Image<'a> {
1313    /// A picture that carries its own proportions.
1314    #[must_use]
1315    pub const fn new(alt: &'a str) -> Self {
1316        Self {
1317            alt,
1318            caption: None,
1319            fit: Fit::Natural,
1320        }
1321    }
1322
1323    /// A visible line under it.
1324    #[must_use]
1325    pub const fn caption(mut self, caption: &'a str) -> Self {
1326        self.caption = Some(caption);
1327        self
1328    }
1329
1330    /// How it sits in its box.
1331    #[must_use]
1332    pub const fn fit(mut self, fit: Fit) -> Self {
1333        self.fit = fit;
1334        self
1335    }
1336
1337    /// Whether the picture adds anything for someone not looking at it.
1338    ///
1339    /// A renderer with no way to show a picture uses this to decide between
1340    /// drawing the alt text and drawing nothing at all. Both are correct and
1341    /// the difference is this flag: standing in for a decorative rule with the
1342    /// word "decoration" is worse than leaving the space empty.
1343    #[must_use]
1344    pub const fn speaks(self) -> bool {
1345        !self.alt.is_empty()
1346    }
1347}
1348
1349#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1350pub struct Act<'a> {
1351    /// What the control says.
1352    pub label: &'a str,
1353    /// The key that reaches it where a host has keys.
1354    ///
1355    /// The one member written for a terminal before there was one. A webview
1356    /// hangs it off `accesskey` or ignores it; a terminal has nothing else to
1357    /// offer, so this is the whole of how a control is reached there.
1358    pub key: Option<&'a str>,
1359    /// What pressing it means. [`Tone::Danger`] is the destructive one.
1360    pub tone: Tone,
1361    /// Disabled, or nothing said.
1362    ///
1363    /// [`State::Disabled`] is what changes what a renderer may do: see
1364    /// [`State::suppresses_interaction`], which is what says a disabled control
1365    /// is drawn and not reachable. It has been the only member since 0.19.0,
1366    /// and a control's focus is not sayable here at all — see the crate header,
1367    /// "Reach, focus and the focus ring".
1368    pub state: Option<State>,
1369}
1370
1371impl<'a> Act<'a> {
1372    /// An ordinary control, reachable, with no key.
1373    #[must_use]
1374    pub const fn new(label: &'a str) -> Self {
1375        Self {
1376            label,
1377            key: None,
1378            tone: Tone::Neutral,
1379            state: None,
1380        }
1381    }
1382
1383    /// The key that reaches it.
1384    #[must_use]
1385    pub const fn key(mut self, key: &'a str) -> Self {
1386        self.key = Some(key);
1387        self
1388    }
1389
1390    /// What pressing it means.
1391    #[must_use]
1392    pub const fn tone(mut self, tone: Tone) -> Self {
1393        self.tone = tone;
1394        self
1395    }
1396
1397    /// Focus, or disabled.
1398    #[must_use]
1399    pub const fn state(mut self, state: State) -> Self {
1400        self.state = Some(state);
1401        self
1402    }
1403
1404    /// Whether the control is drawn and does not answer.
1405    #[must_use]
1406    pub fn disabled(&self) -> bool {
1407        self.state.is_some_and(State::suppresses_interaction)
1408    }
1409}
1410
1411/// A named part of a screen.
1412///
1413/// The thing `makeover-geometry` deliberately does not name: it names the space
1414/// *between* things by relationship, and nothing named the things. Six named
1415/// members, taken from what the two webview apps actually use, plus
1416/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
1417/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
1418/// this layer is absent rather than divergent, which makes it the cheapest of
1419/// the schemas to add and the easiest to over-build.
1420///
1421/// `#[non_exhaustive]` arrives with [`Region::Widget`], the pairing [`RowPart`]
1422/// made at 0.9.0 and [`Readiness`] at 0.12.0, and for the same reason: the
1423/// member after this one should not be a lockstep event across three renderers.
1424#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1425#[non_exhaustive]
1426pub enum Region<'a> {
1427    /// A full-width strip with a title slot and an actions cluster, either of
1428    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
1429    /// `.header` and `.detail-header` are all this, differing only in which
1430    /// slots they fill.
1431    Band,
1432    /// A persistent column beside the content, holding navigation.
1433    Sidebar,
1434    /// A region of content with its own scroll.
1435    Pane,
1436    /// Two panes side by side, where the left chooses what the right shows.
1437    Split,
1438    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
1439    TabGroup,
1440    /// Content over a scrim, taking input until dismissed.
1441    Modal,
1442    /// A region this crate names the *place* of and nothing else. The app owns
1443    /// what goes in it.
1444    ///
1445    /// The escape hatch, and the thing that keeps the description honest about
1446    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
1447    /// paint interaction over the timeline are not describable here and are not
1448    /// going to become describable: a description expressive enough to produce
1449    /// a timeline is a widget library wearing a description's name.
1450    ///
1451    /// But a screen containing one still has to be a screen. Without this
1452    /// member the description covers only the boring screens, and the four that
1453    /// make goingson worth using would need a second, undescribed path beside
1454    /// the router. Two paths is how the vocabulary starts drifting from the app
1455    /// again, which is the exact failure this crate exists to end.
1456    ///
1457    /// So the description says "a thing called `day-plan` goes here" and stops.
1458    /// The name is opaque: this crate never interprets it, and no renderer is
1459    /// expected to know what it means beyond handing the space over.
1460    Bespoke {
1461        /// What the app calls it. Never interpreted here.
1462        name: &'a str,
1463    },
1464    /// A named assembly of things the vocabulary already says.
1465    ///
1466    /// The third tier, between a primitive and [`Bespoke`](Self::Bespoke).
1467    /// Stated by Max 2026-08-12 answering the carousel: "something in between a
1468    /// primitive and a bespoke interface, like a widget, which is just an
1469    /// assembly of primitives." Full note: wiki `widget-tier`.
1470    ///
1471    /// # What separates it from the two members either side
1472    ///
1473    /// A primitive is a thing every renderer draws from scratch, and the test
1474    /// it has to pass is that every host has an honest answer. A carousel fails
1475    /// that test — a terminal has no carousel — which is the same refusal
1476    /// `Node::Html` got and is why the carousel sat unsayable for months.
1477    ///
1478    /// [`Bespoke`](Self::Bespoke) fails it from the other side. Bespoke is for
1479    /// what one app owns and nobody will build twice, and it carries *no*
1480    /// contents: the description names the place and stops. A carousel is
1481    /// furniture any app would have, and every part of it — an ordered set of
1482    /// frames, a position, prev and next, a strip of position indicators — is
1483    /// already sayable. Only the assembly had no name.
1484    ///
1485    /// So this member is the pair the other two are not: a name **and**
1486    /// contents. The contents are the assembly, in the region's own body, said
1487    /// in members that already exist.
1488    ///
1489    /// # Why the name does not have to be understood
1490    ///
1491    /// A renderer that recognises the name draws it the way its host does it: a
1492    /// carousel in a webview, a pager with a count in a terminal, a selector in
1493    /// egui. A renderer that does not recognise it walks the body, which is
1494    /// primitives all the way down and which it can already draw.
1495    ///
1496    /// That is what lets the widget set be **open** without every renderer
1497    /// knowing every widget. An unrecognised widget degrades to its assembly
1498    /// instead of failing, so a second or third party can name one without
1499    /// three renderers releasing in lockstep to accept it. Contrast
1500    /// [`Bespoke`](Self::Bespoke), which no renderer can degrade: there is
1501    /// nothing under it to fall back to.
1502    ///
1503    /// # What it does not do
1504    ///
1505    /// It does not make a timeline describable, and the refusal in the crate
1506    /// header stands unchanged. A widget is an assembly of things the
1507    /// vocabulary *already* says; anything that needs a member the vocabulary
1508    /// does not have is a finding about the vocabulary or it is
1509    /// [`Bespoke`](Self::Bespoke). A widget is never the way a primitive gets
1510    /// added by the back door.
1511    Widget {
1512        /// What the assembly is called. This crate never interprets it, and a
1513        /// renderer is free not to know it.
1514        name: &'a str,
1515    },
1516}
1517
1518impl<'a> Region<'a> {
1519    /// How the region sits on what is behind it.
1520    #[must_use]
1521    pub const fn depth(self) -> Depth {
1522        match self {
1523            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
1524            // A pane is looked into, the same as a table body or a tag tree.
1525            Self::Pane => Depth::Well,
1526            Self::Modal => Depth::Raised,
1527            // Flat because it inherits: a bespoke region takes the depth of
1528            // whatever frames it. An app that wants its timeline in a well puts
1529            // it in a `Pane`, which composes rather than adding a knob here.
1530            //
1531            // A widget inherits for the same reason and it matters more here,
1532            // because a widget is drawn by whichever renderer recognises it. A
1533            // depth set here would be this crate deciding that a carousel is
1534            // raised on every host, which is the kind of value the deferral
1535            // rule exists to refuse.
1536            Self::Bespoke { .. } | Self::Widget { .. } => Depth::Flat,
1537        }
1538    }
1539
1540    /// Whether this crate can say anything about the region's contents.
1541    ///
1542    /// A renderer walks the description and hands every region it understands
1543    /// to the right drawing code. This is how it tells the two apart, and the
1544    /// reason it is a method rather than a `matches!` at each renderer: there
1545    /// is exactly one opaque member and there should stay exactly one.
1546    ///
1547    /// [`Widget`](Self::Widget) is described, and that is the whole of what
1548    /// separates it from [`Bespoke`](Self::Bespoke) here. Both carry a name
1549    /// this crate never interprets; only one of them carries contents under it.
1550    /// A renderer that does not recognise a widget's name still walks its body,
1551    /// so there is nothing for it to hand over and nothing it cannot draw.
1552    #[must_use]
1553    pub const fn described(self) -> bool {
1554        !matches!(self, Self::Bespoke { .. })
1555    }
1556
1557    /// The name an app gave this region, if it gave one.
1558    ///
1559    /// [`Bespoke`](Self::Bespoke) and [`Widget`](Self::Widget) are the two
1560    /// members that carry a name, for two different purposes: one says what the
1561    /// app will fill the space with, the other says what the assembly under it
1562    /// is called. A renderer dispatching on either wants the string without
1563    /// caring which member it came from, and writing that `matches!` at each
1564    /// renderer is how the two drift apart.
1565    #[must_use]
1566    pub const fn name(self) -> Option<&'a str> {
1567        match self {
1568            Self::Bespoke { name } | Self::Widget { name } => Some(name),
1569            // Spelled out rather than a wildcard, so a member added later has
1570            // to answer whether it carries a name instead of inheriting `None`
1571            // by sitting under a `_`.
1572            Self::Band
1573            | Self::Sidebar
1574            | Self::Pane
1575            | Self::Split
1576            | Self::TabGroup
1577            | Self::Modal => None,
1578        }
1579    }
1580}
1581
1582/// How much of the width an arrangement's first region takes.
1583///
1584/// `e0fd485e`. Nothing said how much room a region got, so every renderer
1585/// invented its own number and two hosts showing one screen disagreed about
1586/// its proportions. A webview never noticed, because the stylesheet answered
1587/// once for every consumer; a terminal has no stylesheet to inherit from, so
1588/// `quasi-tui` picked 24 columns for a sidebar and 40% for a list pane and
1589/// neither had anything behind it.
1590///
1591/// # A proportion, never a unit
1592///
1593/// Held as a percentage, and that is the only form it comes in. A description
1594/// carrying columns would be describing a terminal and one carrying pixels a
1595/// webview, and the whole point is that both honour the same fact: a terminal
1596/// resolves it against a column count, a webview writes it into a grid, and
1597/// neither has to know what the other did.
1598///
1599/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
1600/// guess. Geometry is scales that answer the same for every screen and takes
1601/// no input that would let a sidebar screen differ from a list-detail one.
1602///
1603/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
1604#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1605pub struct Share(u8);
1606
1607impl Share {
1608    /// What a sidebar takes, when nobody says otherwise.
1609    ///
1610    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
1611    /// 96-column terminal and about a fifth of a wide one; a quarter is that
1612    /// number said in the form a webview can honour too.
1613    pub const SIDEBAR: Self = Self(25);
1614
1615    /// What the list side of a list-detail takes, when nobody says otherwise.
1616    ///
1617    /// `quasi-tui`'s 40%, which was already a proportion and is the one number
1618    /// this member did not have to invent.
1619    pub const LIST: Self = Self(40);
1620
1621    /// A share of the width, as a percentage.
1622    ///
1623    /// Clamped to 5..=95 rather than refused. A description that asked for a
1624    /// region of nothing is a bug in the app, and a renderer drawing a region
1625    /// zero cells wide reports it as a region that vanished, which is the
1626    /// hardest kind of bug to find from what is on the screen.
1627    #[must_use]
1628    pub const fn percent(percent: u8) -> Self {
1629        Self(if percent < 5 {
1630            5
1631        } else if percent > 95 {
1632            95
1633        } else {
1634            percent
1635        })
1636    }
1637
1638    /// The share as a percentage.
1639    #[must_use]
1640    pub const fn as_percent(self) -> u8 {
1641        self.0
1642    }
1643
1644    /// This share of a width, rounded to the nearest whole unit.
1645    ///
1646    /// What a terminal calls to turn the proportion into columns. At least one,
1647    /// because a region the description named should be visible: a screen
1648    /// 3 columns wide is unusable either way, and a sidebar that is there is a
1649    /// truer picture of the description than a sidebar that is not.
1650    #[must_use]
1651    pub const fn of(self, whole: u16) -> u16 {
1652        let taken = (whole as u32 * self.0 as u32).div_ceil(100);
1653        if taken == 0 { 1 } else { taken as u16 }
1654    }
1655}
1656
1657/// How a screen is laid out.
1658///
1659/// Two, and the second is not a variant of the first. goingson is list-detail,
1660/// Balanced Breakfast is sidebar plus content, and neither app has a third.
1661/// The tab group is a modifier rather than a member, because goingson uses it
1662/// *inside* the same content region rather than instead of one.
1663///
1664/// This exists at all because the router has to be able to express a screen
1665/// rather than only a control. Discovering the arrangement layer missing after
1666/// the renderers exist is a redesign; naming two now is a morning.
1667///
1668/// # Why the share rides here
1669///
1670/// `e0fd485e`. A share is per-arrangement: how much a sidebar takes and how
1671/// much a list side takes are different questions, and this enum is the only
1672/// thing that knows which one is being asked. Geometry would have had to invent
1673/// a channel to be told.
1674///
1675/// [`list_detail`](Self::list_detail) and
1676/// [`sidebar_content`](Self::sidebar_content) build these with the default
1677/// shares, so a screen that has no opinion does not have to have one.
1678#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1679pub enum Arrangement {
1680    /// A list that chooses what the detail beside it shows.
1681    ListDetail {
1682        /// Whether the detail side is a [`Region::TabGroup`].
1683        tabbed: bool,
1684        /// How much of the width the list side takes.
1685        share: Share,
1686    },
1687    /// Navigation down the side, content filling the rest.
1688    SidebarContent {
1689        /// How much of the width the sidebar takes.
1690        share: Share,
1691    },
1692}
1693
1694impl Arrangement {
1695    /// A list and a detail beside it, at the default share.
1696    #[must_use]
1697    pub const fn list_detail(tabbed: bool) -> Self {
1698        Self::ListDetail {
1699            tabbed,
1700            share: Share::LIST,
1701        }
1702    }
1703
1704    /// A sidebar and content beside it, at the default share.
1705    #[must_use]
1706    pub const fn sidebar_content() -> Self {
1707        Self::SidebarContent {
1708            share: Share::SIDEBAR,
1709        }
1710    }
1711
1712    /// How much of the width the first region takes.
1713    #[must_use]
1714    pub const fn share(self) -> Share {
1715        match self {
1716            Self::ListDetail { share, .. } | Self::SidebarContent { share } => share,
1717        }
1718    }
1719
1720    /// The same arrangement, at this share.
1721    #[must_use]
1722    pub const fn with_share(self, share: Share) -> Self {
1723        match self {
1724            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
1725            Self::SidebarContent { .. } => Self::SidebarContent { share },
1726        }
1727    }
1728}
1729
1730/// How wide the content of a whole screen runs.
1731///
1732/// `0eccff0d`, and [`Share`]'s sibling one level up: that one says how a
1733/// screen's width is divided between regions, this says how much of the window
1734/// the screen uses in the first place. Both are the description's, which is
1735/// what answering the two together settled.
1736///
1737/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
1738/// three mutually exclusive classes and the choice is per screen. GoingsOn
1739/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
1740/// token for it, so three apps were solving one thing by hand.
1741///
1742/// # Named for the measure, not for MNW's classes
1743///
1744/// A renderer that is not a browser has to answer this too, and `padded-page`
1745/// tells a terminal nothing. The three say how wide the text runs, which is a
1746/// question every renderer can answer: a webview with a `max-width`, a terminal
1747/// with gutters, an immediate-mode frame with its own width.
1748///
1749/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
1750/// the measurement found three, and a fourth arriving should not be a lockstep
1751/// release across nine repos.
1752#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1753#[non_exhaustive]
1754pub enum Measure {
1755    /// The whole width, with gutters. The default, and 53 of the 69.
1756    ///
1757    /// What a dashboard, a table and a settings screen want: the content is
1758    /// wide because the content *is* wide, and constraining it would waste the
1759    /// window.
1760    #[default]
1761    Wide,
1762    /// Capped at a comfortable page width, centred. 13 of the 69.
1763    ///
1764    /// A form, a sign-in, a purchase. Content that does not get better by
1765    /// getting wider, but is not prose either.
1766    Contained,
1767    /// Capped at a line length that reads well. 3 of the 69.
1768    ///
1769    /// Prose. The narrowest of the three, and the one with a reason outside
1770    /// taste: a line of text past roughly 75 characters costs the reader the
1771    /// return sweep.
1772    Reading,
1773}
1774
1775impl Measure {
1776    /// A stable name, for a renderer that needs to spell it.
1777    ///
1778    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
1779    /// renderers spelling one enum is three chances to spell it differently.
1780    #[must_use]
1781    pub const fn as_str(self) -> &'static str {
1782        match self {
1783            Self::Wide => "wide",
1784            Self::Contained => "contained",
1785            Self::Reading => "reading",
1786        }
1787    }
1788}
1789
1790/// What kind of value a form field takes.
1791///
1792/// The union of the two vocabularies that diverged, which is what triggered
1793/// this crate. They have since converged on their own: both apps now have a
1794/// `renderFormField` emitting the same anatomy, and what is left differing is
1795/// the kind set, the error shape, and whether the return is a string or a node.
1796///
1797/// Validation is deliberately absent. Neither app has a shared story (goingson
1798/// validates after collecting the form data, with per-field transform hooks;
1799/// Balanced Breakfast has `required` and nothing else), and a schema that
1800/// describes fields but not constraints acquires a constraint layer per app,
1801/// which is exactly how the current divergence started. Naming it absent is a
1802/// decision; leaving it unmentioned would not be.
1803/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
1804/// the set keeps growing, so growth must not be a lockstep event. Email, Url
1805/// and Tel arriving in 0.5.0 is the second growth in two releases.
1806#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1807#[non_exhaustive]
1808pub enum FieldKind {
1809    /// A single line of text.
1810    Text,
1811    /// A single line of text that must never be echoed, logged or round-tripped
1812    /// through anything that might persist it.
1813    Secret,
1814    /// A number.
1815    Number,
1816    /// An email address.
1817    ///
1818    /// Distinct from [`Text`](Self::Text) because the distinction is not
1819    /// decoration: a webview renderer emits `type="email"`, which on a touch
1820    /// device changes the keyboard that appears and turns on the platform's own
1821    /// validation. goingson ships to iOS, so collapsing this into text costs a
1822    /// keyboard with no `@` on it.
1823    ///
1824    /// Added 0.5.0, from goingson's contact form.
1825    Email,
1826    /// A URL. Same reasoning as [`Email`](Self::Email).
1827    ///
1828    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
1829    Url,
1830    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
1831    /// clearest case of it: the keyboard is a numeric pad rather than letters.
1832    ///
1833    /// Added 0.5.0, from goingson's contact-phone form.
1834    Tel,
1835    /// A calendar day, with no time of day in it.
1836    ///
1837    /// [`Email`](Self::Email)'s argument, and it carries further: a webview
1838    /// emits `type="date"`, which is a native picker, the platform's own
1839    /// validation, and on a touch device the date keyboard. Described as
1840    /// [`Text`](Self::Text) with a hint reading "YYYY-MM-DD", all three are
1841    /// lost and the hint is doing the platform's job in prose.
1842    ///
1843    /// The membership test passes on every host without stretching: a webview
1844    /// and a Tauri app emit the input, egui has a date picker, a terminal
1845    /// prompts for a day and can validate it, a CLI takes an argument.
1846    ///
1847    /// # The value is ISO 8601, `YYYY-MM-DD`
1848    ///
1849    /// Named here rather than left to each host, because a host that picks
1850    /// differently sends a server something it parses differently, and the
1851    /// failure is silent and per-host. It is `<input type="date">`'s own wire
1852    /// format, so the webview renderer owes nothing to honour it and the other
1853    /// hosts have one spelling to meet. [`DATE_FORMAT`] is the constant, and a
1854    /// test asserts this doc and that constant agree.
1855    ///
1856    /// Added 0.15.0, from the MNW server's git access-token expiry
1857    /// (`user_ssh_keys_tab.html`) and six further sites across the server and
1858    /// goingson.
1859    Date,
1860    /// A calendar day and a time of day together.
1861    ///
1862    /// Apart from [`Date`](Self::Date) because the question is different rather
1863    /// than more precise: "which day does this expire" and "at what moment does
1864    /// this publish" are asked by different screens and answered by different
1865    /// controls. A webview emits `type="datetime-local"` for one and
1866    /// `type="date"` for the other, and a host that collapsed them would ask
1867    /// half the tree for a precision it does not want.
1868    ///
1869    /// Both arrived together on measurement rather than on symmetry: 13 sites
1870    /// of each across the MNW server and goingson, and **zero** of `time`,
1871    /// `month` or `week`, which is why those are not here. A member added for a
1872    /// case nobody has is a member designed against nothing, which is
1873    /// [`File`](Self::File)'s reasoning about `accept` applied to a whole
1874    /// member.
1875    ///
1876    /// # The value is `YYYY-MM-DDTHH:MM`, local, with no zone
1877    ///
1878    /// `<input type="datetime-local">`'s own format, and the "local" is the
1879    /// load-bearing half: the value carries no offset and no `Z`, so the moment
1880    /// it names is only fixed once something supplies a zone. That is the app's
1881    /// business and not the description's. Seconds are absent, which is the
1882    /// browser's own default and is left as the rule rather than restated as a
1883    /// constraint. [`DATETIME_FORMAT`] is the constant.
1884    ///
1885    /// [`Field::min`] and [`Field::max`] already take "the host's own spelling
1886    /// of a bound", so a floor of *not in the past* needs nothing new here: it
1887    /// is a string in this same format.
1888    ///
1889    /// Added 0.15.0, from goingson's snooze picker and day planner and the MNW
1890    /// server's publish-at fields.
1891    DateTime,
1892    /// Several lines of text.
1893    Textarea,
1894    /// One of a fixed set, offered behind a control that shows one at a time.
1895    Select,
1896    /// One of a fixed set, with every option on screen at once.
1897    ///
1898    /// Not a presentation of [`Select`](Self::Select), which is the reading to
1899    /// resist: what differs is a property of the *question*. A choice that is
1900    /// consequential or irreversible has to be readable without opening
1901    /// anything, because a closed control shows one option and hides the rest,
1902    /// and the one it shows is whichever was current before the user had read
1903    /// the alternatives. audiofiles asks whether a library copies samples into
1904    /// its store or references them where they lie — which cannot be changed
1905    /// afterwards — and had already promoted that out of a checkbox by hand,
1906    /// with a comment giving this reason, before the description could say it.
1907    ///
1908    /// It was described here at 0.8.1 as "the one HTML input type this enum was
1909    /// missing", which was not true then and is not true now: `file` arrived at
1910    /// 0.11.0 and `date` and `datetime-local` at 0.15.0. Everything here is
1911    /// still an `<input type=...>`, a `<select>` or a `<textarea>`, and the way
1912    /// this enum grows is by a site being measured rather than by a list being
1913    /// completed, so "the last one" is not a claim it should make again.
1914    ///
1915    /// Added 0.8.1, from audiofiles' Add Library form.
1916    Radio,
1917    /// On or off.
1918    Checkbox,
1919    /// A file the user picks from wherever the host keeps files.
1920    ///
1921    /// Added 0.11.0, `844b5ae0`, from goingson's project-dashboard attachments
1922    /// column. It was filed as a router finding — a control whose destination is
1923    /// a host capability rather than an address — and splitting it is what made
1924    /// it two answers instead of one member satisfying neither. *Opening* a file
1925    /// is a one-way handoff and needs no new API. *Picking* one returns a value
1926    /// into a write, which is a form concern, which is this.
1927    ///
1928    /// The membership test passes on every host and not by a stretch: a Tauri
1929    /// app opens a native picker, a server renders `<input type="file">`, a
1930    /// terminal prompts for a path, a CLI takes an argument. That is closer to
1931    /// [`Email`](Self::Email), which exists because it changes the keyboard,
1932    /// than to anything bespoke.
1933    ///
1934    /// It carries no accepted-types list and no multiple flag, and that is
1935    /// measured rather than deferred: `accept` appears at zero sites in either
1936    /// app. A member added for a case nobody has is a member designed against
1937    /// nothing.
1938    File,
1939    /// Carried through the form and never shown.
1940    Hidden,
1941}
1942
1943/// The wire format a [`FieldKind::Date`] value takes: ISO 8601, `YYYY-MM-DD`.
1944///
1945/// A constant rather than a sentence in a doc comment, because the reason to
1946/// name the format at all is that a host picking its own would fail silently
1947/// against a server parsing another. A host that cannot emit the native control
1948/// still has one spelling to meet, and can say which one it meant.
1949pub const DATE_FORMAT: &str = "%Y-%m-%d";
1950
1951/// The wire format a [`FieldKind::DateTime`] value takes: `YYYY-MM-DDTHH:MM`,
1952/// local, carrying no zone and no seconds.
1953///
1954/// [`DATE_FORMAT`]'s sibling and there for its reason. The absent zone is a
1955/// property of the value rather than an omission: the moment is not fixed until
1956/// something outside the description supplies one.
1957pub const DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M";
1958
1959impl FieldKind {
1960    /// Whether the value the kind takes is a moment rather than a string.
1961    ///
1962    /// Named once here for the reason [`offers_options`](Self::offers_options)
1963    /// is: two kinds answer yes, and a host that has to parse or format a value
1964    /// needs to ask without spelling the pair out at each renderer. A third
1965    /// temporal kind should land here and nowhere else.
1966    ///
1967    /// The format each one takes is [`DATE_FORMAT`] and [`DATETIME_FORMAT`].
1968    #[must_use]
1969    pub const fn temporal(self) -> bool {
1970        matches!(self, Self::Date | Self::DateTime)
1971    }
1972
1973    /// Whether the field is drawn at all.
1974    #[must_use]
1975    pub const fn visible(self) -> bool {
1976        !matches!(self, Self::Hidden)
1977    }
1978
1979    /// Whether the value must be kept out of logs and diagnostics.
1980    #[must_use]
1981    pub const fn confidential(self) -> bool {
1982        matches!(self, Self::Secret)
1983    }
1984
1985    /// Where the field's own label sits.
1986    ///
1987    /// A checkbox labels itself on the right of the box; everything else takes
1988    /// a label above. Both webview apps already do this and both special-case
1989    /// it inline, which is the tell that it belongs in the description.
1990    ///
1991    /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
1992    /// naming: its *options* each label themselves, but the field still asks a
1993    /// question above them, so the group takes a label like everything else.
1994    #[must_use]
1995    pub const fn labels_itself(self) -> bool {
1996        matches!(self, Self::Checkbox)
1997    }
1998
1999    /// Whether the kind reads [`Field::options`].
2000    ///
2001    /// Two kinds do, so the pair is named once here rather than spelled out at
2002    /// each renderer and again in [`Field::options`]' own doc, where "every
2003    /// kind but `Select`" was true for exactly one release. A third
2004    /// option-taking kind should land here and nowhere else.
2005    #[must_use]
2006    pub const fn offers_options(self) -> bool {
2007        matches!(self, Self::Select | Self::Radio)
2008    }
2009}
2010
2011/// One option offered by a field [`FieldKind::offers_options`] accepts.
2012///
2013/// Two strings, because the submitted value and the read label are different
2014/// facts and every renderer that has tried to collapse them has had to
2015/// un-collapse them later. `makeover-webview` invented this shape writing its
2016/// form emitter and it is taken here unchanged; moving it down rather than
2017/// re-deriving it is the point, since the second and third renderers were each
2018/// going to arrive at a near-miss of it.
2019#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2020pub struct Choice<'a> {
2021    /// What is submitted.
2022    pub value: &'a str,
2023    /// What is read.
2024    pub label: &'a str,
2025}
2026
2027impl<'a> Choice<'a> {
2028    /// An option whose submitted value is also its label.
2029    #[must_use]
2030    pub const fn plain(value: &'a str) -> Self {
2031        Self {
2032            value,
2033            label: value,
2034        }
2035    }
2036}
2037
2038/// One field of a form.
2039///
2040/// Borrowed rather than owned: a description is built, read once by a renderer,
2041/// and dropped. Nothing here outlives the screen it describes.
2042///
2043/// # What it carries, and what it does not
2044///
2045/// Stated here so the next renderer does not re-ask, which is what the first
2046/// two both did. It carries everything a renderer needs to *draw* the field:
2047/// its kind, what it is called, what it is asked for, its standing help, what
2048/// is wrong with it now, whether it is compulsory, whether it hides behind a
2049/// disclosure, its ghost text, and the options it offers.
2050///
2051/// It does not carry the **current value**, and it is not going to. That is the
2052/// one thing here that is genuinely renderer state: a webview reads it back out
2053/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
2054/// and writes through it, and a terminal keeps an edit buffer. A description
2055/// that carried the value would have to carry a way to write it back, at which
2056/// point it is a form model and no longer a description.
2057///
2058/// **Constraints** are here and enforcement is not, which is one line rather
2059/// than two. [`required`], [`max_length`], [`min`] and [`max`] are facts about
2060/// the *question*, so a renderer can emit its host's idiom for each — an HTML
2061/// attribute, a marked label, a clamped spinner — and the platform helps the
2062/// user before anything is submitted. Deciding that a value is wrong stays with
2063/// whoever validated, and [`error`] is that decision arriving back.
2064///
2065/// The set stops before `pattern`, and stops there on both tests at once. A
2066/// regex has an honest answer in a webview and none anywhere else: egui would
2067/// have to run it per keystroke and decide what a half-typed value means, which
2068/// is enforcement wearing description's clothes. And it is one site in goingson
2069/// and none in Balanced Breakfast, against 8 and 1 for `maxlength`. Measured
2070/// 2026-08-09, `2cbad3e2`.
2071///
2072/// [`error`]: Field::error
2073/// [`required`]: Field::required
2074/// [`max_length`]: Field::max_length
2075/// [`min`]: Field::min
2076/// [`max`]: Field::max
2077#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2078pub struct Field<'a> {
2079    /// What kind of value it takes.
2080    pub kind: FieldKind,
2081    /// The name the value is submitted under.
2082    pub name: &'a str,
2083    /// What the user is asked for.
2084    pub label: &'a str,
2085    /// Standing help, shown whether or not anything is wrong.
2086    pub hint: Option<&'a str>,
2087    /// What is currently wrong with the value.
2088    pub error: Option<&'a str>,
2089    /// Ghost text shown while the field is empty.
2090    ///
2091    /// User-facing text, and it sits with `label` and `hint` rather than with
2092    /// the value because it is a property of the *question* and not of the
2093    /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
2094    /// reason and it was not a reading on where it belonged: adding a field to
2095    /// a published struct is a breaking change.
2096    ///
2097    /// Not a substitute for a label. A field labelled only by its placeholder
2098    /// loses its label the moment anything is typed, and no renderer here can
2099    /// make that not happen, so the description keeps both.
2100    pub placeholder: Option<&'a str>,
2101    /// The options offered, in the order they are offered.
2102    ///
2103    /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
2104    /// described with no options is sayable on purpose: it is what an app with
2105    /// an unfinished-loading option list actually has, and a renderer showing
2106    /// an empty control says so on screen rather than in a log.
2107    ///
2108    /// Which option is *current* is not here. That is the value, and the value
2109    /// is renderer state.
2110    pub options: &'a [Choice<'a>],
2111    /// Whether the form refuses to submit without it.
2112    pub required: bool,
2113    /// The longest the value may be, in characters.
2114    ///
2115    /// Added 0.11.0 with [`min`](Self::min) and [`max`](Self::max), joining
2116    /// [`required`](Self::required), which had been the only constraint here
2117    /// since before the crate wrote down that it carried none.
2118    pub max_length: Option<u32>,
2119    /// The lowest value accepted, as the host would write it.
2120    ///
2121    /// Text rather than a number, because the bound is only a number for some
2122    /// of the kinds that take one. goingson's own sites are `min="1"` on a
2123    /// duration and `min="2026-08-09T14:30"` on a datetime, and a numeric member
2124    /// could say the first and not the second. The [`kind`](Self::kind) already
2125    /// says how to read it, the same way it does for the value.
2126    pub min: Option<&'a str>,
2127    /// The highest value accepted, as the host would write it. See
2128    /// [`min`](Self::min).
2129    pub max: Option<&'a str>,
2130    /// Whether the field lives behind a "more options" disclosure.
2131    pub extended: bool,
2132}
2133
2134impl<'a> Field<'a> {
2135    /// A plain required-nothing field of the given kind.
2136    #[must_use]
2137    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
2138        Self {
2139            kind,
2140            name,
2141            label,
2142            hint: None,
2143            error: None,
2144            placeholder: None,
2145            options: &[],
2146            required: false,
2147            max_length: None,
2148            min: None,
2149            max: None,
2150            extended: false,
2151        }
2152    }
2153
2154    /// A select offering the given options.
2155    ///
2156    /// One of the two kinds under-described by [`Field::new`], so it gets a
2157    /// constructor rather than leaving every call site to remember that a
2158    /// select with an empty `options` renders as an empty select.
2159    #[must_use]
2160    pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
2161        Self::offering(FieldKind::Select, name, label, options)
2162    }
2163
2164    /// A radio group offering the given options.
2165    ///
2166    /// The other. Same hazard as [`select`](Self::select) and a worse one: a
2167    /// radio group with no options draws nothing at all, so a call site that
2168    /// forgot them has an empty rectangle rather than a visibly empty control.
2169    #[must_use]
2170    pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
2171        Self::offering(FieldKind::Radio, name, label, options)
2172    }
2173
2174    /// The shared body of the two constructors that take options.
2175    ///
2176    /// Private, and keyed on the kind rather than exposed, because the two
2177    /// public names are the point: a call site says which question it is
2178    /// asking, not which flag it is setting.
2179    const fn offering(
2180        kind: FieldKind,
2181        name: &'a str,
2182        label: &'a str,
2183        options: &'a [Choice<'a>],
2184    ) -> Self {
2185        Self {
2186            options,
2187            ..Self::new(kind, name, label)
2188        }
2189    }
2190
2191    /// Whether the field is currently reporting a problem.
2192    ///
2193    /// Read this rather than testing `error.is_some()` at each renderer: the
2194    /// error state has to mark the field's whole group and not only the
2195    /// message, because a renderer with no descendant selectors (egui, a
2196    /// terminal) cannot find the group from the message. goingson already marks
2197    /// the group and Balanced Breakfast does not, so goingson's shape is the
2198    /// one taken here.
2199    #[must_use]
2200    pub const fn invalid(&self) -> bool {
2201        self.error.is_some()
2202    }
2203}
2204
2205/// How much room a column asks for.
2206///
2207/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
2208/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
2209/// only the first three words of that survive deferral.
2210/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
2211/// renderer matches on this and a vocabulary that grows must not break every
2212/// renderer when it does.
2213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2214#[non_exhaustive]
2215pub enum Width {
2216    /// Takes what it needs and no more.
2217    Content,
2218    /// A fixed share, the same at every width.
2219    Fixed,
2220    /// Absorbs whatever is left over.
2221    Fill,
2222}
2223
2224/// What a column is worth when there is not room for all of them.
2225///
2226/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
2227/// drops. This replaces addressing columns by position, which is what both
2228/// webview apps do today and is a live bug rather than only verbosity. goingson
2229/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
2230/// inserting a column silently hides the wrong one.
2231/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
2232/// whole point of the type, so a new tier has to be declared in its place in
2233/// the sequence rather than appended.
2234#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2235#[non_exhaustive]
2236pub enum Priority {
2237    /// Dropped first.
2238    Optional,
2239    /// Dropped once the optional columns are gone.
2240    Secondary,
2241    /// Never dropped. Without it the row does not identify itself.
2242    Essential,
2243}
2244
2245/// One column of a table.
2246///
2247/// Described once. The grid track, the cell order and the drop behaviour are
2248/// all derived from this, rather than being three hand-written encodings that
2249/// must agree and are never checked against each other.
2250#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2251pub struct Column<'a> {
2252    /// The heading, and the name the cell is addressed by.
2253    pub name: &'a str,
2254    /// How much room it asks for.
2255    pub width: Width,
2256    /// What it is worth when room runs out.
2257    pub priority: Priority,
2258    /// Whether the user can reorder the table by this column.
2259    ///
2260    /// `ce620871`. What reordering *calls* is not here — that is an address, and
2261    /// this crate names none — so a host pairs this with the route the way it
2262    /// pairs a row's parts with the row's activation. This says the affordance
2263    /// exists, which is what a renderer needs to draw a header a user can press
2264    /// rather than a heading they cannot.
2265    pub sortable: bool,
2266    /// Which way the table is ordered by this column, if it is.
2267    ///
2268    /// `None` on every column but the one in force. A renderer draws the caret
2269    /// from this and a webview sets `aria-sort`, which is why it is per column
2270    /// rather than a single fact on the table: the host idiom is a property of
2271    /// the header cell.
2272    ///
2273    /// Independent of [`sortable`](Self::sortable) rather than implied by it,
2274    /// because both combinations mean something. A column sorted and not
2275    /// sortable is a list ordered by a key the user cannot change, which is a
2276    /// real thing to describe and a caret worth drawing.
2277    pub sorted: Option<Sort>,
2278}
2279
2280/// Which way a column is ordered.
2281///
2282/// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
2283/// `None`, and folding it in here would be the same absence said twice.
2284#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2285pub enum Sort {
2286    /// Smallest, earliest or first alphabetically at the top.
2287    Ascending,
2288    /// The other way.
2289    Descending,
2290}
2291
2292impl Sort {
2293    /// The other direction, for a header that flips when pressed.
2294    #[must_use]
2295    pub const fn reversed(self) -> Self {
2296        match self {
2297            Self::Ascending => Self::Descending,
2298            Self::Descending => Self::Ascending,
2299        }
2300    }
2301
2302    /// What a webview writes into `aria-sort`.
2303    ///
2304    /// Named here rather than in the webview renderer because a terminal and an
2305    /// immediate-mode painter both want the same two words for a caret's label,
2306    /// and three renderers picking their own is the drift this crate ends.
2307    #[must_use]
2308    pub const fn as_str(self) -> &'static str {
2309        match self {
2310            Self::Ascending => "ascending",
2311            Self::Descending => "descending",
2312        }
2313    }
2314}
2315
2316impl<'a> Column<'a> {
2317    /// A column that absorbs slack and drops after the optional ones.
2318    #[must_use]
2319    pub const fn new(name: &'a str) -> Self {
2320        Self {
2321            name,
2322            width: Width::Fill,
2323            priority: Priority::Secondary,
2324            sortable: false,
2325            sorted: None,
2326        }
2327    }
2328
2329    /// Whether this column survives at the given cutoff.
2330    ///
2331    /// A renderer narrows by raising the cutoff, and never by counting
2332    /// positions.
2333    #[must_use]
2334    pub const fn kept_at(&self, cutoff: Priority) -> bool {
2335        (self.priority as u8) >= (cutoff as u8)
2336    }
2337}
2338
2339/// What a table cell holds.
2340///
2341/// [`RowPart`] for tables, and it exists for the same reason: a part that
2342/// carries a control is not text, and a renderer with one class for the whole
2343/// cell paints it as though it were. `makeover-webview` emitted a single
2344/// `.cell` until 0.25.0, so a button in a cell inherited the cell's content
2345/// colour, which is the exact drift [`RowPart::intent`] prevents for rows and
2346/// prevented for nothing here.
2347///
2348/// Four members, and the count is what quasi's `Cell` was measured to carry:
2349/// a value, tokens (33 cells across 22 server templates), actions (30 rows
2350/// carrying a control, 5 beside a value) and a link (35 cells across 18
2351/// templates). Nothing was added past what something holds.
2352///
2353/// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
2354/// lockstep event across three renderers.
2355///
2356/// # No hover-reveal
2357///
2358/// [`RowPart`] carried a `revealed_on_hover` until 0.13.0 retired it, and this
2359/// enum never gets one. A cell's actions are shown at rest in every consumer
2360/// measured, and a member nothing uses is one three renderers owe an answer
2361/// for.
2362#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2363#[non_exhaustive]
2364pub enum CellPart {
2365    /// The cell's own text.
2366    Value,
2367    /// Small labelled things in the cell: a status badge, a chip.
2368    Tokens,
2369    /// Controls that act on what the row is about.
2370    Actions,
2371    /// The cell's value, where the value is itself a link.
2372    Link,
2373}
2374
2375impl CellPart {
2376    /// The content intent the part takes.
2377    ///
2378    /// One part is text and three are not, so three answer with the intent
2379    /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
2380    /// text side narrower: a cell's secondary and muted readings are the
2381    /// column's business, not the cell's.
2382    #[must_use]
2383    pub const fn intent(self) -> &'static str {
2384        match self {
2385            Self::Value => "content",
2386            // A token carries its own tone, and a part-level intent underneath
2387            // it would fight the token sitting on it.
2388            Self::Tokens => "content",
2389            // Actions carry controls rather than text.
2390            Self::Actions => "content",
2391            // A link takes the action colour from the control it is, rather
2392            // than the cell's text colour from the cell it sits in.
2393            Self::Link => "content",
2394        }
2395    }
2396}
2397
2398#[cfg(test)]
2399mod tests {
2400    use super::*;
2401
2402    #[test]
2403    fn the_four_readiness_states_are_one_axis_and_only_one_shows_content() {
2404        // Mutually exclusive is the test for one enum against several fields: a
2405        // region shows its content, or that it is coming, or that there is none,
2406        // or that it broke. Never two.
2407        assert!(Readiness::Ready.shows_content());
2408        for state in [Readiness::Pending, Readiness::Empty, Readiness::Failed] {
2409            assert!(!state.shows_content());
2410        }
2411    }
2412
2413    #[test]
2414    fn an_empty_region_is_not_a_broken_one() {
2415        // An empty list is the normal state of a new install. Drawing it in a
2416        // danger tone reports a fault where there is none, and this is the one
2417        // place the distinction is carried.
2418        assert_eq!(Readiness::Empty.tone(), Tone::Neutral);
2419        assert_eq!(Readiness::Failed.tone(), Tone::Danger);
2420        assert_eq!(Readiness::Pending.tone(), Tone::Neutral);
2421    }
2422
2423    #[test]
2424    fn a_column_can_be_sorted_without_being_sortable() {
2425        // Both combinations mean something, which is why the two fields are
2426        // independent rather than one implying the other. A list ordered by a
2427        // key the user cannot change is a real thing with a caret worth drawing.
2428        let fixed = Column {
2429            sorted: Some(Sort::Descending),
2430            ..Column::new("Created")
2431        };
2432
2433        assert!(!fixed.sortable);
2434        assert_eq!(fixed.sorted.map(Sort::as_str), Some("descending"));
2435
2436        let offered = Column {
2437            sortable: true,
2438            ..Column::new("Name")
2439        };
2440        assert_eq!(offered.sorted, None);
2441    }
2442
2443    #[test]
2444    fn a_direction_flips_and_says_what_it_is() {
2445        assert_eq!(Sort::Ascending.reversed(), Sort::Descending);
2446        assert_eq!(Sort::Descending.reversed().reversed(), Sort::Descending);
2447        assert_eq!(Sort::Ascending.as_str(), "ascending");
2448    }
2449
2450    #[test]
2451    fn a_figure_carries_its_tone_because_no_renderer_can_derive_it() {
2452        // Three of goingson's five sites tone the figure by their own means, so
2453        // tone is carried at every site that needs it and derived at none. The
2454        // same reasoning `Meter` reached, from a different direction.
2455        let streak = Figure::new("0", "Current Streak").tone(Tone::Warning);
2456        assert_eq!(streak.tone, Tone::Warning);
2457        assert_eq!(Figure::new("17", "Total").tone, Tone::Neutral);
2458    }
2459
2460    #[test]
2461    fn a_figures_change_is_the_toned_part_and_is_absent_by_default() {
2462        // 0.13.0. The MNW server's stat card is a label, a value and a delta,
2463        // across four screens, and the delta is what reads as good or bad. Tone
2464        // had no consumer before this: the figure itself is an ordinary fact.
2465        let views = Figure::new("1,204", "Views")
2466            .change("+12.5%")
2467            .tone(Tone::Success);
2468        assert_eq!(views.change, Some("+12.5%"));
2469        assert_eq!(views.tone, Tone::Success);
2470
2471        // A figure with nothing to compare against says so by having no change,
2472        // rather than by carrying an empty string a renderer has to test for.
2473        assert_eq!(Figure::new("3.1%", "Conversion").change, None);
2474    }
2475
2476    #[test]
2477    fn a_figures_value_is_text_because_only_the_app_knows_what_it_is() {
2478        // "84%", "12/30", "3d". A figure is whatever the app computed, already
2479        // formatted, and that is the line between this and `Meter`: a meter is
2480        // a proportion a renderer draws, a figure is a fact it sets in type.
2481        for value in ["84%", "12/30", "3d"] {
2482            assert_eq!(Figure::new(value, "Rate").value, value);
2483        }
2484    }
2485
2486    #[test]
2487    fn a_proportion_is_a_row_part_and_takes_no_intent_of_its_own() {
2488        // The meter carries the tone, so a part-level intent underneath would
2489        // fight it. Same answer `Tokens` needed, for the same reason.
2490        assert_eq!(RowPart::Proportion.intent(), RowPart::Tokens.intent());
2491    }
2492
2493    #[test]
2494    fn a_file_field_is_drawn_and_offers_no_options() {
2495        // It is a control the user operates, unlike `Hidden`, and it does not
2496        // pick from a list the description carries, unlike `Select`.
2497        assert!(FieldKind::File.visible());
2498        assert!(!FieldKind::File.offers_options());
2499        assert!(!FieldKind::File.confidential());
2500    }
2501
2502    #[test]
2503    fn a_constraint_is_a_fact_about_the_question_and_not_a_verdict() {
2504        // The whole model: the description carries the rule, the renderer emits
2505        // its host's idiom, and `error` is what arrives back when someone
2506        // validated. Nothing here decides a value is wrong.
2507        let field = Field {
2508            max_length: Some(100),
2509            min: Some("1"),
2510            max: Some("240"),
2511            required: true,
2512            ..Field::new(FieldKind::Number, "minutes", "Minutes")
2513        };
2514        assert!(!field.invalid());
2515
2516        // A bound is text because it is only a number for some of the kinds
2517        // that take one. goingson has both shapes live.
2518        let when = Field {
2519            min: Some("2026-08-09T14:30"),
2520            ..Field::new(FieldKind::Text, "starts", "Starts")
2521        };
2522        assert_eq!(when.min, Some("2026-08-09T14:30"));
2523    }
2524
2525    #[test]
2526    fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
2527        // The whole reason this is a pair. goingson's `Task::time_progress`
2528        // clamps to 100 and then carries `is_over_estimate` beside it to say
2529        // what the clamp dropped; a meter says both from one fact.
2530        let over = Meter::new(45, 30);
2531        assert_eq!(over.percent(), 100);
2532        assert!(over.overflowing());
2533
2534        let exact = Meter::new(30, 30);
2535        assert_eq!(exact.percent(), over.percent());
2536        assert!(!exact.overflowing());
2537    }
2538
2539    #[test]
2540    fn an_empty_set_does_not_divide_by_zero() {
2541        // Sayable on purpose, so it has to be answerable. A meter over an
2542        // unloaded count is what an app actually has for a frame.
2543        let none = Meter::new(0, 0);
2544        assert_eq!(none.percent(), 0);
2545        assert!(none.is_empty());
2546        assert!(!none.overflowing());
2547    }
2548
2549    #[test]
2550    fn the_ratio_survives_where_a_percentage_would_not() {
2551        // Given 43 nothing can recover "3 of 7", which is why the numbers are
2552        // carried and the label names only the noun.
2553        let m = Meter::new(3, 7).label("subtasks");
2554        assert_eq!(m.percent(), 42);
2555        assert_eq!((m.done, m.total), (3, 7));
2556        assert_eq!(m.label, Some("subtasks"));
2557    }
2558
2559    #[test]
2560    fn tone_is_carried_because_no_renderer_can_derive_it() {
2561        // The same fullness means opposite things on two of goingson's bars,
2562        // and only the app knows which.
2563        let subtasks = Meter::new(9, 10).tone(Tone::Success);
2564        let estimate = Meter::new(9, 10).tone(Tone::Danger);
2565        assert_eq!(subtasks.percent(), estimate.percent());
2566        assert_ne!(subtasks.tone, estimate.tone);
2567        // Untoned by default: a bar says nothing about status until something
2568        // says so, the same way a row is not selectable until told.
2569        assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
2570    }
2571
2572    #[test]
2573    fn an_act_is_reachable_until_it_is_disabled() {
2574        // The one member a renderer must branch on, and since 0.19.0 the only
2575        // member there is. A stated state is not by itself a reason to stop
2576        // answering, which is the distinction `State` makes and every
2577        // hand-rolled button in the tree had to remember.
2578        assert!(!Act::new("Save").disabled());
2579        assert!(Act::new("Save").state(State::Disabled).disabled());
2580    }
2581
2582    #[test]
2583    fn an_act_carries_its_key_because_a_terminal_has_nothing_else() {
2584        // No key is the ordinary case, and the webview hosts that ignore it
2585        // are why it stayed optional.
2586        assert_eq!(Act::new("Delete").key, None);
2587        let quit = Act::new("Quit").key("q").tone(Tone::Danger);
2588        assert_eq!(quit.key, Some("q"));
2589        assert_eq!(quit.tone, Tone::Danger);
2590    }
2591
2592    #[test]
2593    fn a_meter_does_not_overflow_on_large_counts() {
2594        // done * 100 in u32 would wrap somewhere past 42 million. Counts that
2595        // size are not tasks, but a description layer that silently reports 3%
2596        // for a full bar is worse than one that is slow.
2597        let big = Meter::new(u32::MAX, u32::MAX);
2598        assert_eq!(big.percent(), 100);
2599        assert!(!big.overflowing());
2600    }
2601
2602    #[test]
2603    fn inset_is_raised_with_the_light_moved() {
2604        let (rl, rd) = Bevel::Raised.edges();
2605        let (il, id) = Bevel::Inset.edges();
2606        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
2607        assert_eq!((il, id), (rd, rl));
2608    }
2609
2610    #[test]
2611    fn pressing_twice_is_a_no_op() {
2612        for b in [Bevel::Raised, Bevel::Inset] {
2613            assert_eq!(b.pressed().pressed(), b);
2614        }
2615    }
2616
2617    #[test]
2618    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
2619        // The bug this vocabulary exists to make unrepresentable.
2620        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
2621        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
2622        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
2623        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
2624    }
2625
2626    #[test]
2627    fn state_is_orthogonal_to_depth() {
2628        // The reason State is its own axis and not a Depth member: a disabled
2629        // button and a disabled field are both disabled and are not the same
2630        // shape, which one shared variant could not have said.
2631        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
2632        assert_eq!(Depth::Well.fill(), Some(Fill::Well));
2633        assert!(State::Disabled.suppresses_interaction());
2634    }
2635
2636    #[test]
2637    fn only_disabled_stops_answering() {
2638        // Kept in spirit from the version where `Focus` was the counter-example:
2639        // suppressing interaction is `Disabled`'s alone, so a member added here
2640        // later does not get to inherit it by being a state.
2641        assert!(State::Disabled.suppresses_interaction());
2642    }
2643
2644    #[test]
2645    fn disabled_resolves_against_an_intent_makeover_already_derives() {
2646        // No new token, so this costs no `makeover` release.
2647        assert_eq!(State::Disabled.token(), "content-muted");
2648    }
2649
2650    #[test]
2651    fn flat_has_neither_edge_nor_fill() {
2652        assert_eq!(Depth::Flat.bevel(), None);
2653        assert_eq!(Depth::Flat.fill(), None);
2654    }
2655
2656    #[test]
2657    fn sunken_is_recessed_by_colour_with_no_edge() {
2658        // The one member carrying a fill without a bevel. A renderer that
2659        // assumes the two arrive together drops the fill silently, which is
2660        // exactly what makeover-webview did before 0.3.0.
2661        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
2662        assert_eq!(Depth::Sunken.bevel(), None);
2663    }
2664
2665    #[test]
2666    fn sunken_and_flat_are_different_claims() {
2667        // Both edgeless, and only one of them needs a colour. Collapsing them
2668        // is what left an unchosen tab unsayable.
2669        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
2670        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
2671    }
2672
2673    #[test]
2674    fn a_sunken_surface_is_not_a_well() {
2675        // Authored in opposite directions: makeover derives surface-well by
2676        // inverting against the theme's content colour, while surface-sunken is
2677        // authored and may sit darker than raised.
2678        assert_ne!(Fill::Sunken, Fill::Well);
2679        assert_eq!(Fill::Sunken.token(), "surface-sunken");
2680        assert_eq!(Fill::Well.token(), "surface-well");
2681    }
2682
2683    #[test]
2684    fn every_selector_describes_both_of_its_states() {
2685        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
2686        // unchosen option fell through to Flat at every renderer.
2687        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
2688            assert_ne!(
2689                s.chosen(),
2690                s.unchosen(),
2691                "{s:?} cannot tell picked from unpicked"
2692            );
2693        }
2694    }
2695
2696    #[test]
2697    fn only_a_tab_inverts_the_other_way() {
2698        // Tabs recede so the chosen one comes forward; a segment and a toggle
2699        // stand up so the chosen one is held in. That inversion is the whole
2700        // content of "picked" once colour is deferred, and it is why the three
2701        // are not one member with a flag.
2702        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
2703        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
2704
2705        for s in [Selector::Segmented, Selector::Toggle] {
2706            assert_eq!(s.unchosen(), Depth::Raised);
2707            assert_eq!(s.chosen(), Depth::Well);
2708            // Held in is what pressing produces: one appearance, two reasons.
2709            assert_eq!(s.unchosen().pressed(), s.chosen());
2710        }
2711    }
2712
2713    #[test]
2714    fn pressing_a_card_makes_a_well() {
2715        assert_eq!(Depth::Raised.pressed(), Depth::Well);
2716        assert_eq!(
2717            Depth::Raised.pressed().bevel(),
2718            Depth::Raised.bevel().map(Bevel::pressed)
2719        );
2720        // Only raised regions respond to being pressed.
2721        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
2722        assert_eq!(Depth::Well.pressed(), Depth::Well);
2723        // An overlay is a surface, not a control.
2724        assert_eq!(Depth::Overlay.pressed(), Depth::Overlay);
2725    }
2726
2727    #[test]
2728    fn an_overlay_is_lifted_rather_than_edged() {
2729        // The wave-2 rule: a surface over the page takes elevation, a surface
2730        // in the page takes a bevel. Both halves come off the one Depth, so
2731        // they cannot disagree.
2732        assert_eq!(Depth::Overlay.fill(), Some(Fill::Overlay));
2733        assert_eq!(Depth::Overlay.bevel(), None);
2734
2735        // Three depths have no bevel and they are not the same claim. Flat has
2736        // nothing to separate from, Sunken's colour is doing the separating,
2737        // and an overlay is separated by the lift.
2738        assert_ne!(Depth::Overlay.fill(), Depth::Sunken.fill());
2739        assert_ne!(Depth::Overlay.fill(), Depth::Flat.fill());
2740    }
2741
2742    #[test]
2743    fn intents_name_makeover_tokens_and_nothing_else() {
2744        assert_eq!(Edge::Light.token(), "bevel-light");
2745        assert_eq!(Edge::Dark.token(), "bevel-dark");
2746        assert_eq!(Fill::Raised.token(), "surface-raised");
2747        assert_eq!(Fill::Well.token(), "surface-well");
2748        // No value ever leaves this crate.
2749        for t in [
2750            Edge::Light.token(),
2751            Edge::Dark.token(),
2752            Tone::Danger.token(),
2753            Tone::Neutral.token(),
2754            State::Disabled.token(),
2755        ] {
2756            assert!(!t.starts_with('#'), "{t} looks like a value");
2757            assert!(
2758                !t.chars().next().unwrap().is_ascii_digit(),
2759                "{t} is a value"
2760            );
2761        }
2762    }
2763
2764    #[test]
2765    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
2766        // The one line that runs through all three apps' taxonomies.
2767        assert!(!Token::Badge.interactive());
2768        assert!(Token::Chip { removable: false }.interactive());
2769        assert!(Token::Chip { removable: true }.interactive());
2770
2771        // A badge is a label, so giving it an edge would lie about it.
2772        assert_eq!(Token::Badge.depth(false), Depth::Flat);
2773        assert_eq!(Token::Badge.depth(true), Depth::Flat);
2774
2775        // A latched chip wears the same shape a pressed one does.
2776        let chip = Token::Chip { removable: false };
2777        assert_eq!(chip.depth(false), Depth::Raised);
2778        assert_eq!(chip.depth(true), Depth::Raised.pressed());
2779    }
2780
2781    #[test]
2782    fn a_toast_and_a_banner_differ_in_more_than_placement() {
2783        assert!(Notice::Toast.transient());
2784        assert!(!Notice::Banner.transient());
2785        // A toast floats above the page; a banner rests in the flow.
2786        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
2787        assert_eq!(Notice::Banner.fill(), Fill::Raised);
2788    }
2789
2790    #[test]
2791    fn emphasis_falls_off_down_the_row() {
2792        // `revealed_on_hover` was asserted here until 0.13.0 retired it. It said
2793        // a row's actions stay hidden until hover, which stopped being true when
2794        // makeover-webview 0.23.0 showed them at rest, and nothing had consumed
2795        // it for a release either way.
2796        assert_eq!(RowPart::Primary.intent(), "content");
2797        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
2798        assert_eq!(RowPart::Meta.intent(), "content-muted");
2799    }
2800
2801    #[test]
2802    fn a_token_part_carries_no_intent_of_its_own() {
2803        // Each token carries its own tone, so a part-level intent underneath
2804        // would fight the thing sitting on it. Same reasoning as actions, which
2805        // is why they answer alike.
2806        assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
2807        assert_eq!(RowPart::Tokens.intent(), "content");
2808    }
2809
2810    #[test]
2811    fn the_two_temporal_kinds_are_the_two_that_name_a_moment() {
2812        // The pair is named once so a host with parsing to do asks here rather
2813        // than spelling it out, which is `offers_options`' reason.
2814        assert!(FieldKind::Date.temporal());
2815        assert!(FieldKind::DateTime.temporal());
2816
2817        for kind in [
2818            FieldKind::Text,
2819            FieldKind::Secret,
2820            FieldKind::Number,
2821            FieldKind::Email,
2822            FieldKind::Url,
2823            FieldKind::Tel,
2824            FieldKind::Textarea,
2825            FieldKind::Select,
2826            FieldKind::Radio,
2827            FieldKind::Checkbox,
2828            FieldKind::File,
2829            FieldKind::Hidden,
2830        ] {
2831            assert!(!kind.temporal(), "{kind:?}");
2832        }
2833    }
2834
2835    #[test]
2836    fn a_date_carries_no_time_and_a_datetime_carries_no_zone() {
2837        // The formats are the whole reason the members are worth naming apart
2838        // from text, so the doc comments and the constants have to agree. A
2839        // host reading one and meeting the other is the silent failure.
2840        assert_eq!(DATE_FORMAT, "%Y-%m-%d");
2841        assert!(!DATE_FORMAT.contains("%H"), "a day carries no hour");
2842
2843        assert_eq!(DATETIME_FORMAT, "%Y-%m-%dT%H:%M");
2844        assert!(
2845            DATETIME_FORMAT.starts_with(DATE_FORMAT),
2846            "a moment starts with the day it is on"
2847        );
2848        // Local, and that is a property of the value rather than an omission.
2849        assert!(!DATETIME_FORMAT.contains("%Z"), "no zone name");
2850        assert!(!DATETIME_FORMAT.ends_with('Z'), "not UTC-stamped");
2851        assert!(!DATETIME_FORMAT.contains("%S"), "no seconds by default");
2852    }
2853
2854    #[test]
2855    fn a_temporal_kind_takes_a_label_above_it_and_offers_no_options() {
2856        // Neither is a checkbox and neither is a fixed set, so both fall where
2857        // text does. Asserted because a new kind lands in three predicates and
2858        // only one of them is the interesting one.
2859        for kind in [FieldKind::Date, FieldKind::DateTime] {
2860            assert!(kind.visible(), "{kind:?}");
2861            assert!(!kind.confidential(), "{kind:?}");
2862            assert!(!kind.labels_itself(), "{kind:?}");
2863            assert!(!kind.offers_options(), "{kind:?}");
2864        }
2865    }
2866
2867    #[test]
2868    fn a_cell_part_names_an_intent_and_only_the_value_is_text() {
2869        // The table half of what RowPart::intent does for rows. A cell holding
2870        // a control and a cell holding text answered alike until 0.14.0, and a
2871        // control in a cell took the cell's text colour.
2872        assert_eq!(CellPart::Value.intent(), "content");
2873
2874        for part in [CellPart::Tokens, CellPart::Actions, CellPart::Link] {
2875            // Each for its own reason -- a token carries its tone, an action is
2876            // a control, a link takes the action colour -- and all three reach
2877            // the intent inheriting already gives.
2878            assert_eq!(part.intent(), CellPart::Value.intent(), "{part:?}");
2879        }
2880    }
2881
2882    #[test]
2883    fn every_cell_part_answers_with_a_token_and_never_a_value() {
2884        for part in [
2885            CellPart::Value,
2886            CellPart::Tokens,
2887            CellPart::Actions,
2888            CellPart::Link,
2889        ] {
2890            let intent = part.intent();
2891            assert!(!intent.is_empty(), "{part:?} names nothing");
2892            assert!(!intent.starts_with('#'), "{part:?} looks like a value");
2893        }
2894    }
2895
2896    #[test]
2897    fn a_separator_is_what_tells_a_section_from_a_subsection() {
2898        assert!(Heading::Section.separated());
2899        assert!(!Heading::Subsection.separated());
2900        assert!(!Heading::Page.separated());
2901    }
2902
2903    #[test]
2904    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
2905        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2906        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
2907        // The exception, and the whole folder semantic: the open tab joins its
2908        // pane rather than sinking away from it.
2909        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
2910
2911        // A held-in segment is indistinguishable from a pressed raised one,
2912        // which is the economy the light model buys over a colour swap.
2913        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
2914
2915        // A toggle stands alone; the other two are built out of parts that
2916        // touch.
2917        assert!(Selector::Segmented.abutting());
2918        assert!(Selector::Tabs.abutting());
2919        assert!(!Selector::Toggle.abutting());
2920    }
2921
2922    #[test]
2923    fn a_pane_is_looked_into_and_a_band_is_not() {
2924        assert_eq!(Region::Pane.depth(), Depth::Well);
2925        assert_eq!(Region::Modal.depth(), Depth::Raised);
2926        for r in [
2927            Region::Band,
2928            Region::Sidebar,
2929            Region::Split,
2930            Region::TabGroup,
2931        ] {
2932            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
2933        }
2934    }
2935
2936    #[test]
2937    fn exactly_one_region_is_opaque() {
2938        // The escape hatch is one member and stays one member. If a second
2939        // undescribed region ever appears, the description has started
2940        // conceding rather than deferring.
2941        for r in [
2942            Region::Band,
2943            Region::Sidebar,
2944            Region::Pane,
2945            Region::Split,
2946            Region::TabGroup,
2947            Region::Modal,
2948            // A widget is described, and that is the whole of what separates it
2949            // from a bespoke here. Both carry a name this crate never reads;
2950            // only one of them has contents under it that a renderer which does
2951            // not know the name can still walk.
2952            Region::Widget { name: "carousel" },
2953        ] {
2954            assert!(r.described(), "{r:?} should be describable");
2955        }
2956        assert!(!Region::Bespoke { name: "day-plan" }.described());
2957    }
2958
2959    #[test]
2960    fn a_picture_that_says_nothing_is_a_claim_and_not_an_oversight() {
2961        // The distinction a renderer with no graphics protocol runs on: draw
2962        // the words, or draw nothing. Standing in for a decorative rule with
2963        // the word "decoration" is worse than leaving the space empty.
2964        assert!(Image::new("The library view, mid-import").speaks());
2965        assert!(!Image::new("").speaks());
2966    }
2967
2968    #[test]
2969    fn a_caption_and_alt_text_are_not_the_same_line() {
2970        // A caption is content everybody reads; alt text stands in for the
2971        // picture. A screenshot with a caption still needs alt text.
2972        let shot = Image::new("A file list with three rows selected").caption("The library view");
2973        assert_eq!(shot.caption, Some("The library view"));
2974        assert!(shot.speaks());
2975        assert_ne!(shot.alt, shot.caption.unwrap());
2976    }
2977
2978    #[test]
2979    fn a_picture_keeps_its_own_proportions_unless_told_otherwise() {
2980        // The default is the one that shows the whole picture at its own shape,
2981        // so a renderer ignoring Fit entirely is still right about the common
2982        // case. The shipped MNW carousel sets no object-fit at all, which is
2983        // this.
2984        assert_eq!(Image::new("a").fit, Fit::Natural);
2985        assert_eq!(Fit::default(), Fit::Natural);
2986        assert_eq!(Image::new("a").fit(Fit::Cover).fit, Fit::Cover);
2987    }
2988
2989    #[test]
2990    fn a_widget_inherits_its_depth_the_way_a_bespoke_does() {
2991        // Stronger than the bespoke case: a widget is drawn by whichever
2992        // renderer recognises the name, so a depth chosen here would be this
2993        // crate deciding a carousel is raised on every host.
2994        assert_eq!(Region::Widget { name: "carousel" }.depth(), Depth::Flat);
2995        assert_eq!(Region::Widget { name: "pager" }.depth(), Depth::Flat);
2996    }
2997
2998    #[test]
2999    fn a_name_is_readable_without_asking_which_member_carried_it() {
3000        // A renderer dispatching on a name wants the string, not the member.
3001        // Writing that `matches!` at each renderer is how the two drift apart.
3002        assert_eq!(Region::Widget { name: "carousel" }.name(), Some("carousel"));
3003        assert_eq!(
3004            Region::Bespoke { name: "day-plan" }.name(),
3005            Some("day-plan")
3006        );
3007
3008        for r in [
3009            Region::Band,
3010            Region::Sidebar,
3011            Region::Pane,
3012            Region::Split,
3013            Region::TabGroup,
3014            Region::Modal,
3015        ] {
3016            assert_eq!(r.name(), None, "{r:?} names nothing an app chose");
3017        }
3018    }
3019
3020    #[test]
3021    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
3022        // The app owns the contents, not the placement. An app that wants its
3023        // timeline in a well frames it in a Pane.
3024        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
3025        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
3026    }
3027
3028    #[test]
3029    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
3030        // The argument the member exists for: goingson's day-plan has to be
3031        // routable, or the description covers only the boring screens and the
3032        // interesting four need a second path beside the router.
3033        let day_plan = [
3034            Region::Band,
3035            Region::Bespoke { name: "day-plan" },
3036            Region::Sidebar,
3037        ];
3038        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
3039        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
3040    }
3041
3042    #[test]
3043    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
3044        let secret = Field::new(FieldKind::Secret, "password", "Password");
3045        assert!(secret.kind.confidential());
3046        assert!(secret.kind.visible());
3047
3048        assert!(!FieldKind::Hidden.visible());
3049        // Nothing else is confidential, or the marker means nothing.
3050        for k in [
3051            FieldKind::Text,
3052            FieldKind::Number,
3053            FieldKind::Textarea,
3054            FieldKind::Select,
3055            FieldKind::Checkbox,
3056            FieldKind::Hidden,
3057        ] {
3058            assert!(!k.confidential(), "{k:?} should not be confidential");
3059        }
3060
3061        // Only a checkbox carries its own label.
3062        assert!(FieldKind::Checkbox.labels_itself());
3063        assert!(!FieldKind::Text.labels_itself());
3064    }
3065
3066    #[test]
3067    fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
3068        let text = Field::new(FieldKind::Text, "title", "Title");
3069        assert!(text.options.is_empty());
3070        assert_eq!(text.placeholder, None);
3071
3072        let sizes = [Choice::plain("small"), Choice::plain("large")];
3073        let select = Field::select("size", "Size", &sizes);
3074        assert_eq!(select.kind, FieldKind::Select);
3075        assert_eq!(select.options.len(), 2);
3076    }
3077
3078    #[test]
3079    fn a_choice_says_what_submits_and_what_is_read_apart() {
3080        // The whole reason it is two strings. `plain` is the case where they
3081        // coincide, and it is a shorthand rather than the general shape.
3082        let plain = Choice::plain("7");
3083        assert_eq!((plain.value, plain.label), ("7", "7"));
3084
3085        let spelled = Choice {
3086            value: "7",
3087            label: "One week",
3088        };
3089        assert_ne!(spelled.value, spelled.label);
3090    }
3091
3092    #[test]
3093    fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
3094        // Both offer a fixed set and both read `options`, so the two
3095        // constructors differ in exactly one thing. That one thing is the
3096        // point: a renderer decides whether the alternatives are readable
3097        // without opening anything, and it can only decide that if the
3098        // description said which question was asked.
3099        let styles = [
3100            Choice {
3101                value: "copy",
3102                label: "Copy samples in",
3103            },
3104            Choice {
3105                value: "reference",
3106                label: "Reference in place",
3107            },
3108        ];
3109        let radio = Field::radio("storage", "Storage style", &styles);
3110        let select = Field::select("storage", "Storage style", &styles);
3111
3112        assert_eq!(radio.kind, FieldKind::Radio);
3113        assert_ne!(radio.kind, select.kind);
3114        assert_eq!(radio.options, select.options);
3115        assert_eq!(
3116            Field {
3117                kind: select.kind,
3118                ..radio
3119            },
3120            select
3121        );
3122    }
3123
3124    #[test]
3125    fn exactly_the_option_taking_kinds_say_so() {
3126        // The renderers branch on this rather than on a list of their own, so
3127        // a kind added without a decision here renders its options nowhere.
3128        assert!(FieldKind::Select.offers_options());
3129        assert!(FieldKind::Radio.offers_options());
3130        for kind in [
3131            FieldKind::Text,
3132            FieldKind::Secret,
3133            FieldKind::Number,
3134            FieldKind::Email,
3135            FieldKind::Url,
3136            FieldKind::Tel,
3137            FieldKind::Textarea,
3138            FieldKind::Checkbox,
3139            FieldKind::Hidden,
3140        ] {
3141            assert!(!kind.offers_options(), "{kind:?} does not offer options");
3142        }
3143    }
3144
3145    #[test]
3146    fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
3147        // The near-miss: each option is labelled beside its own button, so a
3148        // renderer could plausibly read the group as self-labelling and drop
3149        // the question. Checkbox is the only kind that does that.
3150        assert!(!FieldKind::Radio.labels_itself());
3151        assert!(FieldKind::Checkbox.labels_itself());
3152    }
3153
3154    #[test]
3155    fn a_select_with_no_options_is_sayable() {
3156        // An app whose option list has not loaded has exactly this. Making it
3157        // unrepresentable would push the state somewhere less visible, and a
3158        // renderer drawing an empty select reports it on screen.
3159        let loading = Field::select("project", "Project", &[]);
3160        assert!(loading.options.is_empty());
3161    }
3162
3163    #[test]
3164    fn the_description_carries_the_question_and_never_the_answer() {
3165        // The line 0.8.0 drew. Placeholder and options are properties of what
3166        // is being asked; the current value is what came back, and no field
3167        // here holds one.
3168        let f = Field {
3169            placeholder: Some("yyyy-mm-dd"),
3170            ..Field::new(FieldKind::Text, "due", "Due")
3171        };
3172        assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
3173        // A placeholder is not a label, and having one does not excuse the
3174        // field from carrying the other.
3175        assert_eq!(f.label, "Due");
3176    }
3177
3178    #[test]
3179    fn a_field_reports_its_own_error_state() {
3180        let mut f = Field::new(FieldKind::Text, "title", "Title");
3181        assert!(!f.invalid());
3182        f.error = Some("Required");
3183        assert!(f.invalid());
3184    }
3185
3186    #[test]
3187    fn columns_drop_by_priority_and_never_by_position() {
3188        let cols = [
3189            Column {
3190                width: Width::Fill,
3191                priority: Priority::Essential,
3192                ..Column::new("Title")
3193            },
3194            Column {
3195                width: Width::Fixed,
3196                priority: Priority::Secondary,
3197                ..Column::new("Due")
3198            },
3199            Column {
3200                width: Width::Fixed,
3201                priority: Priority::Optional,
3202                ..Column::new("Estimate")
3203            },
3204        ];
3205
3206        // Widest: everything survives.
3207        assert_eq!(
3208            cols.iter()
3209                .filter(|c| c.kept_at(Priority::Optional))
3210                .count(),
3211            3
3212        );
3213        // Narrower: the optional column goes first.
3214        let kept: Vec<_> = cols
3215            .iter()
3216            .filter(|c| c.kept_at(Priority::Secondary))
3217            .map(|c| c.name)
3218            .collect();
3219        assert_eq!(kept, ["Title", "Due"]);
3220        // Narrowest: only what identifies the row.
3221        let kept: Vec<_> = cols
3222            .iter()
3223            .filter(|c| c.kept_at(Priority::Essential))
3224            .map(|c| c.name)
3225            .collect();
3226        assert_eq!(kept, ["Title"]);
3227    }
3228
3229    #[test]
3230    fn inserting_a_column_does_not_move_what_gets_dropped() {
3231        // The bug the ordinal form has and this form cannot: goingson hides
3232        // `nth-child(n+5)` against a seven-column table, so a column inserted
3233        // anywhere to the left silently hides a different one.
3234        let before = [
3235            Column::new("Title"),
3236            Column {
3237                width: Width::Fixed,
3238                priority: Priority::Optional,
3239                ..Column::new("Estimate")
3240            },
3241        ];
3242        let after = [
3243            Column::new("Title"),
3244            Column::new("Project"), // inserted
3245            Column {
3246                width: Width::Fixed,
3247                priority: Priority::Optional,
3248                ..Column::new("Estimate")
3249            },
3250        ];
3251
3252        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
3253            cols.iter()
3254                .filter(|c| !c.kept_at(Priority::Secondary))
3255                .map(|c| c.name)
3256                .collect()
3257        }
3258        assert_eq!(dropped(&before), ["Estimate"]);
3259        assert_eq!(dropped(&after), ["Estimate"]);
3260    }
3261
3262    #[test]
3263    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
3264        // goingson uses the tab group inside the content region rather than
3265        // instead of one, so it is not a third arrangement.
3266        let go = Arrangement::list_detail(true);
3267        let plain = Arrangement::list_detail(false);
3268        assert_ne!(go, plain);
3269        assert_ne!(go, Arrangement::sidebar_content());
3270    }
3271
3272    #[test]
3273    fn a_share_is_a_proportion_and_resolves_the_same_way_everywhere() {
3274        // The point of the member: a terminal reading columns and a webview
3275        // reading a grid honour one fact, so two hosts showing one screen agree
3276        // about its proportions.
3277        assert_eq!(Share::LIST.as_percent(), 40);
3278        assert_eq!(Share::LIST.of(100), 40);
3279        assert_eq!(
3280            Share::SIDEBAR.of(96),
3281            24,
3282            "quasi-tui's 24 columns, said as a quarter"
3283        );
3284    }
3285
3286    #[test]
3287    fn a_region_never_resolves_to_nothing() {
3288        // A region the description named should be visible. A zero-width one
3289        // reads on screen as a region that vanished, which is the hardest kind
3290        // of bug to find from what is drawn.
3291        assert_eq!(Share::percent(5).of(1), 1);
3292        assert_eq!(Share::percent(5).of(0), 1);
3293    }
3294
3295    #[test]
3296    fn a_share_outside_the_range_is_clamped_rather_than_refused() {
3297        assert_eq!(Share::percent(0), Share::percent(5));
3298        assert_eq!(Share::percent(200), Share::percent(95));
3299    }
3300
3301    #[test]
3302    fn the_share_rides_on_the_arrangement_that_knows_which_question_it_is() {
3303        // How much a sidebar takes and how much a list side takes are different
3304        // questions, and this enum is the only thing that knows which is being
3305        // asked.
3306        assert_eq!(Arrangement::sidebar_content().share(), Share::SIDEBAR);
3307        assert_eq!(Arrangement::list_detail(false).share(), Share::LIST);
3308
3309        let narrow = Arrangement::sidebar_content().with_share(Share::percent(20));
3310        assert_eq!(narrow.share(), Share::percent(20));
3311        assert!(matches!(narrow, Arrangement::SidebarContent { .. }));
3312    }
3313
3314    #[test]
3315    fn a_measure_defaults_to_the_one_53_of_69_templates_asked_for() {
3316        // The default is meaningful: a screen nobody said anything about uses
3317        // the window it was given.
3318        assert_eq!(Measure::default(), Measure::Wide);
3319        assert_eq!(Measure::Reading.as_str(), "reading");
3320    }
3321
3322    #[test]
3323    fn readiness_names_the_state_and_not_the_shimmer() {
3324        // Two members and no third. If a skeleton ever appears in this enum,
3325        // the deferral rule has been broken.
3326        assert_ne!(Readiness::Ready, Readiness::Pending);
3327    }
3328}