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//! 0.22.0 finishes [`Image`], which 0.21.0 shipped unable to say how much room
250//! a picture needs. Without that a renderer cannot reserve space, so a picture
251//! occupies nothing until its bytes arrive and then takes its full height at
252//! once. Measured on MNW's landing page: a 478px jump per frame and a
253//! cumulative layout shift of 0.087 for the page.
254//!
255//! - [`Image::intrinsic`], the picture's own dimensions, carried as [`Extent`].
256//!   A fact about the asset rather than a display size, which is what keeps it
257//!   on this side of the deferral rule: 5120x3412 is what the file *is*, and no
258//!   renderer can learn it without fetching the bytes.
259//! - [`Loading`], and the default flips to [`Loading::Eager`]. 0.21.0 emitted
260//!   the webview's `loading="lazy"` for every picture, which read one
261//!   consumer's habit as a rule. Deferring a picture that is on screen at first
262//!   paint saves nothing and makes its shift land later. The carousel is the
263//!   case that proves this cannot be one renderer-wide setting: its first frame
264//!   is on screen and its others are not, in one widget, at one moment.
265//!
266//! 0.23.0 adds [`Showing`], which is three open findings collapsing into one
267//! member. A tab group could not say which tab was open, a carousel could not
268//! say which frame was up, and a disclosure could not say whether its child was
269//! showing. All three are the same missing sentence, and while it was missing a
270//! renderer had two moves: match on a widget name, or draw every child.
271//!
272//! So the widget tier was taking the blame for a gap one level below it. With
273//! this a renderer derives its chrome from the description — labels get a strip,
274//! no labels get previous/position/next — once, for every widget there will ever
275//! be, and [`Region::Widget`]'s name goes back to being app vocabulary a
276//! renderer may decline to know.
277//!
278//! Only the kind lives here. Which child is up, and what each child is called,
279//! sit with whatever holds the regions, the same split [`Selector`] already made
280//! against `Node::Select`.
281//!
282//! 0.27.0 adds [`Region::Group`], which closes a gap this crate had carried
283//! since 0.2.0 without noticing: [`Heading::Section`] is documented as naming a
284//! block within the screen, and there was no block. A section heading is a leaf
285//! beside the things it names, so the description could say a section had
286//! *started* and never that one had ended.
287//!
288//! Found by asking how a screen distinguishes groups of settings by colour, and
289//! the answer turned out to be two findings rather than one. This is the first
290//! and it is the precondition: there is nothing to tint until there is a
291//! container. The second — every renderer already resolves `category.one`
292//! through `category.six` and no description can reach any of them — is filed
293//! and not shipped here.
294//!
295//! What the colour question settled anyway, because it shapes this member: the
296//! group carries no colour and no ordinal. A renderer distinguishing sibling
297//! groups derives the assignment from their order, which is
298//! [`Region::Columns`]' reasoning about counts applied to colour — the children
299//! say, and a value here would be a second source for something the description
300//! already states by containing them.
301//!
302//! 0.28.0 is what audiofiles' forms port found it could not say, three findings
303//! filed against a working conversion rather than guessed at in advance. All
304//! three are about a *question* rather than about a control, which is the line
305//! this crate keeps having to redraw.
306//!
307//! - [`FieldKind::Range`] and [`Field::step`]. A bounded number the user drags
308//!   across, where both ends being on screen is what the question means. The
309//!   reading to resist is that this is [`FieldKind::Number`] with bounds, and it
310//!   is [`FieldKind::Radio`]'s argument again: a validated number can be out of
311//!   range and a slider cannot, so the bounds stop being a rule and become the
312//!   control's extent. [`Field::bounded`] is the check a renderer asks, since a
313//!   range missing an end has nothing to draw.
314//! - [`Choice::unavailable`]. An option that is real, worth showing, and cannot
315//!   be picked yet. Without it an app either drops the option — and the user
316//!   never learns it is there — or hand-rolls the control outside the
317//!   description, which is what audiofiles' instrument panel did: a permanently
318//!   disabled radio plus a hand-written line saying what would enable it.
319//!   `#[non_exhaustive]` arrives on [`Choice`] in the same release, so this is
320//!   the last breaking addition to it.
321//! - Not a member at all: [`Field::placeholder`] on a chooser. It was sayable
322//!   already and no renderer read it, so a select with nothing chosen showed an
323//!   empty box and the instruction lived on a disabled button elsewhere. The
324//!   renderers moved, not the description.
325//!
326//! 0.29.1 adds [`Awaiting`], which is the sentence [`Readiness`] could say about
327//! a region and could not say about a control. A described screen could state
328//! that a list was on its way and could not state that the button just pressed
329//! is doing the thing it was pressed for, so every renderer's in-flight
330//! treatment was the app's to hand-write. The MNW server hand-writes it 57 times
331//! and hand-writes the guard against a second press twice, which is the half
332//! that matters going missing on a codebase that sells things.
333//!
334//! The mark is the fact that something outstanding will complete, once, in
335//! expected finite time. Deliberately not remoteness, since a heavy local query
336//! waits too, and deliberately not slowness, which is a judgement rather than a
337//! property. It carries an optional amount, stated only when the amount is
338//! measured, and it carries no duration at all: a renderer draws what is done
339//! over what there is plus the time so far, and never an estimate of what is
340//! left.
341//!
342//! One mark and two readings, which is what keeps a slow region from being
343//! hand-split into its own route the way MNW's payout summary is: a pressed
344//! control goes busy and locks, a region fed by an awaiting call stands in as
345//! [`Readiness::Pending`] and fills when it lands.
346//!
347//! A patch release for a new member, which is the 0.27.5 precedent rather than a
348//! new rule: nothing existing changed shape, so every consumer already asking
349//! for 0.29 keeps resolving and the suite below this crate does not have to move
350//! for a type only quasi reads. The minor releases above were minor because they
351//! also narrowed something.
352//!
353//! 0.30.0 is two members batched into one release, which is 0.11.0's precedent
354//! and its reasoning: pre-1.0 a minor is breaking, the cascade below this crate
355//! is seven repos, and paying that twice in a week for two unrelated words is
356//! the tax the batching exists to avoid.
357//!
358//! - [`FieldKind::Rich`], a field whose value is markdown source. The editing
359//!   counterpart of prose already carried as markdown, and it is renderable
360//!   everywhere for the reason the carrying is: editing markdown is editing
361//!   text. It buys a renderer permission to offer a preview or a syntax pass and
362//!   buys a host reading the value back the knowledge of what it holds; a
363//!   renderer with neither draws a textarea. It says nothing about when the
364//!   value is saved, because autosave is a clock. Measured against four MNW
365//!   section editors that are one shape written four times.
366//!   [`FieldKind::multiline`] arrives with it, since the pair is now two members
367//!   every renderer has to ask about.
368//! - [`Facet`], [`Selecting`], [`FacetValue`] and [`Standing`]: a named
369//!   dimension a set is narrowed by. MNW's discover page filters six ways
370//!   through six mechanisms, and its filter rows carry a tick box *and* a
371//!   chevron only because a tag's selection and a tag's browse position were
372//!   held separately. One word covers all six, and [`Selecting::Subtree`] is the
373//!   member that made it an enum rather than a bool: a tree's selection is
374//!   branches taken and branches pruned, which no flat mode can express, and
375//!   making one gesture do browsing and filtering together is what lets the
376//!   second mechanism go. [`Standing`] has four members rather than a bool for
377//!   the tree's sake — a value in force because an ancestor is, is not a value
378//!   somebody picked. [`FacetValue`] splits an identifier from a label for
379//!   [`Choice`]'s reason and one of its own: two leaves under different parents
380//!   are legitimately both called "Ambient", and the path is what tells them
381//!   apart and what nearest-ancestor-wins resolves over. Deliberately wider than
382//!   that one page: audiofiles' library browser and goingson's filters are the
383//!   same shape.
384//!
385//! 0.39.0 gives an *option* its second line. [`Choice::detail`] is the sentence
386//! that says what picking one means, and it is one member and not two. Measured
387//! 2026-08-29 (`5e21dcfc`), off the MNW server's un-ported markup.
388//!
389//! - **Six sites, and four of them had already folded it into the label.**
390//!   `<strong>Public</strong>: Anyone can see this repository` in git settings,
391//!   the same shape in the project-basics AI tier and the cart's currency
392//!   conversion, `Mislabeled (wrong AI tier or category)` in the report modal.
393//!   The item-type and item-pricing wizards give it its own span. The described
394//!   screens fold it in miniature: `Every 15 minutes (recommended)`. One fact,
395//!   six spellings, and the folding is what says the member was missing.
396//! - **It is not a price**, and the count is what decided that rather than
397//!   taste. The site that asked carries a name, a price and a description; the
398//!   tree's other three priced tier lists are not option lists at all — each
399//!   card carries its own submit, so each is a region with a heading, a fact
400//!   and an act and is sayable today. A price member would have one consumer
401//!   and would mean growing a money type this crate does not have.
402//! - **Where it is drawn is [`unavailable`](Choice::unavailable)'s question met
403//!   a third time**, and it takes the same answer: its own element in a radio
404//!   group, run into the option's own text in a `<select>`, a row of its own on
405//!   a terminal. A rule the crate had already paid for twice is the cheapest
406//!   evidence that one member is the right size.
407//! - **This does not reopen 0.35.0.** That release ruled [`Candidate`] a type
408//!   of its own rather than a `Choice` with a second line, and it stays one:
409//!   what separates them is that an option is picked out of a set the user can
410//!   see whole and a candidate is offered out of one nobody can see. The
411//!   argument 0.35.0 made against a member here — that it would land on every
412//!   option list including the ones with nowhere to draw it — is answered by
413//!   the two sentences above: it lands as `None` on the ones that do not ask,
414//!   and the one host with nowhere to draw it already had a rule.
415//!
416//! 0.38.0 describes the theme picker. [`FieldKind::Theme`], [`ThemeChoice`],
417//! [`ThemeVariant`], [`Contrast`], [`Field::themes`] and [`Field::follows`] are
418//! one screen's control named as furniture. Ruled by Max 2026-08-28
419//! (`70028e00`), against the grouped option list that was the obvious answer.
420//!
421//! - **The measurement is what rejected `Choice::group`.** `optgroup` appears
422//!   at exactly one live site in the tree, in the one app not yet ported, and
423//!   the non-theme grouping count is zero. Two apps' grouped pickers were
424//!   deleted by their ports and both described replacements dropped the
425//!   grouping on purpose. So the thing that recurs is not option lists that
426//!   group; it is this picker, hand-written three times.
427//! - **Two of the four facts cannot come from an app.** A theme's group and its
428//!   measured contrast tier come off the resolved theme, so the layer that
429//!   loaded it is the only party holding them. `Choice::new(id, "{name}
430//!   ({variant})")` is what all three apps wrote, and it turns structure into
431//!   prose and drops the tier entirely.
432//! - **The order is the grouping**, rather than a returned list of groups. A
433//!   renderer that draws headings walks the run of one variant; one that cannot
434//!   still gets the useful order, and neither shape is made to flatten the
435//!   other's.
436//! - **[`ThemeVariant`] is spelled twice on purpose.** This crate takes no
437//!   dependencies, so it cannot name `makeover::Variant`, and a renderer that
438//!   groups needs the groups as values. The adopter converts, in a three-arm
439//!   match.
440//! - **The cost is stated rather than found later.** This is the first member
441//!   here that names a subject instead of a shape of answer. It stays narrow: a
442//!   theme picker, not a general host-resolved list. A second such list is when
443//!   the generalisation gets measured.
444//!
445//! 0.35.0 gives a suggestion its second line. [`Candidate`] is the entry in a
446//! field's suggestion list: a value, a label, and the [`detail`] that orients
447//! it. Ruled by Max 2026-08-21 (`1fcf2e9b`) after the combobox member shipped
448//! and was then held against the two sites it was designed from, which is an
449//! order worth not repeating.
450//!
451//! - **A candidate is not a [`Choice`], and the difference is in the reading
452//!   rather than the writing.** Both submit one string and read as another. An
453//!   option is picked out of a set the user can see whole; a candidate is
454//!   offered out of a set nobody can see, so it has to say what tells it from
455//!   its neighbours. Both measured sites draw that second string today, by
456//!   hand, in a second span.
457//! - **It is its own type rather than a member on [`Choice`].** `Choice` is the
458//!   most-consumed struct in the vocabulary and the member would have landed on
459//!   every option list in the tree the day it shipped, including the ones with
460//!   nowhere to draw it.
461//! - **[`Candidate`] is `#[non_exhaustive]` from birth**, which is the whole of
462//!   what 0.28.0 cost and is not being paid twice.
463//! - No `unavailable`. A suggestion that cannot be picked is a row a route
464//!   should not have offered.
465//!
466//! [`detail`]: Candidate::detail
467//!
468//! 0.34.0 gives an interval a description. [`FieldKind::Interval`] and
469//! [`Field::upper_name`] say that two values are one question with two ends.
470//! Ruled by Max 2026-08-21 against audiofiles' six filter axes and the MNW
471//! server's price pair, which is HTML saying the grouping in an ARIA
472//! `role="group"` and nowhere else.
473//!
474//! - **The ends constrain each other, and nothing else in the vocabulary could
475//!   say so.** Two [`FieldKind::Number`] fields are two questions: a renderer
476//!   draws two labels with no relationship, and [`Field::error`] attaches to one
477//!   side of a fault that belongs to both.
478//! - **It is not [`FieldKind::Range`]**, which is the reading to resist and the
479//!   same resistance `Range` needed against `Number`. A range is one value
480//!   inside an extent; this is two, and the extent is a bound on each rather
481//!   than the question's meaning.
482//! - **Both names are stated rather than derived.** Measured the same day, the
483//!   two sites disagree about affix order -- `bpm_min`/`bpm_max` against
484//!   `min_price`/`max_price` -- so any rule renames one of them. One member
485//!   instead of a naming convention this crate would own forever, and which
486//!   member a name sits in is what says which end it is.
487//! - The crossing rule is not enforced, exactly as [`Field::min`] is not. What
488//!   the description buys is one place to report the fault rather than two.
489//!
490//! [`Field::upper_name`] is a member on a struct that is not
491//! `#[non_exhaustive]`, so this is a formal break for crates.io and zero
492//! call-site edits in the tree: every literal builds on a constructor.
493//!
494//! 0.33.0 gives a number its unit. [`Field::unit`] carries what the value is
495//! measured in, and [`FieldKind::measurable`] says which kinds read it. Decided
496//! by Max 2026-08-21 (`32215e21`) against eight sites across four audiofiles
497//! files that had each independently put the unit in parentheses at the end of
498//! the label -- three of them written while the gap was a known open question.
499//!
500//! - **A unit is a fact about the value, not part of the question's name.** The
501//!   two readings come apart the moment anything reads a field back rather than
502//!   drawing it, which is the argument that decided it.
503//! - **The convention it replaces froze the worst placement.** A label is the
504//!   sentence above the control, so unit-in-label was the same answer on every
505//!   host -- including the host that had somewhere better, since egui's slider
506//!   already draws a suffix beside the readout, which is what these controls did
507//!   before they were described.
508//! - A string rather than a closed family, which is [`Curve`]'s argument
509//!   inverted and correctly so: a curve is a mapping this crate computes, and a
510//!   unit is a symbol it only carries. The measured set is `GiB`, `dBFS`, `s`
511//!   and `ms`, and this crate does not know what the next consumer measures in.
512//!
513//! Additive: absent is what every field meant before.
514//!
515//! 0.32.0 is the slider's real shape. **The data of a slider is a fraction and
516//! a function taking numbers to numbers** (Max, 2026-08-21), so [`Curve`]
517//! arrives and [`Field::curve`] with it. [`Field::min`] and [`Field::max`] were
518//! never the control's extent: a slider's extent is always 0 to 1, and the
519//! bounds are `f(0)` and `f(1)`. Linear is the constant-slope case, which is
520//! why the mapping was invisible — under it the extent and the bounds coincide
521//! numerically — and why four renderers each hard-coded it without anyone
522//! deciding to.
523//!
524//! - It is not a scale flag on a range. The question this replaced asked
525//!   whether to name a decoration; what was unnamed is half of what a slider
526//!   *is*, which is why the member is a mapping and not an adjective.
527//! - **The step spacing rides on the curve.** Max, in the same breath: if the
528//!   family is prescriptive anyway, the granularity belongs in it. On a slider
529//!   the two are one decision, and holding them apart is what let a 0-to-1
530//!   threshold ship as a two-position control. [`Field::step`] narrows to the
531//!   *typed* kinds, where there is no mapping to decide with.
532//! - A closed family rather than `fn(f64) -> f64`, which is the literal reading
533//!   and does not cross the description boundary: a fn pointer cannot be
534//!   emitted into a browser and cannot be compared or hashed meaningfully,
535//!   which [`Field`] needs. Nothing measured wants an arbitrary function — one
536//!   non-linear shape across five controls, and no second shape.
537//! - The mapping computes here rather than in each renderer
538//!   ([`Curve::value_at`], [`Curve::position_of`]), so a terminal's bar, an
539//!   egui slider and a browser's input cannot disagree about where a value
540//!   sits. This crate otherwise describes rather than computes; four copies of
541//!   two formulas is the cost of holding that line here.
542//!
543//! Additive: [`Curve::Linear`] with no step is what every range meant before,
544//! so no existing site changes meaning. Consumers: audiofiles' ADSR envelope
545//! (three logarithmic times) and its storage cap picker.
546//!
547//! 0.31.0 finishes the file field. [`FieldKind::File`] arrived at 0.11.0
548//! carrying neither an accepted-types list nor a multiplicity flag, and said so
549//! in its own doc: `accept` appeared at zero sites in either app, and a member
550//! added for a case nobody has is a member designed against nothing. That count
551//! was taken over goingson and Balanced Breakfast, and the MNW server is a third
552//! consumer with 14 `accept` lists across 10 templates and 4 of its 16 file
553//! inputs marked `multiple`. The reasoning was right and the measurement went
554//! stale, so [`Field::accept`] and [`Field::multiple`] arrive now.
555//!
556//! - [`Accepted`] is an enum rather than the comma-joined string the templates
557//!   hold, because the list is read twice and only one of the readings is
558//!   filtering. The other is which disclosure to offer — a preview, a duration,
559//!   a waveform — and a renderer deciding that from raw strings is three
560//!   renderers each writing a media-type parser. [`Accepted::family`] answers it
561//!   once. All three shapes are in the measured sites and none can be dropped:
562//!   `image/*` is a [`Family`], `image/jpeg` and `text/csv` are a
563//!   [`Type`](Accepted::Type), and `.zip`, `.tar.gz` and `.clap` are a
564//!   [`Suffix`](Accepted::Suffix). One site carries `.csv,text/csv`, which is
565//!   both in one list.
566//! - A suffix carries no family and this crate will not infer one. `.mp3` is
567//!   audio in fact, and a table here saying so is a mapping that rots in a
568//!   published crate and is wrong for the first container format someone hands
569//!   it. A call site that wants the disclosure writes the family or the media
570//!   type, which is what the sites offering previews already do.
571//! - There is one upload shape, not one per type. What a media upload shows
572//!   beyond a plain one is disclosure layered on this shape, which is why the
573//!   accept list is load-bearing beyond validation and why nothing here names a
574//!   media upload as its own kind.
575//! - Progress is not a member and needs none. An upload in flight is a control
576//!   in flight with a number attached, so it is [`Awaiting`] with the file's
577//!   length as its [`amount`](Awaiting::amount) — the case that type's own doc
578//!   names. Where the bytes go is an address, and this crate holds none; that is
579//!   the router's [`Action`], which the field already points at when it writes
580//!   on its own.
581//!
582//! # Reach, focus and the focus ring
583//!
584//! Three terms, and no others, for what 0.19.0 moved out of the description.
585//! **Reach** is which things can take focus and in what order; a browser reads
586//! it off the document, a TUI derives it from draw order, egui from its own id
587//! stack. **Focus** is which reached thing has the keyboard right now: the
588//! renderer's, live, never described and never round-tripped through a
589//! description. The **focus ring** is the visible cue; the token (`focus-ring`,
590//! derived by `makeover` from the action colour) is the one shared artifact and
591//! the drawing is the renderer's. Retired as names for any of this: "focus
592//! stroke", "focus cue", "wants focus". "Caret" is a different thing — the text
593//! cursor inside a field — and keeps its name.
594//!
595//! # The three tones, and what a colour claims
596//!
597//! One rule, settled 2026-08-16, for how colour says whether a thing can be
598//! used. Every renderer answers to it, and it is stated here because the
599//! description is what names the intents.
600//!
601//! | the thing | intent |
602//! |-----------|--------|
603//! | active, emphasised, the thing itself | `content` |
604//! | inactive but usable: it still answers a press | `content-secondary` |
605//! | inert: disabled, or not a control at all | `content-muted` |
606//!
607//! `content-muted` is the one with a claim in it. [`State::Disabled`] resolves
608//! to it, so a live control wearing it is telling the user it will not answer —
609//! and being wrong about that is worse than being quiet, because the user's
610//! response is to stop trying. A sortable column heading that was never sorted,
611//! and every unchosen option in a radio group, both read as dead lists that way;
612//! those are the two this rule was written out of. What is legitimately muted is
613//! a caption, a hint, a placeholder, a meter's reading, an axis label: text that
614//! was never going to answer anything.
615//!
616//! The three are one ramp and not three colours. `makeover`'s `Emphasis` derives
617//! the quieter two from the ink, so "one step back" means the same distance in
618//! every theme and a renderer cannot land between them by picking its own.
619//!
620//! # First paint is final paint
621//!
622//! One rule, settled 2026-08-16. Nothing may change size or position after it is
623//! first drawn, and nothing may stand in for content that has not arrived yet.
624//! Both halves are absolute.
625//!
626//! It is stated here, rather than left to each renderer, because a renderer can
627//! only reserve space the description gave it enough to size. A member whose
628//! size depends on its content therefore owes whatever makes it sizeable while
629//! the content is still absent, and that is the second admission test for a new
630//! member: not only does it compose something this crate already names, it can
631//! be laid out before it is filled.
632//!
633//! The mechanism is a reservation, and [`Sort`]'s caret is the worked example.
634//! The caret is drawn into a box its own width whether or not the column is
635//! sorted, so pressing a heading cannot reflow the row it sits in. The box names
636//! no magnitude, which is what keeps it out of `makeover-geometry`'s territory.
637//! Reserve from what is known; never discover geometry from what has not
638//! arrived.
639//!
640//! The trap is an `Option` that means "not yet". [`Readiness::Pending`] is the
641//! honest way to say a region is still waiting. An optional *measurement* is
642//! not: a count that shows up later widens the text that prints it and moves
643//! everything beside it, which is the reflow this rule exists to forbid. So an
644//! `Option` on a measurement means the host will never know it — a property of
645//! the query, fixed for the life of the screen — and a renderer sizes for the
646//! answer it was handed rather than for the one it hopes is coming.
647//!
648//! # Any width, one answer
649//!
650//! The sibling of the rule above, and settled the same day. That one is
651//! independence from *when*; this one is independence from *how you got here*.
652//!
653//! A rendering is a pure function of the description and the viewport. The same
654//! description at the same width is the same output, whatever widths came
655//! before it. No renderer may carry geometry across frames, and none may narrow
656//! by counting.
657//!
658//! The failure this forbids is ordinary enough to be the default everywhere
659//! else: a page that hides its sidebar below some width, remembers that it hid
660//! it, and does not bring it back the same way. Layout there is a function of
661//! `(width, history)`, so dragging a window to 900 wide is a different screen
662//! depending on whether you came from 1400 or from 600. Nobody chose that; it
663//! is what measuring and remembering produce.
664//!
665//! The mechanism is [`Width`] for what grows and [`Priority`] for what drops.
666//! Both are declared, both are read off the description, and neither needs a
667//! measurement. A renderer narrows by raising a cutoff over a total order,
668//! never by counting what fits and stopping — `makeover-tui`'s table states
669//! that as its own rule and tests it, and `makeover-webview` reaches the same
670//! place with `@media` and `display: none`, which is path-independent by
671//! construction because CSS has nowhere to keep the previous width.
672//!
673//! Two things follow for anything new. A member that would need last frame's
674//! size to lay out this frame is refused, the same way a member that cannot be
675//! sized before it is filled is refused. And a fact about what disappears
676//! belongs in the description, because a host that has to infer it can only
677//! infer it from a measurement.
678//!
679//! # Where the description stops
680//!
681//! The rule is that a member is added when an app needs a fact the vocabulary
682//! cannot state, and refused when what it wants is presentation it should be
683//! asking a renderer for. That is the whole test. It is not a quota, and the
684//! goal is every screen described.
685//!
686//! ## What the timeline refusal got wrong, 2026-08-15
687//!
688//! This section used to read "a day-plan timeline, a kanban board and a
689//! calendar are not describable here and will not become describable", and it
690//! propagated: 12 files across three apps, three libraries and the design wiki
691//! cited it, including audiofiles and the MNW server, neither of which has a
692//! timeline. It is withdrawn, and [`Track`] is the member it was refusing.
693//!
694//! The error was pricing. The argument assumed a timeline needs a component
695//! library's worth of vocabulary, and nobody measured it. Held against
696//! goingson's `day-planning-render.js`, the members it actually needed and
697//! could not get were two integers: where a thing starts, and how long it
698//! lasts. Labels, gridlines, item bodies and tones were all furniture this
699//! crate already named. A refusal that expensive should have carried a
700//! measurement, and did not.
701//!
702//! The reasoning underneath it survives and is still the test: slot heights,
703//! gridline colour, how overlapping things stack, which hour scrolls into view.
704//! Those are presentation, they stay the renderer's, and [`Track`] carries none
705//! of them. What changed is the conclusion, not the principle.
706//!
707//! ## The other two, measured 2026-08-15
708//!
709//! The same sentence refused a kanban board and a calendar. Both were counted
710//! the way the timeline should have been, and neither came out where the
711//! refusal put it.
712//!
713//! **Kanban: one member, and it is [`Region::Columns`].** Held against
714//! goingson's `tasks-kanban.js`, every card fact was already sayable — title,
715//! project, due date, the blocked and unblocks badges, subtask progress, the
716//! open action and the context menu are `Row`'s existing parts. A column is a
717//! heading, a count and a list. What nothing could say was that the columns are
718//! *peers*: [`Arrangement`] offers list-detail and sidebar-content, and a board
719//! described as either is a lie about the screen. Dragging a card between
720//! columns never entered into it — a drop's effect is "set status", a discrete
721//! action `Row`'s menu already carries, and the drag itself is affordance.
722//!
723//! **Calendar: no members, no consumer, and a sharper reason (Max,
724//! 2026-08-15).** The month grid's primacy in calendar apps is an artifact of
725//! paper: paper cannot be queried, so it has to show every day at once as a
726//! fallback index. Routes, search and ranking do that job better, which is the
727//! argument `events-calendar.js` already lost to a segmented list on
728//! 2026-08-11.
729//!
730//! Three jobs survive that reasoning, and only one of them needs a grid:
731//!
732//! 1. **Spans across days** — a stretch of leave, a trip, a sprint. You cannot
733//!    see "away the 3rd to the 17th" in a list without diffing dates. This is
734//!    [`Track`] with [`Unit::Days`], not a calendar, and
735//!    [`Track::days`] is it.
736//! 2. **Density at a glance** — which weeks were heavy. That is a heatmap, and
737//!    goingson describes both of its heatmaps as lists already.
738//! 3. **Weekday periodicity** — "every other Tuesday", "the 15th is a
739//!    Saturday". This is the only job that needs the seven-column wrap, because
740//!    alignment is the whole of what makes it visible.
741//!
742//! So the open question is not "is a calendar describable" but "is job 3 worth
743//! a member", and nothing in the tree asks for job 3 yet. GoingsOn
744//! quasicoherent `4a1237b6`.
745//!
746//! A month grid renders today as a
747//! [`Table`](crate::Column): seven weekday columns, weeks as rows, blanks for
748//! the offset. goingson's monthly review reached this conclusion before this
749//! note did and describes its month as a list of days that had something on
750//! them, marking today with an ordinary badge. What the tree actually contains
751//! is two completion heatmaps — one scalar per day — and no calendar at all:
752//! `events-calendar.js` was deleted 2026-08-11 in favour of a segmented list,
753//! and no MNW template mentions one. So the refusal was defending a screen
754//! nobody has. If one is built, measure again; the facts already fit and only
755//! the grid's shape would be in question.
756//!
757//! The pattern worth keeping from all three: one sentence refused three things
758//! for one reason, and the reason was wrong three different ways. Count the
759//! members.
760//!
761//! [`Region::Bespoke`] remains for the genuinely app-owned, and its
762//! justification does not depend on the withdrawn claim. The
763//! description names the *place* and the app owns the contents, so a screen
764//! containing a timeline is still a whole screen and still routable. Without
765//! it, the four goingson screens that make the app worth using would need a
766//! second, undescribed path beside the router, and two paths is how a
767//! vocabulary starts drifting from its app again.
768//!
769//! [`Region::Widget`] sits between that limit and the primitives, and it does
770//! not move the limit. A widget is an assembly of members this crate *already*
771//! has, under a name a renderer may or may not recognise. Anything that needs a
772//! member the vocabulary does not have is still a finding about the vocabulary
773//! or still bespoke; naming an assembly buys no new expressive power, which is
774//! exactly why it is safe to let the set grow outside this crate.
775
776#![forbid(unsafe_code)]
777
778/// A colour intent this crate refers to but never resolves.
779///
780/// The string is the token name `makeover` publishes, so a renderer can look
781/// it up without this crate knowing what colour came back.
782pub trait Intent {
783    /// The `makeover` intent token this resolves against.
784    fn token(self) -> &'static str;
785}
786
787/// Which way the light falls across a two-tone edge.
788///
789/// The whole content of a bevel, once colour and thickness are deferred. The
790/// light is always assumed to come from the top left: every consumer measured
791/// agreed on that and none of them ever varied it, so it is an invariant here
792/// rather than a parameter.
793///
794/// # The two corners that belong to both edges
795///
796/// Top-right and bottom-left are where the lit run meets the shaded one, and
797/// the description's claim is that they belong to *both*. How a renderer says
798/// that is its own business, because the answer is bounded by resolution and
799/// not by taste:
800///
801/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
802///   to one tone thickens that edge by a cell and reads as one run overrunning
803///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
804///   splits it and recovers real information. Its box-drawing fallback cannot:
805///   a single stroke has no half to give, so there both corners go to dark.
806/// - A pixel bevel is a one-point stroke by default, which makes the corner a
807///   one-point square. There is nothing to divide — a diagonal seam across one
808///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
809///   already produces. So `makeover-immediate` mitres and is *not* diverging;
810///   it is the same rule at a resolution where the split degenerates.
811///
812/// Stated here so the difference reads as a decision rather than as drift. A
813/// renderer with room to divide the corner should; one without should mitre or
814/// pick the shaded tone, and neither is a bug.
815#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
816pub enum Bevel {
817    /// Lit from the top left: light on top and left, dark on bottom and right.
818    Raised,
819    /// The same edge inverted, which is also the pressed state of anything
820    /// that draws itself [`Bevel::Raised`].
821    Inset,
822}
823
824impl Bevel {
825    /// The edge intents, as `(top_left, bottom_right)`.
826    ///
827    /// Split out from any painting because the inversion *is* the idea, and
828    /// it is the one part every renderer implements identically.
829    #[must_use]
830    pub const fn edges(self) -> (Edge, Edge) {
831        match self {
832            Self::Raised => (Edge::Light, Edge::Dark),
833            Self::Inset => (Edge::Dark, Edge::Light),
834        }
835    }
836
837    /// Pressing inverts. A raised control reads as inset while held.
838    ///
839    /// Stated here rather than left to each consumer because a cascade can
840    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
841    /// resolves this per call site, eighteen times.
842    #[must_use]
843    pub const fn pressed(self) -> Self {
844        match self {
845            Self::Raised => Self::Inset,
846            Self::Inset => Self::Raised,
847        }
848    }
849}
850
851/// One side of a bevel, named by the intent it takes.
852#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
853pub enum Edge {
854    /// The lit side.
855    Light,
856    /// The shadowed side.
857    Dark,
858}
859
860impl Intent for Edge {
861    fn token(self) -> &'static str {
862        match self {
863            Self::Light => "bevel-light",
864            Self::Dark => "bevel-dark",
865        }
866    }
867}
868
869/// A surface intent a region is filled with.
870///
871/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
872/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
873/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
874/// `makeover-immediate` at compile time and left neither able to move until
875/// both published. The vocabulary exists to grow and the renderers exist to
876/// disagree about how much of it they answer, so growth must not be a
877/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
878/// resolved through a fallible lookup, and a missing intent is answered with
879/// structure rather than with a substituted colour.
880///
881/// [`Sunken`]: Fill::Sunken
882#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
883#[non_exhaustive]
884pub enum Fill {
885    /// The page behind everything.
886    Page,
887    /// A surface lifted off the page: cards, controls, menus, toasts.
888    Raised,
889    /// A surface floating above the page rather than resting on it.
890    Overlay,
891    /// The inside of a well.
892    Well,
893    /// A surface set back from the one it sits on, by colour and nothing else.
894    ///
895    /// Not a well. A well is a hole with an edge, and the two are authored in
896    /// opposite directions: `makeover` derives `surface-well` by inverting
897    /// against the theme's own content colour, while `surface-sunken` is
898    /// authored and free to sit darker than raised (goingson's does). Naming
899    /// only the well left the recessed-with-no-edge surface unsayable, which is
900    /// what an unchosen tab is: it recedes so the chosen one can come forward,
901    /// and it carries no bevel of its own.
902    ///
903    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
904    /// and could not delete the line because no member described it.
905    Sunken,
906}
907
908// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
909// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
910// had something to paint. makeover-tui found that wrong within a day: page is
911// the surface a well is usually cut into, so on a terminal that substitution
912// produces exactly the invisibility it was meant to prevent, and the right
913// answer there is a drawn edge rather than a different colour.
914//
915// Substituting one intent for another is renderer policy. The description says
916// what the region is and stops.
917
918impl Intent for Fill {
919    fn token(self) -> &'static str {
920        match self {
921            Self::Page => "surface-page",
922            Self::Raised => "surface-raised",
923            Self::Overlay => "surface-overlay",
924            Self::Well => "surface-well",
925            Self::Sunken => "surface-sunken",
926        }
927    }
928}
929
930/// How a region sits relative to the surface behind it.
931///
932/// Fill and bevel are named together because naming them apart is what let
933/// them disagree. Every consumer measured had at least one region carrying a
934/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
935/// and recorded the bug in its doc comment, and Balanced Breakfast still had
936/// twelve of them a year later. A single name for the pair makes that
937/// unrepresentable.
938/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
939/// release: a depth this renderer has no drawing for should cost it a
940/// wildcard arm, not a compile error and a wait on someone else's publish.
941#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
942#[non_exhaustive]
943pub enum Depth {
944    /// Level with its surroundings. No edge.
945    Flat,
946    /// A card laid on the panel it sits in.
947    Raised,
948    /// A hole in the panel, with content down inside it. For anything the
949    /// user looks *into*: a table body, a tag tree, a text field.
950    Well,
951    /// Set back from what it sits on, by colour alone. No edge.
952    ///
953    /// The one member carrying a fill without a bevel, so a renderer cannot
954    /// assume the two arrive together. That is deliberate and it is still the
955    /// pairing rule: both halves come off the same `Depth`, so they cannot
956    /// disagree, and here one half is legitimately absent.
957    ///
958    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
959    /// Recessed and level-with are different claims, and only one of them
960    /// needs a colour.
961    Sunken,
962    /// A surface sitting *over* the page rather than in it. A modal, a popover,
963    /// a menu.
964    ///
965    /// Takes elevation and no bevel: a surface overlaying the page is lifted
966    /// off it, and a surface in the page is cut into it. That is the same
967    /// pairing rule the rest of the enum holds, applied to the one case where
968    /// the separation is not an edge at all — the lift and the scrim behind it
969    /// are already saying where the surface is.
970    ///
971    /// Every renderer had the surface before it had this variant.
972    /// `makeover-tui` carries `Palette::overlay`, `makeover-immediate` gained
973    /// `Palette::elevation` at 0.10.0, and `makeover-webview` emits
974    /// `--elevation-overlay`. What was missing was the route from a description
975    /// to any of them, which is why this is one variant rather than a feature.
976    Overlay,
977}
978
979impl Depth {
980    /// The edge this depth is drawn with, if it has one.
981    #[must_use]
982    pub const fn bevel(self) -> Option<Bevel> {
983        match self {
984            // Sunken joins Flat here, for the opposite reason: Flat has no edge
985            // because nothing separates it from its surroundings, and Sunken has
986            // none because its colour is already doing the separating.
987            Self::Flat | Self::Sunken => None,
988            // A third reason to have no edge, which is why it gets its own arm
989            // rather than joining the two above: an overlay is separated by the
990            // lift and by the scrim behind it, so an edge would be a second
991            // answer to a question already answered.
992            Self::Overlay => None,
993            Self::Raised => Some(Bevel::Raised),
994            Self::Well => Some(Bevel::Inset),
995        }
996    }
997
998    /// The surface this depth is filled with.
999    ///
1000    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
1001    /// which is the difference between level-with and painted-the-same-colour.
1002    #[must_use]
1003    pub const fn fill(self) -> Option<Fill> {
1004        match self {
1005            Self::Flat => None,
1006            Self::Raised => Some(Fill::Raised),
1007            Self::Well => Some(Fill::Well),
1008            Self::Sunken => Some(Fill::Sunken),
1009            Self::Overlay => Some(Fill::Overlay),
1010        }
1011    }
1012
1013    /// Pressing a raised region reads as a well, and nothing else moves.
1014    ///
1015    /// [`Depth::Overlay`] is untouched along with the rest: an overlay is a
1016    /// surface, not a control, so there is nothing there to press.
1017    #[must_use]
1018    pub const fn pressed(self) -> Self {
1019        match self {
1020            Self::Raised => Self::Well,
1021            other => other,
1022        }
1023    }
1024}
1025
1026/// An interaction state a region can be in, beside whatever [`Depth`] it is.
1027///
1028/// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
1029/// and a disabled field is still a [`Depth::Well`], so folding either member
1030/// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
1031/// something that is not a depth, and would leave disabled-button and
1032/// disabled-field sharing one variant that cannot tell them apart.
1033///
1034/// # Why hover and pressed are not members
1035///
1036/// The line is whether every renderer has the state to express, not whether CSS
1037/// does. Hover is renderer policy and `makeover-webview` says so in its own
1038/// header: a terminal and an immediate-mode painter have no pointer hovering
1039/// over anything, and pressed already arrives through [`Bevel::pressed`] and
1040/// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
1041/// rather than a separate condition.
1042///
1043/// Focus and disabled are different in kind. A TUI has a focused widget and a
1044/// greyed-out one; so does egui. Both were unsayable here, so all three webview
1045/// consumers supplied them from outside the primitive by out-specifying rules
1046/// they did not own: goingson alone carries 19 of them, and the MNW server
1047/// another 21. That is the divergence this crate exists to end, arriving one
1048/// layer down.
1049///
1050/// # The principle this encodes
1051///
1052/// A primitive owns every state it implies. A renderer that emits a hover rule
1053/// for a thing owes disabled and the capability answer for that same thing,
1054/// because anything less exports the completion work to N consumers who will
1055/// each do it differently.
1056///
1057/// Focus is not on that list and was removed from this axis in 0.19.0. It is
1058/// the renderer's, decided after the description; see the crate header, "Reach,
1059/// focus and the focus ring", for the three terms and who owns each.
1060///
1061/// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
1062/// must not be a lockstep event across the three renderers.
1063#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1064#[non_exhaustive]
1065pub enum State {
1066    /// Present, visible, and not answering.
1067    ///
1068    /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
1069    /// control keeps the surface it always had and stops responding, so what
1070    /// changes is its content and its interactivity rather than what it is.
1071    Disabled,
1072}
1073
1074impl State {
1075    /// Whether a region in this state stops answering the pointer.
1076    ///
1077    /// Stated in the description rather than left to each renderer, on the same
1078    /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
1079    /// immediate-mode renderer resolves it per call site, so leaving it unsaid
1080    /// means resolving it once per consumer and disagreeing.
1081    #[must_use]
1082    pub const fn suppresses_interaction(self) -> bool {
1083        // A match rather than a bare `true`, so a member added to this
1084        // `#[non_exhaustive]` axis has to answer the question rather than
1085        // inheriting an answer.
1086        match self {
1087            Self::Disabled => true,
1088        }
1089    }
1090}
1091
1092impl Intent for State {
1093    fn token(self) -> &'static str {
1094        match self {
1095            // Reusing the muted content intent rather than minting a
1096            // `disabled` colour. Disabled is a reduction and not a status, and
1097            // `makeover-webview`'s progress rules already record the reading
1098            // that `content-muted` is what disabled looks like.
1099            Self::Disabled => "content-muted",
1100        }
1101    }
1102}
1103
1104/// What a region is saying, when it is saying something.
1105///
1106/// The one intent family shared by badges, notices and nothing else. Kept
1107/// separate from [`Fill`] because a surface is where a thing sits and a tone is
1108/// what it means, and the three apps agree on the four statuses:
1109/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
1110/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
1111/// `.toast.error` in Balanced Breakfast.
1112///
1113/// The per-tag palette (`category-one` through `category-six`) is deliberately
1114/// not here. Which colour a *particular* tag takes is app domain, and both
1115/// webview apps already carry it as a `data-color` attribute.
1116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1117pub enum Tone {
1118    /// No status.
1119    ///
1120    /// Ordinary content, at full weight. It does not also mean muted: a
1121    /// badge reads quiet because [`Token::Badge`] answers no click, which is
1122    /// the renderer's knowledge and not this axis's. A renderer wanting a
1123    /// muted badge reaches for [`Token::interactive`] itself rather than
1124    /// expecting `Neutral` to have muted it.
1125    Neutral,
1126    /// Something worth knowing and nothing to do about it.
1127    Info,
1128    /// Something finished and it worked.
1129    Success,
1130    /// Something the user should look at before continuing.
1131    Warning,
1132    /// Something broken, or something about to be destroyed.
1133    Danger,
1134}
1135
1136impl Intent for Tone {
1137    fn token(self) -> &'static str {
1138        match self {
1139            // Neutral has no status token of its own, so it takes the plain
1140            // content intent. It used to answer `content-muted`, which read
1141            // "no status" as "de-emphasised" and muted every figure value in
1142            // the webview. Muting is a renderer's call about a particular
1143            // token, not something the status axis knows.
1144            Self::Neutral => "content",
1145            Self::Info => "info",
1146            Self::Success => "success",
1147            Self::Warning => "warning",
1148            Self::Danger => "danger",
1149        }
1150    }
1151}
1152
1153/// A small labelled thing that sits inside something else.
1154///
1155/// Two members, because the three apps drew three taxonomies and only one line
1156/// runs through all of them: does it answer a click. audiofiles has
1157/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
1158/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
1159/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
1160/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
1161/// to decide which of the two it always was.
1162///
1163/// The evidence that a chip is a real concept rather than a badge with a
1164/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
1165/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
1166/// holds itself down", which is exactly what [`Depth::pressed`] already says.
1167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1168pub enum Token {
1169    /// Non-interactive status or count. Answers no click.
1170    Badge,
1171    /// An interactive or removable token. Answers a click, and latches if it
1172    /// stands for a filter that is either on or off.
1173    Chip {
1174        /// Whether it carries its own remove affordance.
1175        removable: bool,
1176    },
1177}
1178
1179impl Token {
1180    /// Whether this answers a click.
1181    ///
1182    /// The whole difference between the two members, and the reason a renderer
1183    /// with no hover (a touch surface, a terminal) can still tell them apart.
1184    #[must_use]
1185    pub const fn interactive(self) -> bool {
1186        matches!(self, Self::Chip { .. })
1187    }
1188
1189    /// How it sits, given whether it is currently latched down.
1190    ///
1191    /// A badge is flat: it is a label, and giving it an edge would say it can
1192    /// be pressed. A chip is raised, and inset while latched.
1193    #[must_use]
1194    pub const fn depth(self, latched: bool) -> Depth {
1195        match self {
1196            Self::Badge => Depth::Flat,
1197            Self::Chip { .. } if latched => Depth::Well,
1198            Self::Chip { .. } => Depth::Raised,
1199        }
1200    }
1201}
1202
1203/// Something the app is telling the user, unprompted.
1204///
1205/// Two concepts, not one with a placement. They differ in more than where they
1206/// sit: a toast is transient, stacked and self-dismissing, and a banner is
1207/// persistent, in flow, one per region, and dismissed by fixing the condition
1208/// it reports. Folding them into one member with a placement parameter would
1209/// make lifetime, stacking and dismissal all placement-dependent, which is the
1210/// description leaking renderer policy.
1211///
1212/// All three apps have banners: `info_banner` and `warning_banner` in
1213/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
1214/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
1215/// webview apps also have toasts. So neither member is speculative, and no app
1216/// gains a concept it lacks except audiofiles, whose renderer may legitimately
1217/// decline to draw a toast at all.
1218#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1219pub enum Notice {
1220    /// Transient, stacked, dismisses itself.
1221    Toast,
1222    /// Persistent, in flow, one per region, dismissed by fixing the cause.
1223    Banner,
1224}
1225
1226impl Notice {
1227    /// Whether it goes away on its own.
1228    #[must_use]
1229    pub const fn transient(self) -> bool {
1230        matches!(self, Self::Toast)
1231    }
1232
1233    /// How it sits.
1234    ///
1235    /// A toast floats above the page rather than resting on it, which is
1236    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
1237    /// flow. Both are raised, and they are raised off different things.
1238    #[must_use]
1239    pub const fn fill(self) -> Fill {
1240        match self {
1241            Self::Toast => Fill::Overlay,
1242            Self::Banner => Fill::Raised,
1243        }
1244    }
1245}
1246
1247/// The parts of a list row.
1248///
1249/// Four to begin with, taken from Balanced Breakfast, which was the only
1250/// consumer that had all of them (`row-primary`, `row-secondary`, `row-meta`,
1251/// `row-actions`). audiofiles has two and no slot structure at all, so it gains
1252/// meta and actions as real work rather than a rename; goingson moves off
1253/// `task-row` / `task-cell`.
1254///
1255/// [`Tokens`](Self::Tokens) joined at 0.9.0, and `#[non_exhaustive]` with it.
1256/// See the crate header for why the two arrived together.
1257///
1258/// # Meta against Tokens
1259///
1260/// The line is whether the thing has its own standing. `Meta` is one short
1261/// trailing fact about the row, written as text: a count, a size, a date.
1262/// `Tokens` is a set of small labelled things, each of which can be toned and
1263/// can answer a click. "3 files" is meta. A status badge that is amber, and a
1264/// tag you can click to filter by, are tokens.
1265///
1266/// Keeping them apart is what a single widened slot would have foreclosed. A
1267/// renderer can right-align one string and cannot usefully do the same to a
1268/// strip of chips, and a fact that is not clickable should not be drawn as
1269/// though it were.
1270/// How much vertical room a part's text may take.
1271///
1272/// A row is an inline run and every part in it is a leaf, so a part's text has
1273/// always been drawn on one line and no description could say otherwise. Two
1274/// apps say otherwise in their own stylesheets, both to the same number and
1275/// both with a comment explaining it: Balanced Breakfast clamps a feed row's
1276/// title to two lines (`.row--article .row-primary`, whose comment reads
1277/// "overrides .row-primary's single flex line"), and goingson clamps a
1278/// problem's body to two ("two lines is enough to recognize one, and the full
1279/// text is in the task once promoted").
1280///
1281/// Two named tiers rather than a line count, and the count is what the measured
1282/// demand argues against. Both sites want exactly one tier past the default,
1283/// and a number invites a row whose primary is a paragraph, which is a block
1284/// and has no business in a run. A third tier is a decision, made here, rather
1285/// than something a call site can reach for.
1286///
1287/// What a renderer owes it: `Tight` is what a run already does and needs no
1288/// answer. `Relaxed` is at most two lines and then truncation, however that
1289/// renderer truncates -- a webview clamps, a terminal wraps into two rows of
1290/// cells, an immediate-mode renderer caps the galley. A renderer that cannot
1291/// give two lines may draw one; what it may not do is grow without bound,
1292/// because the run is a line and the row's neighbours are relying on that.
1293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1294#[non_exhaustive]
1295pub enum Flow {
1296    /// One line. What every part did before this type existed.
1297    #[default]
1298    Tight,
1299    /// Up to two lines, then truncated.
1300    Relaxed,
1301}
1302
1303impl Flow {
1304    /// How many lines the part may take.
1305    ///
1306    /// A number here rather than in the enum, because a renderer needs one and
1307    /// a call site does not. That asymmetry is the whole argument for the
1308    /// tiers: the description says how much room the thing deserves and this
1309    /// says what that costs, so a third tier changes one line rather than every
1310    /// consumer's arithmetic.
1311    #[must_use]
1312    pub const fn lines(self) -> u8 {
1313        match self {
1314            Self::Relaxed => 2,
1315            // Including any tier added later: one line is the safe reading of
1316            // an unknown flow, since it is what the run guaranteed before flows
1317            // existed.
1318            _ => 1,
1319        }
1320    }
1321}
1322
1323#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1324#[non_exhaustive]
1325pub enum RowPart {
1326    /// The thing itself. What the row is called.
1327    Primary,
1328    /// Supporting text under the primary.
1329    Secondary,
1330    /// A short trailing fact: a count, a size, a date.
1331    Meta,
1332    /// Controls that act on this row.
1333    Actions,
1334    /// Small labelled things belonging to the row: badges, chips, tags.
1335    ///
1336    /// Each carries its own [`Token`] kind and [`Tone`], so a renderer with no
1337    /// colour still has the kind to work with, and one with no chips still has
1338    /// the label. That is the constrained-consumer test this vocabulary exists
1339    /// to pass, and it is why the tone lives on the token rather than on the
1340    /// part.
1341    Tokens,
1342    /// How much of a set the row's thing has done: a [`Meter`] in the row.
1343    ///
1344    /// Added 0.11.0, `da5666ae`, and it is [`Tokens`](Self::Tokens)'s problem
1345    /// again with a different payload. [`Meter`] arrived at 0.10.0 and closed
1346    /// two of the seven sites that asked for it; the other five sit in rows, and
1347    /// a row holds no nodes by the ruling that a row part may not carry an
1348    /// arbitrary node — the door through which a description becomes a
1349    /// templating language. So the part carries the *description of a bar*
1350    /// rather than a node, exactly as `Tokens` carries tags rather than nodes.
1351    ///
1352    /// Without it a row flattens the proportion into [`Meta`](Self::Meta) as
1353    /// "3/7 subtasks", which keeps both numbers and loses the reading, the same
1354    /// way a toned status badge read as prose before `Tokens`.
1355    Proportion,
1356}
1357
1358impl RowPart {
1359    /// What the part is worth when the run does not fit.
1360    ///
1361    /// The default only. A part may say otherwise, and a renderer reads the
1362    /// part rather than the role; this is what a description that has never
1363    /// heard of [`Priority`] means, which is every description written before
1364    /// the field existed.
1365    ///
1366    /// Deriving it from the role is the thing this vocabulary has otherwise
1367    /// been moving away from, and it is right here for one reason: the roles
1368    /// already encode this ranking and every consumer already assumes it.
1369    /// [`Primary`](Self::Primary) is what the row is called, and
1370    /// [`Priority::Essential`]'s own doc was written about exactly that --
1371    /// "without it the row does not identify itself".
1372    ///
1373    /// [`Actions`](Self::Actions) is `Essential` and it is the interesting one.
1374    /// A control is not a fact, so dropping it does not cost the reader a
1375    /// detail; it costs them the only way to act on the row, and in a terminal
1376    /// it silently removes something focus had already been claimed for. A
1377    /// renderer that needs room takes it from what the row *says*, never from
1378    /// what it *offers*.
1379    ///
1380    /// An unknown member reads as [`Priority::Secondary`]: droppable, but not
1381    /// first, since guessing `Optional` for something this crate has not been
1382    /// taught would make a new member the first thing to vanish.
1383    #[must_use]
1384    pub const fn priority(self) -> Priority {
1385        match self {
1386            Self::Primary | Self::Actions => Priority::Essential,
1387            Self::Meta | Self::Proportion => Priority::Optional,
1388            _ => Priority::Secondary,
1389        }
1390    }
1391
1392    /// The content intent the part takes.
1393    #[must_use]
1394    pub const fn intent(self) -> &'static str {
1395        match self {
1396            Self::Primary => "content",
1397            Self::Secondary => "content-secondary",
1398            Self::Meta => "content-muted",
1399            // Actions carry controls rather than text, so they inherit.
1400            Self::Actions => "content",
1401            // So do tokens: each one carries its own tone, and a part-level
1402            // intent underneath it would fight the token that sits on it.
1403            Self::Tokens => "content",
1404            // And so does a proportion, for the same reason: the meter carries
1405            // the tone, and it is about the ratio rather than about the row.
1406            Self::Proportion => "content",
1407        }
1408    }
1409}
1410
1411/// How far down the heading tree a title sits.
1412///
1413/// Three, and only the three that are actually headings. The bands those used
1414/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
1415/// and `.detail-header`) are arrangement, not type, and live at
1416/// [`Region::Band`]. One of them contains no text at all.
1417#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1418pub enum Heading {
1419    /// Names the whole screen. One per screen.
1420    Page,
1421    /// Names a block within the screen.
1422    Section,
1423    /// Names a sub-block inside an already-named section.
1424    Subsection,
1425}
1426
1427impl Heading {
1428    /// Whether a rule follows the heading.
1429    ///
1430    /// audiofiles' `section_header` draws a separator and its
1431    /// `subsection_label` deliberately does not, which is the only thing
1432    /// distinguishing the two once weight and colour are deferred.
1433    #[must_use]
1434    pub const fn separated(self) -> bool {
1435        matches!(self, Self::Section)
1436    }
1437}
1438
1439/// A control that picks between things.
1440///
1441/// Three, because three distinct behaviours are in play and collapsing any two
1442/// loses something. A segmented control picks a value; a tab picks a pane; a
1443/// toggle picks nothing and simply holds itself on or off.
1444#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1445pub enum Selector {
1446    /// Exactly one of N, and the options abut.
1447    Segmented,
1448    /// Independent on or off, on its own.
1449    Toggle,
1450    /// Navigation between panes. The folder semantic.
1451    Tabs,
1452}
1453
1454impl Selector {
1455    /// How the chosen option sits.
1456    ///
1457    /// Held in for a segmented control and a toggle, which is the same shape
1458    /// pressing produces and the whole economy of the idiom: one appearance,
1459    /// two reasons to wear it. A tab is the exception, because the selected
1460    /// folder tab comes *forward* to join the pane it opens.
1461    #[must_use]
1462    pub const fn chosen(self) -> Depth {
1463        match self {
1464            Self::Segmented | Self::Toggle => Depth::Well,
1465            Self::Tabs => Depth::Raised,
1466        }
1467    }
1468
1469    /// How the options that were *not* picked sit.
1470    ///
1471    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
1472    /// option falling through to [`Depth::Flat`], which says it is level with
1473    /// the strip it sits in, and no renderer emitted anything for it. That is
1474    /// wrong in both directions and goingson proved it: its unchosen tabs are
1475    /// recessed by hand, and being recessed is *why* the chosen one reads as
1476    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
1477    /// drawn on the strip's own colour, which is a much weaker folder effect
1478    /// than the contrast the idiom is named after.
1479    ///
1480    /// Each member is the inverse of its chosen state, which is the whole
1481    /// content of "picked" once colour is deferred:
1482    ///
1483    /// - Tabs recede, so the chosen one comes forward.
1484    /// - A segment and a toggle stand up, so the chosen one is held in.
1485    #[must_use]
1486    pub const fn unchosen(self) -> Depth {
1487        match self {
1488            Self::Tabs => Depth::Sunken,
1489            Self::Segmented | Self::Toggle => Depth::Raised,
1490        }
1491    }
1492
1493    /// Whether the options touch.
1494    ///
1495    /// The gap is the entire difference between a segmented control and a row
1496    /// of buttons that happen to sit near each other, which is what audiofiles'
1497    /// `segmented_control` says in its own comment and why it zeroes the
1498    /// spacing by hand.
1499    #[must_use]
1500    pub const fn abutting(self) -> bool {
1501        matches!(self, Self::Segmented | Self::Tabs)
1502    }
1503}
1504
1505/// What is in a region right now.
1506///
1507/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
1508/// nothing at all is renderer policy, the same class of decision that got
1509/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
1510/// each grew a skeleton with differently-named parts; both keep them, as the
1511/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
1512/// and needs none, because an immediate-mode renderer simply repaints.
1513///
1514/// # Four states and not two, as of 0.12.0
1515///
1516/// `703f4cd2`. It named `Ready` and `Pending` and stopped, so a described screen
1517/// whose list came back empty had to render an empty region or invent its own
1518/// placeholder text, and neither says what it is. goingson draws one at 27 sites
1519/// across 12 files and Balanced Breakfast at 9, with a class family that had
1520/// already drifted into `empty-state`, `empty-state--error`, `error-state` and
1521/// six more.
1522///
1523/// The four are one axis because they are mutually exclusive: a region shows its
1524/// content, or a sign that it is coming, or a sign that there is none, or a sign
1525/// that it broke. Never two. That is the test for one enum against several
1526/// fields, and it is why this grew rather than a new member arriving beside it.
1527///
1528/// # What is not here
1529///
1530/// **The message.** "No projects yet" is content, and this names a state. It
1531/// lives with whatever holds the region — in quasi's case a `Slot` — alongside
1532/// the action that leads out of the emptiness, since an address is the one thing
1533/// this crate never names.
1534///
1535/// **How much room it gets.** goingson's `--compact`, `--dashboard` and
1536/// `--padded` are the same state at three sizes, and a size is
1537/// `makeover-geometry`'s question. Naming them here would be this crate stating
1538/// values again.
1539///
1540/// **The icon.** Presentation, and each host has its own answer or none.
1541#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1542#[non_exhaustive]
1543pub enum Readiness {
1544    /// The content is here.
1545    Ready,
1546    /// The content is on its way.
1547    ///
1548    /// For a region that changes *after* the first paint, and never for the
1549    /// first paint itself: see "First paint is final paint" in the crate header.
1550    /// A host that renders once, with its data already in hand, has nothing to
1551    /// say this about, and a screen arriving in this state is describing a
1552    /// moment its host should not have been in.
1553    ///
1554    /// What stands in occupies the geometry the content will occupy. A stand-in
1555    /// sized to itself rather than to what replaces it is the reflow the rule
1556    /// forbids, arriving one repaint later.
1557    Pending,
1558    /// The content arrived and there is none of it.
1559    ///
1560    /// Not a failure. An empty list is the normal state of a new install, and a
1561    /// renderer that drew it in a danger tone would be reporting a fault where
1562    /// there is none.
1563    Empty,
1564    /// The content did not arrive.
1565    Failed,
1566}
1567
1568impl Readiness {
1569    /// Whether the region draws its own content, or something standing in for
1570    /// it.
1571    ///
1572    /// The question every renderer asks first, so it is answered once here
1573    /// rather than by a `matches!` in each. A state added later is a stand-in
1574    /// until proven otherwise: falling back to drawing content that may not be
1575    /// there is the worse of the two mistakes.
1576    #[must_use]
1577    pub const fn shows_content(self) -> bool {
1578        matches!(self, Self::Ready)
1579    }
1580
1581    /// What the state means, for a renderer choosing a colour.
1582    ///
1583    /// Derived rather than carried, which is the opposite of [`Meter`] and
1584    /// [`Figure`], and the difference is worth stating: a proportion's meaning
1585    /// depends on what is being counted and only the app knows it, while
1586    /// "nothing here yet" and "this broke" mean the same thing in every app that
1587    /// will ever have them.
1588    #[must_use]
1589    pub const fn tone(self) -> Tone {
1590        match self {
1591            Self::Failed => Tone::Danger,
1592            _ => Tone::Neutral,
1593        }
1594    }
1595}
1596
1597/// An action is waiting on something that resolves once, in expected finite
1598/// time.
1599///
1600/// The control-side sibling of [`Readiness`]. That enum names four states for a
1601/// region and named nothing at all for the button that is currently doing what
1602/// it was clicked for, so the in-flight treatment is hand-written wherever it
1603/// exists: the MNW server carries 57 in-flight indicators against 2 guards
1604/// against a second press, which is the spinner mostly present and the guard
1605/// mostly absent, on a codebase whose money path is a purchase button.
1606///
1607/// # What is described here, and what is not
1608///
1609/// The fact is that there is an outstanding thing which will complete. Not that
1610/// the address is remote: a heavy local query waits too, and a server calling a
1611/// payment provider is not the browser leaving the app. Not that the call is
1612/// slow either, which is a judgement about a call rather than a property of one.
1613///
1614/// Resolving **once** is the boundary, and it is what separates this from a
1615/// screen that keeps changing. A live screen never resolves and has no name in
1616/// this crate yet.
1617///
1618/// # One mark, two renderings
1619///
1620/// | what reads it | what it does |
1621/// |---|---|
1622/// | a control that was pressed | goes busy and refuses a second press until it resolves |
1623/// | a region fed by it | stands in as [`Readiness::Pending`], then fills |
1624///
1625/// The two were on the table separately and both were taken. Controls alone
1626/// leaves a slow region hand-split into its own route, which is what MNW's user
1627/// dashboard does with its payout summary; regions alone leaves the purchase
1628/// button unguarded.
1629///
1630/// # A quantity when it is measured, never a duration
1631///
1632/// [`amount`](Self::amount) is stated only when it is a measured fact about the
1633/// payload. An upload's file length, yes; a round trip to a payment provider,
1634/// [`None`]. A duration is described nowhere, and a renderer may not manufacture
1635/// one from the amount either: a determinate bar shows what is done over what
1636/// there is, plus the time it has taken so far, and never a remaining time, an
1637/// arrival time or a rate extrapolated forwards. A prediction is wrong the
1638/// moment the transfer stalls, and being confidently wrong is worse than being
1639/// honestly indeterminate.
1640///
1641/// This is why the crate refuses to say how long an undo stays offered and
1642/// accepts a byte count here. The refusal is about naming a decision that
1643/// belongs to the renderer; a file's length is not a decision, nobody chose it.
1644///
1645/// # Not [`Meter`]
1646///
1647/// [`Meter`] is how much of a set is done, and its own docs refuse the progress
1648/// of an operation on the grounds that a description is built once and dropped
1649/// while an operation runs between renders. That refusal stands. This names the
1650/// operation and its size, which is all that is known before it starts; how much
1651/// of it has gone through is the renderer's to observe live, and nothing round
1652/// trips through a description to say so.
1653#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1654#[non_exhaustive]
1655pub struct Awaiting {
1656    /// Total work to get through, when it is a measured fact about the payload.
1657    ///
1658    /// `None` when the wait has no countable size, which is the common case and
1659    /// the default.
1660    ///
1661    /// Unit-agnostic on purpose. Bytes for an upload, rows for an import; what
1662    /// is being counted is the app's business and a renderer draws a proportion
1663    /// either way.
1664    pub amount: Option<u64>,
1665}
1666
1667impl Awaiting {
1668    /// A wait with no countable size.
1669    #[must_use]
1670    pub const fn unmeasured() -> Self {
1671        Self { amount: None }
1672    }
1673
1674    /// A wait whose size is known.
1675    ///
1676    /// Reach for it only with a measured figure. An estimate written in here is
1677    /// a prediction wearing a fact's clothes, and the renderer has no way to
1678    /// tell the two apart.
1679    #[must_use]
1680    pub const fn of(amount: u64) -> Self {
1681        Self {
1682            amount: Some(amount),
1683        }
1684    }
1685
1686    /// Whether there is a proportion to draw.
1687    ///
1688    /// The question every renderer asks first, answered once here rather than by
1689    /// a `matches!` in each. False means indeterminate, which is the honest
1690    /// drawing when nothing countable was measured.
1691    #[must_use]
1692    pub const fn is_determinate(self) -> bool {
1693        self.amount.is_some()
1694    }
1695}
1696
1697/// How much of a set is done.
1698///
1699/// Added 0.10.0. Nine sites across the two webview apps drew a bar and nothing
1700/// here named one, so every described screen concatenated the two numbers into
1701/// its heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m
1702/// est, over". Every fact survives that and the reading does not, which is the
1703/// same loss `RowPart::Tokens` closed when a toned status badge became prose.
1704///
1705/// # Why a pair and not a percentage
1706///
1707/// Both numbers, not the percentage the apps compute from them. The percentage
1708/// was the obvious shape and it had already been tried: goingson's
1709/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
1710/// away the one case the bar exists to show — 45 minutes tracked against a
1711/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
1712/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
1713/// companion flag, and [`percent`](Meter::percent) is still one call away for a
1714/// renderer that wants it.
1715///
1716/// The pair is also what the apps already have at every site. All seven
1717/// determinate bars write the ratio into the accessible layer and never the
1718/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
1719/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
1720/// percentage member would have made [`label`](Meter::label) mandatory at every
1721/// call site, which is the concatenated text this member removes, moved one
1722/// layer down.
1723///
1724/// # What this is not
1725///
1726/// The progress of an *operation*. Two of the nine sites are that — goingson's
1727/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
1728/// purpose. Both are imperative controllers over a live handle, driven by a tick
1729/// or an event stream, and a description is built once and dropped. Holding one
1730/// would mean growing a way to update a description between renders, which is a
1731/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
1732/// honest part.
1733///
1734/// The two cases are distinguishable in the markup rather than by taste: every
1735/// determinate bar in both apps carries a tone, and neither operation bar
1736/// carries one. Two codebases drew that line the same way without coordinating.
1737#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1738pub struct Meter<'a> {
1739    /// How much is done. May exceed [`total`](Self::total), and that is the
1740    /// case worth drawing.
1741    pub done: u32,
1742    /// How much there is to do. Zero means there is no set, not that the set is
1743    /// complete.
1744    pub total: u32,
1745    /// What the proportion means right now.
1746    ///
1747    /// Carried rather than derived, because no renderer can work it out. The
1748    /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
1749    /// a time estimate, and goingson picks between them from `is_over_estimate`,
1750    /// a fact about the data and not about the number.
1751    pub tone: Tone,
1752    /// What is being counted, if the bar says so: "subtasks", "tasks".
1753    ///
1754    /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
1755    /// and the two numbers; handing it the assembled string would put the
1756    /// sentence order in the description, where a terminal at one line and a
1757    /// tooltip want different ones.
1758    pub label: Option<&'a str>,
1759}
1760
1761impl<'a> Meter<'a> {
1762    /// A proportion with no tone and no label.
1763    #[must_use]
1764    pub const fn new(done: u32, total: u32) -> Self {
1765        Self {
1766            done,
1767            total,
1768            tone: Tone::Neutral,
1769            label: None,
1770        }
1771    }
1772
1773    /// What the proportion means.
1774    #[must_use]
1775    pub const fn tone(mut self, tone: Tone) -> Self {
1776        self.tone = tone;
1777        self
1778    }
1779
1780    /// What is being counted.
1781    #[must_use]
1782    pub const fn label(mut self, label: &'a str) -> Self {
1783        self.label = Some(label);
1784        self
1785    }
1786
1787    /// How full the bar is, 0 to 100, clamped.
1788    ///
1789    /// For drawing, which is the only thing a clamped number is good for. Ask
1790    /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
1791    /// is `time_progress`'s bug again with the clamp moved.
1792    ///
1793    /// An empty set reads as 0. Nothing is done, because there is nothing to do
1794    /// and no bar to fill; the apps guard on the count before drawing at all.
1795    #[must_use]
1796    pub const fn percent(&self) -> u8 {
1797        if self.total == 0 {
1798            return 0;
1799        }
1800        let scaled = (self.done as u64 * 100) / self.total as u64;
1801        if scaled > 100 { 100 } else { scaled as u8 }
1802    }
1803
1804    /// Whether more is done than there was to do.
1805    ///
1806    /// The fact [`percent`](Self::percent) destroys, kept reachable so a
1807    /// renderer can mark the over-run rather than drawing a full bar and
1808    /// implying it landed exactly.
1809    #[must_use]
1810    pub const fn overflowing(&self) -> bool {
1811        self.done > self.total
1812    }
1813
1814    /// Whether there is a set at all.
1815    ///
1816    /// A meter over nothing is sayable on purpose, for the same reason a field
1817    /// with no options is: it is what an app with an unloaded count actually
1818    /// has, and a renderer that shows an empty bar says so on screen rather than
1819    /// dividing by zero.
1820    #[must_use]
1821    pub const fn is_empty(&self) -> bool {
1822        self.total == 0
1823    }
1824}
1825
1826/// One figure with a caption: a number and what it counts.
1827///
1828/// The dashboard shape. A large value over a small caption, several of them in a
1829/// strip: a current streak, a completion rate, a total. Added 0.11.0,
1830/// `93c6a174`, after goingson turned out to have five of them across five
1831/// screens with five class vocabularies for the one shape — `task-overview-stat`,
1832/// `stat-box`, `month-stat-item`, `contact-summary-stat`, `sync-stat`. Four put
1833/// the value above the caption and one inverts it, which is drift inside the
1834/// shape rather than a second shape.
1835///
1836/// # Why the value is text
1837///
1838/// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
1839/// formatted, and the formatting is the app's because only it knows whether the
1840/// number is a percentage, a duration or a ratio. This carries none of the
1841/// arithmetic [`Meter`] carries, and that is the difference between them: a
1842/// meter is a proportion a renderer draws, and a figure is a fact a renderer
1843/// sets in type.
1844///
1845/// # Tone is carried, for [`Meter`]'s reason
1846///
1847/// Three of the five sites tone the figure by their own means — `red`/`blue` on
1848/// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
1849/// sync. So tone is carried at every site that needs it and derived at none, and
1850/// no renderer can work out that a streak of zero is worth colouring.
1851///
1852/// # What is not here
1853///
1854/// Whether the figure answers a click. One of the five is a control — sync's
1855/// "Not Applied: 3" opens the list — and an action is not something this crate
1856/// can name: nothing here knows what a route is. That belongs beside the figure
1857/// in whatever layer holds the actions, the same way a row's activation sits
1858/// beside its parts rather than inside them.
1859///
1860/// The arrangement is not here either. Several figures in a strip is a set, and
1861/// a renderer given them one at a time cannot tell it is looking at one; the
1862/// layer that holds the tree is where the set gets said.
1863#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1864pub struct Figure<'a> {
1865    /// The number, formatted the way the app means it to read.
1866    pub value: &'a str,
1867    /// What it counts. The caption under the value.
1868    pub caption: &'a str,
1869    /// How the value has moved, if the app is tracking that.
1870    ///
1871    /// Added 0.13.0. Text, for [`value`](Self::value)'s reason: only the app
1872    /// knows whether a move reads as `+12.5%`, `+3` or `2x`, and a renderer
1873    /// handed a number would have to guess.
1874    ///
1875    /// This is what [`tone`](Self::tone) was for and had no consumer of. The MNW
1876    /// server has four screens whose stat card is a label, a value and a delta,
1877    /// and the delta is the toned part: the figure itself is an ordinary fact
1878    /// and it is the movement that reads as good or bad. Without this the delta
1879    /// has to be folded into the caption, which loses the tone and reads as a
1880    /// longer caption rather than as a second, smaller line.
1881    pub change: Option<&'a str>,
1882    /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
1883    ///
1884    /// Applies to [`change`](Self::change) where there is one, since that is the
1885    /// part that carries the judgement, and to the value where there is not.
1886    pub tone: Tone,
1887}
1888
1889impl<'a> Figure<'a> {
1890    /// A figure that is an ordinary fact.
1891    #[must_use]
1892    pub const fn new(value: &'a str, caption: &'a str) -> Self {
1893        Self {
1894            value,
1895            caption,
1896            change: None,
1897            tone: Tone::Neutral,
1898        }
1899    }
1900
1901    /// How the value has moved.
1902    #[must_use]
1903    pub const fn change(mut self, change: &'a str) -> Self {
1904        self.change = Some(change);
1905        self
1906    }
1907
1908    /// What the figure means.
1909    #[must_use]
1910    pub const fn tone(mut self, tone: Tone) -> Self {
1911        self.tone = tone;
1912        self
1913    }
1914}
1915
1916/// Something the user can do, and what it costs to say so.
1917///
1918/// Added 0.17.0, out of `quasi-tui`: the terminal renderer had drawn one of
1919/// these for months and every other consumer that wanted a button had written
1920/// its own, because this layer named [`RowPart::Actions`] as a *slot* and never
1921/// named the thing that goes in it. Beside [`Meter`] and [`Figure`] for the
1922/// reason those are here: a renderer that is handed the parts has to decide how
1923/// to say them, and a renderer that is handed a finished string has already had
1924/// the decision made for it.
1925///
1926/// No address. Where a control goes is the app's business and every host
1927/// follows it differently — an `hx-get`, a protocol URL, a function call — so
1928/// the description says what the control *is* and the caller keeps what it
1929/// does. That is the same split [`Choice`] makes.
1930///
1931/// No confirmation flag either, and that one is a finding rather than an
1932/// omission: a question asked *after* a control is pressed belongs to whatever
1933/// is holding the interaction, and a renderer that drew it would be asking
1934/// before there was anything to answer.
1935/// How a picture sits in the box it is given.
1936///
1937/// An intent rather than a value, so a renderer picks the expression it has:
1938/// `object-fit` in a webview, a texture's UV rect in egui, and in a terminal a
1939/// choice about how many cells the blit gets. Named because MNW already makes
1940/// the distinction deliberately at 17 sites and makes it three different ways,
1941/// which is a policy the app decided rather than one a shared crate would be
1942/// picking by accident.
1943#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1944#[non_exhaustive]
1945pub enum Fit {
1946    /// The picture's own proportions, and the box takes the height they imply.
1947    ///
1948    /// The default because it is the only one that shows the whole picture at
1949    /// its own shape, so a renderer that ignores this enum entirely is still
1950    /// right about the common case. A screenshot wants this; the shipped MNW
1951    /// carousel sets no `object-fit` at all, which is this.
1952    #[default]
1953    Natural,
1954    /// Fill the box and crop whatever does not fit.
1955    ///
1956    /// For a picture in a slot whose shape the layout fixed: a thumbnail, an
1957    /// avatar, cover art. 15 of MNW's 17 sites.
1958    Cover,
1959    /// Fit inside the box whole, leaving space on two sides.
1960    ///
1961    /// The letterbox. For when the whole picture matters more than filling the
1962    /// space, and the space is not the picture's shape.
1963    Contain,
1964}
1965
1966/// A picture, and what it says to someone who is not looking at it.
1967///
1968/// # No source
1969///
1970/// [`Act`]'s split, for [`Act`]'s reason. A source is an address, and this
1971/// crate has no notion of an address: it says what a thing *is* and the caller
1972/// keeps what it points at. The three findings dropped from 0.11.0 were all
1973/// this same shape.
1974///
1975/// It matters more here than it does for a control, because a picture is the
1976/// one member where the address is most of what a webview needs and *none* of
1977/// what the description knows. `quasi_router::Node::Image` carries the URL, the
1978/// way it carries an `Action` for a control.
1979///
1980/// # Why [`alt`](Self::alt) is not optional
1981///
1982/// Every other host has to draw something, and for two of the three the alt
1983/// text is not a fallback but the whole rendering: a terminal without a
1984/// graphics protocol has the words and nothing else. Making it optional would
1985/// make "this picture is invisible on a terminal" the default, and the
1986/// description would be carrying a webview assumption in its shape.
1987///
1988/// An image that genuinely says nothing — a rule, a spacer, a decoration
1989/// repeating what the text beside it already said — is an empty `alt`, which is
1990/// the same thing HTML means by it and is a claim rather than an oversight.
1991#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1992pub struct Image<'a> {
1993    /// What the picture says, for anything not showing it.
1994    ///
1995    /// Empty means the picture is decorative and adds nothing to the text
1996    /// around it. See the type's own docs on why this is not an `Option`.
1997    pub alt: &'a str,
1998    /// A visible line under the picture, where the app wants one.
1999    ///
2000    /// Distinct from [`alt`](Self::alt) and the difference is who it is for: a
2001    /// caption is content everybody reads, alt text is what stands in for the
2002    /// picture. A screenshot captioned "The library view" still needs alt text
2003    /// describing what is in the shot.
2004    pub caption: Option<&'a str>,
2005    /// How it sits in the box it is given.
2006    pub fit: Fit,
2007    /// The picture's own dimensions, where the app knows them.
2008    ///
2009    /// **Not a display size**, and that distinction is what makes this belong
2010    /// here rather than fall foul of the deferral rule. Saying a picture should
2011    /// be 320 points wide is a layout value and is not the description's to
2012    /// give. Saying the file is 5120x3412 is a fact *about the picture*, the
2013    /// same kind of fact [`alt`](Self::alt) is, and no renderer can find it out
2014    /// without fetching the bytes.
2015    ///
2016    /// # What it is for, and it is not decoration
2017    ///
2018    /// Without it a renderer cannot reserve room, so the picture occupies
2019    /// nothing until it arrives and then takes its full height at once,
2020    /// shoving everything below it down the screen. Measured on MNW's landing
2021    /// page 2026-08-14: a 478px jump per frame, and a cumulative layout shift
2022    /// of 0.087 for the page, which is most of the way to the 0.1 that counts
2023    /// as bad.
2024    ///
2025    /// Every host wants it and none can derive it. A webview writes `width` and
2026    /// `height` so the browser holds the space; egui sizes a texture; a
2027    /// terminal with a graphics protocol scales a blit into cells. This was
2028    /// missing from 0.21.0, which is the release that added [`Image`], and its
2029    /// absence is the defect rather than an omission.
2030    ///
2031    /// `None` is honest and common: a creator-uploaded image whose dimensions
2032    /// the app never recorded genuinely does not know. It means the renderer
2033    /// cannot reserve, not that the picture has no size.
2034    pub intrinsic: Option<Extent>,
2035    /// Whether the picture is needed with the screen, or can arrive later.
2036    pub loading: Loading,
2037}
2038
2039/// A picture's own pixel dimensions.
2040///
2041/// Deliberately not [`makeover_geometry`]'s business. Geometry answers *how
2042/// much space a thing should get*, which is a scale question with the same
2043/// answer on every screen. This is the intrinsic size of one asset, which is a
2044/// fact about that asset and varies per picture.
2045///
2046/// [`makeover_geometry`]: https://docs.rs/makeover-geometry
2047#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2048pub struct Extent {
2049    /// Width in the picture's own pixels.
2050    pub width: u32,
2051    /// Height in the picture's own pixels.
2052    pub height: u32,
2053}
2054
2055impl Extent {
2056    /// A picture's dimensions.
2057    #[must_use]
2058    pub const fn new(width: u32, height: u32) -> Self {
2059        Self { width, height }
2060    }
2061
2062    /// Width over height, or `None` if either side is zero.
2063    ///
2064    /// The form a renderer actually reserves space with: a box that knows its
2065    /// proportion holds the right height at any width, which is what a
2066    /// responsive picture needs and what a fixed pixel height cannot give.
2067    #[must_use]
2068    pub fn ratio(self) -> Option<f32> {
2069        (self.width > 0 && self.height > 0).then(|| self.width as f32 / self.height as f32)
2070    }
2071}
2072
2073/// When a picture is needed.
2074///
2075/// A claim about *importance and position* rather than a fetch mechanism, which
2076/// is why it is the description's to make: only the app knows whether a picture
2077/// is the first thing on the screen or the fortieth thing down a list.
2078///
2079/// # Eager is the default, and that is a correctness choice
2080///
2081/// 0.21.0 emitted the webview's `loading="lazy"` for every picture, on the
2082/// evidence that the one consumer measured wrote it. That was reading a habit
2083/// as a rule. Deferring a picture that is on screen at first paint does not
2084/// save anything -- it is needed immediately either way -- and it delays the
2085/// arrival, so the space it eventually takes is claimed later and the shift is
2086/// more visible, not less.
2087///
2088/// So the safe answer is the default and the optimisation is opted into. A
2089/// carousel is the case that proves the two cannot be one setting for the
2090/// renderer to choose: its first frame is on screen and its other frames are
2091/// not, in the same widget, at the same moment.
2092#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2093#[non_exhaustive]
2094pub enum Loading {
2095    /// Needed with the screen. Fetch it now.
2096    #[default]
2097    Eager,
2098    /// Not on screen yet. It can wait until it is near.
2099    Lazy,
2100}
2101
2102impl<'a> Image<'a> {
2103    /// A picture that carries its own proportions.
2104    #[must_use]
2105    pub const fn new(alt: &'a str) -> Self {
2106        Self {
2107            alt,
2108            caption: None,
2109            fit: Fit::Natural,
2110            intrinsic: None,
2111            loading: Loading::Eager,
2112        }
2113    }
2114
2115    /// The picture's own dimensions, so a renderer can hold its place.
2116    #[must_use]
2117    pub const fn intrinsic(mut self, width: u32, height: u32) -> Self {
2118        self.intrinsic = Some(Extent::new(width, height));
2119        self
2120    }
2121
2122    /// This picture is not on screen yet; it can arrive when it is near.
2123    #[must_use]
2124    pub const fn lazy(mut self) -> Self {
2125        self.loading = Loading::Lazy;
2126        self
2127    }
2128
2129    /// A visible line under it.
2130    #[must_use]
2131    pub const fn caption(mut self, caption: &'a str) -> Self {
2132        self.caption = Some(caption);
2133        self
2134    }
2135
2136    /// How it sits in its box.
2137    #[must_use]
2138    pub const fn fit(mut self, fit: Fit) -> Self {
2139        self.fit = fit;
2140        self
2141    }
2142
2143    /// Whether the picture adds anything for someone not looking at it.
2144    ///
2145    /// A renderer with no way to show a picture uses this to decide between
2146    /// drawing the alt text and drawing nothing at all. Both are correct and
2147    /// the difference is this flag: standing in for a decorative rule with the
2148    /// word "decoration" is worse than leaving the space empty.
2149    #[must_use]
2150    pub const fn speaks(self) -> bool {
2151        !self.alt.is_empty()
2152    }
2153}
2154
2155/// What a [`Track`]'s integers count.
2156///
2157/// `Track::fraction` never needed this -- the arithmetic is the same whatever
2158/// the numbers mean -- which is exactly how the ruler came to assume minutes
2159/// and print `00:00` over a month. A renderer drawing an axis has to write a
2160/// label, and it cannot derive the unit from the numbers.
2161///
2162/// Added 2026-08-15, after a probe put a fifteen-day span on a
2163/// thirty-one-slot track and got correct geometry under a wall clock.
2164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2165#[non_exhaustive]
2166pub enum Unit {
2167    /// Minutes from the start of a day. A day view.
2168    #[default]
2169    Minutes,
2170    /// Whole days. A month strip, a sprint, a stretch of leave.
2171    ///
2172    /// A day-granularity axis is a *strip*, not a calendar: one line with
2173    /// spans laid along it. What it deliberately does not do is wrap into
2174    /// weeks, which is the shape that makes weekday periodicity visible and
2175    /// the one job of a month grid that a strip cannot take over. See the
2176    /// crate header.
2177    Days,
2178}
2179
2180/// A window on an axis, in whatever [`Unit`] its [`Track`] counts.
2181///
2182/// The axis a [`Track`] draws. Offsets rather than instants, because a
2183/// description carrying a `DateTime` would carry a timezone with it and the
2184/// vocabulary has no business holding one. The app knows which day or month
2185/// this is; the description says how far along it a thing sits.
2186///
2187/// `to` is exclusive and may exceed the natural period, which is how a span
2188/// running past the end is said without a second date: under
2189/// [`Unit::Minutes`], `Span::new(1320, 1560)` is 22:00 to 02:00.
2190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2191pub struct Span {
2192    from: u16,
2193    to: u16,
2194}
2195
2196impl Span {
2197    /// Midnight to midnight, the ordinary day.
2198    pub const DAY: Self = Self { from: 0, to: 1440 };
2199
2200    /// A span, clamped to a sane one.
2201    ///
2202    /// An empty or backwards span is a caller bug that should not cost a
2203    /// renderer a division by zero, so `to` is forced at least one minute past
2204    /// `from` rather than returning an error nobody can act on. Same reasoning
2205    /// as [`Share::percent`], which clamps rather than refuses.
2206    #[must_use]
2207    pub const fn new(from: u16, to: u16) -> Self {
2208        Self {
2209            from,
2210            to: if to > from { to } else { from + 1 },
2211        }
2212    }
2213
2214    /// The first minute on the axis.
2215    #[must_use]
2216    pub const fn from(self) -> u16 {
2217        self.from
2218    }
2219
2220    /// One past the last minute on the axis.
2221    #[must_use]
2222    pub const fn to(self) -> u16 {
2223        self.to
2224    }
2225
2226    /// How much the axis covers, in its track's unit. Never zero.
2227    #[must_use]
2228    pub const fn length(self) -> u16 {
2229        self.to - self.from
2230    }
2231
2232    /// Whether an offset falls on this axis.
2233    #[must_use]
2234    pub const fn holds(self, minute: u16) -> bool {
2235        minute >= self.from && minute < self.to
2236    }
2237}
2238
2239impl Default for Span {
2240    fn default() -> Self {
2241        Self::DAY
2242    }
2243}
2244
2245/// Where a thing sits on a [`Track`], and for how long.
2246///
2247/// The one fact a list cannot carry and the whole reason this primitive exists.
2248/// A list says what order things come in; a track says a thing starts 135
2249/// minutes along and lasts 45, which is a different claim and not derivable
2250/// from the first.
2251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2252pub struct Placement {
2253    at: u16,
2254    length: u16,
2255}
2256
2257impl Placement {
2258    /// A placement, clamped to a drawable one.
2259    ///
2260    /// Zero length becomes one for the same reason [`Span::new`] clamps: a
2261    /// zero-height thing is invisible rather than expressive, and every
2262    /// renderer would need its own guard.
2263    #[must_use]
2264    pub const fn new(at: u16, length: u16) -> Self {
2265        Self {
2266            at,
2267            length: if length == 0 { 1 } else { length },
2268        }
2269    }
2270
2271    /// Offset from the axis origin, matching [`Span`]'s.
2272    #[must_use]
2273    pub const fn at(self) -> u16 {
2274        self.at
2275    }
2276
2277    /// How long it lasts, in its track's unit. Never zero.
2278    #[must_use]
2279    pub const fn length(self) -> u16 {
2280        self.length
2281    }
2282
2283    /// One past its last minute.
2284    #[must_use]
2285    pub const fn end(self) -> u16 {
2286        self.at + self.length
2287    }
2288
2289    /// Whether two placements cover any of the same time.
2290    ///
2291    /// Geometry, and deliberately not a described field. Whether an overlap is
2292    /// a *conflict* is the app's judgment -- a meeting inside a block of free
2293    /// time overlaps and is fine -- and that judgment travels the way every
2294    /// other judgment does, as a [`Tone`] on the thing itself. What a renderer
2295    /// needs in order to lay two things side by side instead of on top of each
2296    /// other is this, and it can compute it.
2297    ///
2298    /// The alternative was a `conflicts: bool` on each entry, which is state
2299    /// that can disagree with the times beside it. Two sources for one fact is
2300    /// how a screen starts rendering a conflict badge on a thing that no longer
2301    /// conflicts.
2302    #[must_use]
2303    pub const fn overlaps(self, other: Self) -> bool {
2304        self.at < other.end() && other.at < self.end()
2305    }
2306}
2307
2308/// A time axis: things placed by when they happen, rather than flowed.
2309///
2310/// # Why this is a primitive
2311///
2312/// This crate refused to name it until 2026-08-15, on the argument that a
2313/// description expressive enough to draw a timeline is a component library
2314/// wearing a description's name. The refusal is withdrawn, and it is worth
2315/// being precise about what was wrong with it, because the reasoning it used
2316/// applies to real cases and should not be discarded with it.
2317///
2318/// What a timeline needs that a [`List`](Region::Pane) does not is **one**
2319/// thing: placement. Where a thing sits is a fact about the thing, the way a
2320/// row's primary text is, and it is not derivable from order. Everything else a
2321/// day view draws -- the labels, the gridlines, the item bodies, the tones --
2322/// is furniture this vocabulary already names. Measured against goingson's
2323/// `day-planning-render.js`, the only members it needed and could not get were
2324/// `at` and `minutes`.
2325///
2326/// So the timeline was never a component library's worth of vocabulary. It was
2327/// two integers, and the refusal was priced as though it were the whole widget.
2328/// The test that matters is not "does this shape look complicated" but "how
2329/// many members does it actually add, and are they facts or presentation".
2330/// Slot heights, gridline colour, how overlaps stack and which hour scrolls
2331/// into view on open are all presentation and all stay the renderer's, which is
2332/// why they are absent here.
2333///
2334/// # What it does not carry
2335///
2336/// No pixel measure, no scroll offset, no drag affordance. A renderer draws the
2337/// span at whatever density its host uses; `makeover-geometry` owns that the
2338/// way it owns everything else measured in pixels.
2339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2340pub struct Track {
2341    /// The window the axis covers.
2342    pub span: Span,
2343    /// The granularity a thing can be placed on, in minutes.
2344    ///
2345    /// goingson's day view is 15, giving 96 slots across a day. A renderer uses
2346    /// it to decide where gridlines fall and what a drop lands on; it does not
2347    /// constrain [`Placement`], because data arriving from a calendar does not
2348    /// respect anyone's grid.
2349    pub slot: u16,
2350    /// How often the axis labels itself, in its own unit.
2351    ///
2352    /// 60 gives an hourly ruler over a 15-minute grid, which is the common
2353    /// shape and the reason this is separate from `slot`. Zero means an
2354    /// unlabelled axis.
2355    pub tick: u16,
2356    /// What `span`, `slot`, `tick` and every [`Placement`] on it count.
2357    ///
2358    /// The one field here a renderer cannot derive, and the reason it exists:
2359    /// [`fraction`](Self::fraction) is unit-agnostic, so a day-granularity
2360    /// track produced correct geometry under an hours-and-minutes ruler until
2361    /// this was added. Geometry never needed it; a label always did.
2362    pub unit: Unit,
2363}
2364
2365impl Track {
2366    /// An ordinary day: midnight to midnight, quarter-hour slots, hourly ticks.
2367    pub const DAY: Self = Self {
2368        span: Span::DAY,
2369        slot: 15,
2370        tick: 60,
2371        unit: Unit::Minutes,
2372    };
2373
2374    /// A track over `span`, with the day's usual granularity.
2375    #[must_use]
2376    pub const fn over(span: Span) -> Self {
2377        Self {
2378            span,
2379            slot: 15,
2380            tick: 60,
2381            unit: Unit::Minutes,
2382        }
2383    }
2384
2385    /// A strip of whole days: one slot a day, a label a week.
2386    ///
2387    /// The shape a stretch of leave or a sprint is drawn on. Not a calendar --
2388    /// it does not wrap into weeks, and the crate header says why that
2389    /// distinction is the whole of what a month grid still has over this.
2390    #[must_use]
2391    pub const fn days(span: Span) -> Self {
2392        Self {
2393            span,
2394            slot: 1,
2395            tick: 7,
2396            unit: Unit::Days,
2397        }
2398    }
2399
2400    /// How many slots the axis holds.
2401    ///
2402    /// Rounded up, so a span that does not divide evenly by `slot` still has a
2403    /// slot covering its tail rather than dropping it. Never zero: `slot` of 0
2404    /// reads as one slot spanning the whole axis rather than a division by
2405    /// zero, since a renderer asking this question has already committed to
2406    /// drawing something.
2407    #[must_use]
2408    pub const fn slots(self) -> u16 {
2409        if self.slot == 0 {
2410            1
2411        } else {
2412            self.span.length().div_ceil(self.slot)
2413        }
2414    }
2415
2416    /// Where a placement sits on the axis, as a fraction from 0.0 to 1.0.
2417    ///
2418    /// The one calculation every renderer would otherwise write itself, and the
2419    /// place the three would drift apart. Clamped, so a placement outside the
2420    /// span draws at the edge rather than off it -- an event running past
2421    /// midnight is a real thing and truncating it is better than either
2422    /// panicking or drawing it somewhere impossible.
2423    #[must_use]
2424    pub fn fraction(self, minute: u16) -> f32 {
2425        let span = f32::from(self.span.length());
2426        let offset = f32::from(minute.saturating_sub(self.span.from()));
2427        (offset / span).clamp(0.0, 1.0)
2428    }
2429}
2430
2431impl Default for Track {
2432    fn default() -> Self {
2433        Self::DAY
2434    }
2435}
2436
2437#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2438pub struct Act<'a> {
2439    /// What the control says.
2440    pub label: &'a str,
2441    /// The key that reaches it where a host has keys.
2442    ///
2443    /// The one member written for a terminal before there was one. A webview
2444    /// hangs it off `accesskey` or ignores it; a terminal has nothing else to
2445    /// offer, so this is the whole of how a control is reached there.
2446    pub key: Option<&'a str>,
2447    /// What pressing it means. [`Tone::Danger`] is the destructive one.
2448    pub tone: Tone,
2449    /// Disabled, or nothing said.
2450    ///
2451    /// [`State::Disabled`] is what changes what a renderer may do: see
2452    /// [`State::suppresses_interaction`], which is what says a disabled control
2453    /// is drawn and not reachable. It was the only member from 0.19.0 to
2454    /// 0.40.0, and a control's focus is not sayable here at all — see the crate
2455    /// header, "Reach, focus and the focus ring".
2456    pub state: Option<State>,
2457    /// A sentence that is always true of this control, shown rather than hunted
2458    /// for.
2459    ///
2460    /// Standing help, not a message and not a tooltip. Half the hosts that read
2461    /// this have no pointer: a hover is one spelling of it, and the shipped
2462    /// apps reached for that spelling only because egui and a browser both had
2463    /// one. What is being said is that the sentence is true, never that it is
2464    /// hidden until a pointer arrives.
2465    ///
2466    /// # Why it is here rather than a layer up
2467    ///
2468    /// It was in `quasi_router::Act` alone until 0.40.0, and each renderer drew
2469    /// it for itself: `makeover_tui` had no hint to read, so quasi-tui built
2470    /// the muted line, and quasi-immediate called `on_hover_text` outside
2471    /// [`crate::Act`] rather than inside it. `Field::hint` was here the whole
2472    /// time, so the same idea sat at two layers depending on which thing
2473    /// carried it, and a host that was not quasi could say it of a field and
2474    /// not of a control.
2475    ///
2476    /// What kept it out was price rather than doubt: this crate declares
2477    /// `links`, so a member here moves 25 manifests across 12 repos. That is a
2478    /// release's forward-fix pass, which is a cost and was being read as a
2479    /// barrier.
2480    ///
2481    /// # What a renderer owes it
2482    ///
2483    /// Somewhere to put it, or nothing. Dropping it is legitimate; drawing it
2484    /// *instead of* the label is not, and neither is drawing it in a way that
2485    /// takes it out of the accessible tree, which is the failure `title` alone
2486    /// has on a browser. Nothing may live only in a hint.
2487    ///
2488    /// `None` is a control whose label is the whole of it, which is nearly all
2489    /// of them.
2490    ///
2491    /// Added 0.40.0.
2492    pub hint: Option<&'a str>,
2493}
2494
2495impl<'a> Act<'a> {
2496    /// An ordinary control, reachable, with no key.
2497    #[must_use]
2498    pub const fn new(label: &'a str) -> Self {
2499        Self {
2500            label,
2501            key: None,
2502            tone: Tone::Neutral,
2503            state: None,
2504            hint: None,
2505        }
2506    }
2507
2508    /// The sentence that is always true of it; see [`hint`](Self::hint).
2509    ///
2510    /// A renderer with nowhere to put it drops it, so this must never be the
2511    /// only place a fact appears.
2512    #[must_use]
2513    pub const fn hinted(mut self, hint: &'a str) -> Self {
2514        self.hint = Some(hint);
2515        self
2516    }
2517
2518    /// The key that reaches it.
2519    #[must_use]
2520    pub const fn key(mut self, key: &'a str) -> Self {
2521        self.key = Some(key);
2522        self
2523    }
2524
2525    /// What pressing it means.
2526    #[must_use]
2527    pub const fn tone(mut self, tone: Tone) -> Self {
2528        self.tone = tone;
2529        self
2530    }
2531
2532    /// Focus, or disabled.
2533    #[must_use]
2534    pub const fn state(mut self, state: State) -> Self {
2535        self.state = Some(state);
2536        self
2537    }
2538
2539    /// Whether the control is drawn and does not answer.
2540    #[must_use]
2541    pub fn disabled(&self) -> bool {
2542        self.state.is_some_and(State::suppresses_interaction)
2543    }
2544}
2545
2546/// A named part of a screen.
2547///
2548/// The thing `makeover-geometry` deliberately does not name: it names the space
2549/// *between* things by relationship, and nothing named the things. Six named
2550/// members, taken from what the two webview apps actually use, plus
2551/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
2552/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
2553/// this layer is absent rather than divergent, which makes it the cheapest of
2554/// the schemas to add and the easiest to over-build.
2555///
2556/// `#[non_exhaustive]` arrives with [`Region::Widget`], the pairing [`RowPart`]
2557/// made at 0.9.0 and [`Readiness`] at 0.12.0, and for the same reason: the
2558/// member after this one should not be a lockstep event across three renderers.
2559#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2560#[non_exhaustive]
2561pub enum Region<'a> {
2562    /// A full-width strip with a title slot and an actions cluster, either of
2563    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
2564    /// `.header` and `.detail-header` are all this, differing only in which
2565    /// slots they fill.
2566    Band,
2567    /// A persistent column beside the content, holding navigation.
2568    Sidebar,
2569    /// A region of content with its own scroll.
2570    Pane,
2571    /// Things that belong together, and nothing else.
2572    ///
2573    /// The block [`Heading::Section`] has been naming since 0.2.0 without the
2574    /// vocabulary being able to contain it. A section heading is a leaf sitting
2575    /// *beside* the things it names, so nothing said where a section started or
2576    /// ended and a renderer learned one had ended only because the next heading
2577    /// arrived.
2578    ///
2579    /// # The measurement
2580    ///
2581    /// 41 [`Heading::Section`] sites across the ten screens described through
2582    /// the router, not one of them contained. audiofiles' settings screen is the
2583    /// clearest: one pane holding a heading, a field, a heading, two toggles, a
2584    /// heading, a toggle and a heading, which is four sections and no
2585    /// containers. Under the hand-written CSS the ports are replacing the same
2586    /// block is spelled `.settings-section` in goingson, `.form-section` and
2587    /// `.content-section` in the MNW server, `.help-section` in Balanced
2588    /// Breakfast: three apps, four names, one shape.
2589    ///
2590    /// # Why the existing members were the wrong answer
2591    ///
2592    /// [`Pane`](Self::Pane) is what apps reached for, and it is 28 of the 45
2593    /// regions in the described screens. It claims a scroll of its own and
2594    /// [`Depth::Well`], so four settings groups inside a pane are four wells
2595    /// inside a well and four scroll contexts. Neither claim is true of a group.
2596    ///
2597    /// [`Widget`](Self::Widget) is wrong from the other side. Its own docs say a
2598    /// widget is never how a primitive gets added by the back door, and a run of
2599    /// related controls under a heading is furniture any app would have, which
2600    /// is the generic-against-bespoke bar a primitive has to clear.
2601    ///
2602    /// # What it does not carry
2603    ///
2604    /// **A heading.** A group usually has one and it is an ordinary node in the
2605    /// body, the way it already was. A group of related toggles with no heading
2606    /// is a real thing and a mandatory slot would forbid it.
2607    ///
2608    /// **A depth.** [`Depth::Flat`], on [`Bespoke`](Self::Bespoke)'s reasoning:
2609    /// it inherits, and an app that wants its group in a well puts it in a
2610    /// [`Pane`](Self::Pane), which composes rather than adding a knob here.
2611    ///
2612    /// **A colour.** Distinguishing sibling groups by colour is the thing this
2613    /// member was asked for and it is deliberately not stated here. The
2614    /// description says these things belong together; which of the theme's
2615    /// categorical colours a renderer reaches for, and whether it reaches for
2616    /// one at all, is derived from sibling order at the renderer. A terminal
2617    /// that tints nothing and separates with a rule is honouring this.
2618    Group,
2619    /// Two panes side by side, where the left chooses what the right shows.
2620    Split,
2621    /// Peer regions across, all of them equals.
2622    ///
2623    /// A kanban board's columns, and the shape [`Split`](Self::Split) is not:
2624    /// a split's two panes stand in a master-detail relationship, where the
2625    /// left chooses what the right shows. These choose nothing about each
2626    /// other. Each is a whole region and the set is the arrangement.
2627    ///
2628    /// # What it does not carry
2629    ///
2630    /// **How many.** The children say, and a count here would be a second
2631    /// source for something the description already states by containing them.
2632    ///
2633    /// **How wide.** Peers are equal by definition, so there is no [`Share`] to
2634    /// state. A board whose columns wanted different widths would be a
2635    /// different member, and no app has one.
2636    ///
2637    /// **What happens when there is no room.** Scroll across, wrap, or collapse
2638    /// to one column at a time: all three are right on some host, none is
2639    /// derivable from the description, and every one of them is presentation.
2640    /// A terminal that stacks them vertically is honouring this, not degrading
2641    /// it.
2642    ///
2643    /// # Why it is not an `Arrangement`
2644    ///
2645    /// [`Arrangement`] is the page's shape, and a board is usually a region
2646    /// *inside* a page that also has a band over it. Naming it here composes;
2647    /// naming it there would make a screen either a board or a list-detail and
2648    /// never a band above a board. It also keeps [`Arrangement::share`]
2649    /// meaningful, which a peer arrangement has no answer for.
2650    Columns,
2651    /// A set of panes, one visible at a time, and a [`Selector::Tabs`] that
2652    /// chooses between them.
2653    ///
2654    /// Says nothing about where the strip sits. A row over the panes, a column
2655    /// beside them, a wrapped run of links under them: all three are the same
2656    /// member drawn by a renderer that knows its host, the way the strip's
2657    /// overflow is.
2658    TabGroup,
2659    /// Content over a scrim, taking input until dismissed.
2660    Modal,
2661    /// A region this crate names the *place* of and nothing else. The app owns
2662    /// what goes in it.
2663    ///
2664    /// The escape hatch, and the thing that keeps the description honest about
2665    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
2666    /// paint interaction over the timeline are not describable here and are not
2667    /// going to become describable: a description expressive enough to produce
2668    /// a timeline is a widget library wearing a description's name.
2669    ///
2670    /// But a screen containing one still has to be a screen. Without this
2671    /// member the description covers only the boring screens, and the four that
2672    /// make goingson worth using would need a second, undescribed path beside
2673    /// the router. Two paths is how the vocabulary starts drifting from the app
2674    /// again, which is the exact failure this crate exists to end.
2675    ///
2676    /// So the description says "a thing called `day-plan` goes here" and stops.
2677    /// The name is opaque: this crate never interprets it, and no renderer is
2678    /// expected to know what it means beyond handing the space over.
2679    Bespoke {
2680        /// What the app calls it. Never interpreted here.
2681        name: &'a str,
2682    },
2683    /// A named assembly of things the vocabulary already says.
2684    ///
2685    /// The third tier, between a primitive and [`Bespoke`](Self::Bespoke).
2686    /// Stated by Max 2026-08-12 answering the carousel: "something in between a
2687    /// primitive and a bespoke interface, like a widget, which is just an
2688    /// assembly of primitives." Full note: wiki `widget-tier`.
2689    ///
2690    /// # What separates it from the two members either side
2691    ///
2692    /// A primitive is a thing every renderer draws from scratch, and the test
2693    /// it has to pass is that every host has an honest answer. A carousel fails
2694    /// that test — a terminal has no carousel — which is the same refusal
2695    /// `Node::Html` got and is why the carousel sat unsayable for months.
2696    ///
2697    /// [`Bespoke`](Self::Bespoke) fails it from the other side. Bespoke is for
2698    /// what one app owns and nobody will build twice, and it carries *no*
2699    /// contents: the description names the place and stops. A carousel is
2700    /// furniture any app would have, and every part of it — an ordered set of
2701    /// frames, a position, prev and next, a strip of position indicators — is
2702    /// already sayable. Only the assembly had no name.
2703    ///
2704    /// So this member is the pair the other two are not: a name **and**
2705    /// contents. The contents are the assembly, in the region's own body, said
2706    /// in members that already exist.
2707    ///
2708    /// # Why the name does not have to be understood
2709    ///
2710    /// A renderer that recognises the name draws it the way its host does it: a
2711    /// carousel in a webview, a pager with a count in a terminal, a selector in
2712    /// egui. A renderer that does not recognise it walks the body, which is
2713    /// primitives all the way down and which it can already draw.
2714    ///
2715    /// That is what lets the widget set be **open** without every renderer
2716    /// knowing every widget. An unrecognised widget degrades to its assembly
2717    /// instead of failing, so a second or third party can name one without
2718    /// three renderers releasing in lockstep to accept it. Contrast
2719    /// [`Bespoke`](Self::Bespoke), which no renderer can degrade: there is
2720    /// nothing under it to fall back to.
2721    ///
2722    /// # What it does not do
2723    ///
2724    /// A widget is an assembly of things the vocabulary *already* says, so it
2725    /// buys no expressive power. Anything needing a member the vocabulary does
2726    /// not have is a finding about the vocabulary, and the answer to a finding
2727    /// is to add the member. A widget is never the way a primitive gets added
2728    /// by the back door.
2729    ///
2730    /// This used to say "it does not make a timeline describable, and the
2731    /// refusal in the crate header stands unchanged". The timeline is
2732    /// describable as of 2026-08-15 -- see [`Track`] -- and it got there the
2733    /// way the paragraph above says it should have: by adding the two members
2734    /// that were missing, not by dressing the screen up as an assembly.
2735    Widget {
2736        /// What the assembly is called. This crate never interprets it, and a
2737        /// renderer is free not to know it.
2738        name: &'a str,
2739    },
2740}
2741
2742impl<'a> Region<'a> {
2743    /// How the region sits on what is behind it.
2744    #[must_use]
2745    pub const fn depth(self) -> Depth {
2746        match self {
2747            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
2748            // Flat, and it inherits. A group says its contents belong together
2749            // and says nothing about the surface they sit on, so a group in a
2750            // pane is in a well and a group on the page is on the page. An app
2751            // wanting one lifted puts it in a `Pane`.
2752            Self::Group => Depth::Flat,
2753            // Flat, and it is the container rather than the columns. Each
2754            // column is its own region and brings its own depth; a well here
2755            // would put a second edge around a row of wells.
2756            Self::Columns => Depth::Flat,
2757            // A pane is looked into, the same as a table body or a tag tree.
2758            Self::Pane => Depth::Well,
2759            Self::Modal => Depth::Raised,
2760            // Flat because it inherits: a bespoke region takes the depth of
2761            // whatever frames it. An app that wants its timeline in a well puts
2762            // it in a `Pane`, which composes rather than adding a knob here.
2763            //
2764            // A widget inherits for the same reason and it matters more here,
2765            // because a widget is drawn by whichever renderer recognises it. A
2766            // depth set here would be this crate deciding that a carousel is
2767            // raised on every host, which is the kind of value the deferral
2768            // rule exists to refuse.
2769            Self::Bespoke { .. } | Self::Widget { .. } => Depth::Flat,
2770        }
2771    }
2772
2773    /// Whether this crate can say anything about the region's contents.
2774    ///
2775    /// A renderer walks the description and hands every region it understands
2776    /// to the right drawing code. This is how it tells the two apart, and the
2777    /// reason it is a method rather than a `matches!` at each renderer: there
2778    /// is exactly one opaque member and there should stay exactly one.
2779    ///
2780    /// [`Widget`](Self::Widget) is described, and that is the whole of what
2781    /// separates it from [`Bespoke`](Self::Bespoke) here. Both carry a name
2782    /// this crate never interprets; only one of them carries contents under it.
2783    /// A renderer that does not recognise a widget's name still walks its body,
2784    /// so there is nothing for it to hand over and nothing it cannot draw.
2785    #[must_use]
2786    pub const fn described(self) -> bool {
2787        !matches!(self, Self::Bespoke { .. })
2788    }
2789
2790    /// The name an app gave this region, if it gave one.
2791    ///
2792    /// [`Bespoke`](Self::Bespoke) and [`Widget`](Self::Widget) are the two
2793    /// members that carry a name, for two different purposes: one says what the
2794    /// app will fill the space with, the other says what the assembly under it
2795    /// is called. A renderer dispatching on either wants the string without
2796    /// caring which member it came from, and writing that `matches!` at each
2797    /// renderer is how the two drift apart.
2798    #[must_use]
2799    pub const fn name(self) -> Option<&'a str> {
2800        match self {
2801            Self::Bespoke { name } | Self::Widget { name } => Some(name),
2802            // Spelled out rather than a wildcard, so a member added later has
2803            // to answer whether it carries a name instead of inheriting `None`
2804            // by sitting under a `_`.
2805            Self::Band
2806            | Self::Sidebar
2807            | Self::Pane
2808            | Self::Group
2809            | Self::Split
2810            | Self::Columns
2811            | Self::TabGroup
2812            | Self::Modal => None,
2813        }
2814    }
2815}
2816
2817/// How many of a region's children are visible at once.
2818///
2819/// `4dcd241b`. Three findings turned out to be one sentence the vocabulary
2820/// could not say: *this region holds several children and shows some of them,
2821/// and the reader can change which.* [`Region::TabGroup`] existed with nothing
2822/// saying which tab was open, a carousel had nothing saying which frame was up,
2823/// and a disclosure had nothing saying whether its one child was showing at all.
2824///
2825/// Because the fact lived nowhere, a renderer had two moves: hardcode a widget
2826/// name, or draw every child. That is what put per-widget code in renderers, and
2827/// it was the missing member rather than the widget tier that put it there.
2828///
2829/// # What is here and what is not
2830///
2831/// The *kind*, and only the kind. Which child is currently up is the current
2832/// answer, and a layer that defers every address does not hold the current
2833/// answer either — the split [`Selector`] already makes, where this crate says
2834/// what kind of chooser a thing is and the router says which option is picked.
2835/// So a holder of regions carries the index and the per-child label beside this.
2836///
2837/// # What a renderer does with it
2838///
2839/// Derives its chrome, once, for every widget rather than per name:
2840///
2841/// - Children carrying labels get a strip of the labels, the current one marked.
2842/// - Children carrying none get previous, position, next.
2843/// - [`AtMostOne`](Self::AtMostOne) over one child gets a summary line that
2844///   opens.
2845///
2846/// The name on [`Region::Widget`] survives as app vocabulary, for a renderer
2847/// that wants to do something *special* with one, which is what it should have
2848/// been from the start.
2849///
2850/// Degradation runs the way it already did: a renderer ignoring this draws every
2851/// child, which is more content rather than less.
2852#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2853#[non_exhaustive]
2854pub enum Showing {
2855    /// Every child, in order. What every region did before this existed.
2856    #[default]
2857    All,
2858    /// Exactly one. A carousel, a tab group.
2859    One,
2860    /// One, or none. A disclosure, which is closed until it is opened.
2861    AtMostOne,
2862}
2863
2864impl Showing {
2865    /// Whether the reader can change which child is up.
2866    ///
2867    /// The question every renderer's region arm asks before deriving any
2868    /// chrome, and a method rather than a `matches!` at each renderer for
2869    /// [`Region::name`]'s reason: three renderers writing the same comparison is
2870    /// how they come to disagree about a member added later.
2871    #[must_use]
2872    pub const fn selective(self) -> bool {
2873        !matches!(self, Self::All)
2874    }
2875
2876    /// Whether showing nothing is a legal state.
2877    ///
2878    /// True only for [`AtMostOne`](Self::AtMostOne). A renderer needs this to
2879    /// know whether its control closes as well as moves: a carousel's row moves
2880    /// between frames and never reaches empty, and a disclosure's summary line
2881    /// is the same control wearing its closed state.
2882    #[must_use]
2883    pub const fn dismissible(self) -> bool {
2884        matches!(self, Self::AtMostOne)
2885    }
2886}
2887
2888/// A window onto a sequence: where it starts, how much it covers, and how long
2889/// the sequence is when that is known.
2890///
2891/// The mechanism under two things the vocabulary deliberately keeps apart. A
2892/// carousel is a window of one frame over children that are all present; a
2893/// paged list is a window of a page over rows most of which were never fetched.
2894/// Those are different facts and they stay different types — [`Showing`] says
2895/// which child is up, [`Paging`] says where a reader is in a query — but the
2896/// arithmetic underneath is one piece of code, so a terminal and a browser
2897/// cannot come to disagree about which frame is last.
2898///
2899/// # Why `of` is optional and `count` is not
2900///
2901/// `count` is what is on screen and is therefore always known. `of` is the
2902/// length of the thing being windowed, and a host that cannot count says so by
2903/// leaving it empty **for the life of the screen**. It is never "not counted
2904/// yet": see "First paint is final paint" in the crate header. A total that
2905/// turns up on a later pass widens the text that prints it.
2906///
2907/// # Clamping
2908///
2909/// Every derivation clamps rather than refusing, and a zero `count` answers
2910/// `None` rather than dividing. A window past the end is a bug in the host, and
2911/// a renderer that answered it by drawing nothing would report a region that
2912/// vanished, which is the hardest kind of bug to find from what is on screen.
2913/// [`Share::percent`] clamps for the same reason.
2914#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2915pub struct Window {
2916    /// The index into the sequence where the window starts.
2917    pub from: usize,
2918    /// How many the window covers. One, for a carousel.
2919    pub count: usize,
2920    /// How long the sequence is, when the host can say.
2921    pub of: Option<usize>,
2922}
2923
2924impl Window {
2925    /// A window of `count`, starting at `from`, over a sequence of unknown
2926    /// length.
2927    #[must_use]
2928    pub const fn new(from: usize, count: usize) -> Self {
2929        Self {
2930            from,
2931            count,
2932            of: None,
2933        }
2934    }
2935
2936    /// How long the sequence is.
2937    #[must_use]
2938    pub const fn of(mut self, of: usize) -> Self {
2939        self.of = Some(of);
2940        self
2941    }
2942
2943    /// One item of a sequence whose length is known. A carousel frame.
2944    #[must_use]
2945    pub const fn frame(at: usize, of: usize) -> Self {
2946        Self {
2947            from: at,
2948            count: 1,
2949            of: Some(of),
2950        }
2951    }
2952
2953    /// Which window this is, counting from zero.
2954    ///
2955    /// `None` when `count` is zero, which is the only input with no answer
2956    /// rather than a clamped one.
2957    #[must_use]
2958    pub const fn index(self) -> Option<usize> {
2959        if self.count == 0 {
2960            return None;
2961        }
2962        Some(self.from / self.count)
2963    }
2964
2965    /// How many windows the sequence holds.
2966    ///
2967    /// `None` unless both the length and a non-zero `count` are known. A
2968    /// partial answer here would be a renderer drawing "of 0".
2969    #[must_use]
2970    pub const fn windows(self) -> Option<usize> {
2971        match self.of {
2972            Some(of) if self.count > 0 => Some(of.div_ceil(self.count)),
2973            _ => None,
2974        }
2975    }
2976
2977    /// Whether anything sits before this window.
2978    #[must_use]
2979    pub const fn has_before(self) -> bool {
2980        self.from > 0
2981    }
2982
2983    /// How many sit after this window, when the length is known.
2984    ///
2985    /// Here rather than in each renderer for [`Showing::selective`]'s reason:
2986    /// three of them writing the same subtraction is how they come to disagree,
2987    /// and this one has an underflow in it for whoever writes it fourth.
2988    #[must_use]
2989    pub const fn after(self) -> Option<usize> {
2990        match self.of {
2991            Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
2992            None => None,
2993        }
2994    }
2995
2996    /// Whether anything sits after it.
2997    ///
2998    /// `true` when the length is unknown: a host that cannot count cannot rule
2999    /// out more, and offering a way forward that turns out to be empty is the
3000    /// cheaper of the two mistakes.
3001    #[must_use]
3002    pub const fn has_after(self) -> bool {
3003        match self.of {
3004            Some(of) => self.from.saturating_add(self.count) < of,
3005            None => true,
3006        }
3007    }
3008
3009    /// The window with `from` brought inside the sequence.
3010    ///
3011    /// A no-op when the length is unknown, since there is nothing to clamp
3012    /// against.
3013    #[must_use]
3014    pub const fn clamped(mut self) -> Self {
3015        if let Some(of) = self.of
3016            && self.from >= of
3017        {
3018            // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
3019            // window would otherwise clamp onto the end rather than inside it.
3020            let step = if self.count == 0 { 1 } else { self.count };
3021            self.from = of.saturating_sub(step);
3022        }
3023        self
3024    }
3025}
3026
3027/// Where a reader is in a set that arrived in parts.
3028///
3029/// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
3030/// window at the top level on purpose, because the intent differs and a call
3031/// site should say which one it means, while the arithmetic below is shared so
3032/// the two cannot drift apart.
3033///
3034/// # The two idioms, and which one a renderer may draw
3035///
3036/// Load-more and numbered pages are both this type. Which is honest is
3037/// [`paged`](Self::paged): a set whose page size is known can be drawn as
3038/// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
3039/// forward. Saying it here rather than letting each renderer guess is the point
3040/// — three renderers inferring it from the numbers is how they come to disagree.
3041///
3042/// # What it does not carry
3043///
3044/// No addresses. `makeover-layout` cannot name an action, and the way to ask for
3045/// the next part is the host's: `quasi_router` pairs this with the addresses the
3046/// same way `Row` pairs its parts with `Row::activate`. That split is the reason
3047/// this type is reusable by a carousel, which has nothing to ask.
3048#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3049pub struct Paging {
3050    /// The window onto the set.
3051    pub window: Window,
3052    /// Whether the parts are a fixed size, and so whether pages are countable.
3053    ///
3054    /// `false` for load-more, where the window simply grew and "page 2" would
3055    /// name nothing.
3056    pub paged: bool,
3057}
3058
3059impl Paging {
3060    /// A page of `per`, starting at `from`.
3061    #[must_use]
3062    pub const fn pages(from: usize, per: usize) -> Self {
3063        Self {
3064            window: Window::new(from, per),
3065            paged: true,
3066        }
3067    }
3068
3069    /// The first `shown`, with more behind them.
3070    ///
3071    /// The load-more shape: the window starts at the beginning and grows, so
3072    /// there is no page to number.
3073    #[must_use]
3074    pub const fn more(shown: usize) -> Self {
3075        Self {
3076            window: Window::new(0, shown),
3077            paged: false,
3078        }
3079    }
3080
3081    /// How many there are altogether.
3082    ///
3083    /// Left unsaid by a host that cannot count, and left unsaid **for good**:
3084    /// a total arriving later widens whatever prints it. See "First paint is
3085    /// final paint" in the crate header.
3086    #[must_use]
3087    pub const fn of(mut self, of: usize) -> Self {
3088        self.window = self.window.of(of);
3089        self
3090    }
3091
3092    /// Which page this is, counting from one, when pages are countable.
3093    ///
3094    /// One-based because it is read aloud. [`Window::index`] is the zero-based
3095    /// form for anyone indexing with it.
3096    #[must_use]
3097    pub const fn page(self) -> Option<usize> {
3098        if !self.paged {
3099            return None;
3100        }
3101        match self.window.index() {
3102            Some(index) => Some(index + 1),
3103            None => None,
3104        }
3105    }
3106
3107    /// How many pages there are, when that is countable.
3108    #[must_use]
3109    pub const fn pages_total(self) -> Option<usize> {
3110        if !self.paged {
3111            return None;
3112        }
3113        self.window.windows()
3114    }
3115
3116    /// How many are on screen.
3117    #[must_use]
3118    pub const fn shown(self) -> usize {
3119        self.window.count
3120    }
3121
3122    /// How many there are, when the host counted.
3123    #[must_use]
3124    pub const fn total(self) -> Option<usize> {
3125        self.window.of
3126    }
3127
3128    /// How many are not shown yet, when the host counted.
3129    ///
3130    /// The figure a load-more control puts in its label. `None` is the honest
3131    /// and common case: a set that cannot say how many more there are still has
3132    /// a way to ask for them.
3133    #[must_use]
3134    pub const fn remaining(self) -> Option<usize> {
3135        self.window.after()
3136    }
3137
3138    /// Whether there is anything further on.
3139    #[must_use]
3140    pub const fn has_more(self) -> bool {
3141        self.window.has_after()
3142    }
3143
3144    /// Whether there is anything back the other way.
3145    #[must_use]
3146    pub const fn has_previous(self) -> bool {
3147        self.window.has_before()
3148    }
3149}
3150
3151/// How much of the width an arrangement's first region takes.
3152///
3153/// `e0fd485e`. Nothing said how much room a region got, so every renderer
3154/// invented its own number and two hosts showing one screen disagreed about
3155/// its proportions. A webview never noticed, because the stylesheet answered
3156/// once for every consumer; a terminal has no stylesheet to inherit from, so
3157/// `quasi-tui` picked 24 columns for a sidebar and 40% for a list pane and
3158/// neither had anything behind it.
3159///
3160/// # A proportion, never a unit
3161///
3162/// Held as a percentage, and that is the only form it comes in. A description
3163/// carrying columns would be describing a terminal and one carrying pixels a
3164/// webview, and the whole point is that both honour the same fact: a terminal
3165/// resolves it against a column count, a webview writes it into a grid, and
3166/// neither has to know what the other did.
3167///
3168/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
3169/// guess. Geometry is scales that answer the same for every screen and takes
3170/// no input that would let a sidebar screen differ from a list-detail one.
3171///
3172/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
3173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3174pub struct Share(u8);
3175
3176impl Share {
3177    /// What a sidebar takes, when nobody says otherwise.
3178    ///
3179    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
3180    /// 96-column terminal and about a fifth of a wide one; a quarter is that
3181    /// number said in the form a webview can honour too.
3182    pub const SIDEBAR: Self = Self(25);
3183
3184    /// What the list side of a list-detail takes, when nobody says otherwise.
3185    ///
3186    /// `quasi-tui`'s 40%, which was already a proportion and is the one number
3187    /// this member did not have to invent.
3188    pub const LIST: Self = Self(40);
3189
3190    /// A share of the width, as a percentage.
3191    ///
3192    /// Clamped to 5..=95 rather than refused. A description that asked for a
3193    /// region of nothing is a bug in the app, and a renderer drawing a region
3194    /// zero cells wide reports it as a region that vanished, which is the
3195    /// hardest kind of bug to find from what is on the screen.
3196    #[must_use]
3197    pub const fn percent(percent: u8) -> Self {
3198        Self(if percent < 5 {
3199            5
3200        } else if percent > 95 {
3201            95
3202        } else {
3203            percent
3204        })
3205    }
3206
3207    /// The share as a percentage.
3208    #[must_use]
3209    pub const fn as_percent(self) -> u8 {
3210        self.0
3211    }
3212
3213    /// This share of a width, rounded to the nearest whole unit.
3214    ///
3215    /// What a terminal calls to turn the proportion into columns. At least one,
3216    /// because a region the description named should be visible: a screen
3217    /// 3 columns wide is unusable either way, and a sidebar that is there is a
3218    /// truer picture of the description than a sidebar that is not.
3219    #[must_use]
3220    pub const fn of(self, whole: u16) -> u16 {
3221        let taken = (whole as u32 * self.0 as u32).div_ceil(100);
3222        if taken == 0 { 1 } else { taken as u16 }
3223    }
3224}
3225
3226/// How a screen is laid out.
3227///
3228/// Three, and no one of them is a variant of another. goingson is list-detail,
3229/// Balanced Breakfast is sidebar plus content, and MNW's embeds are one region
3230/// filling the document. The tab group is a modifier rather than a member,
3231/// because goingson uses it *inside* the same content region rather than
3232/// instead of one.
3233///
3234/// This exists at all because the router has to be able to express a screen
3235/// rather than only a control. Discovering the arrangement layer missing after
3236/// the renderers exist is a redesign; naming two now is a morning.
3237///
3238/// # Why the share rides here
3239///
3240/// `e0fd485e`. A share is per-arrangement: how much a sidebar takes and how
3241/// much a list side takes are different questions, and this enum is the only
3242/// thing that knows which one is being asked. Geometry would have had to invent
3243/// a channel to be told.
3244///
3245/// [`list_detail`](Self::list_detail) and
3246/// [`sidebar_content`](Self::sidebar_content) build these with the default
3247/// shares, so a screen that has no opinion does not have to have one.
3248#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3249pub enum Arrangement {
3250    /// A list that chooses what the detail beside it shows.
3251    ListDetail {
3252        /// Whether the detail side is a [`Region::TabGroup`].
3253        tabbed: bool,
3254        /// How much of the width the list side takes.
3255        share: Share,
3256    },
3257    /// Navigation down the side, content filling the rest.
3258    SidebarContent {
3259        /// How much of the width the sidebar takes.
3260        share: Share,
3261    },
3262    /// One region, filling the document.
3263    ///
3264    /// `52699de6`. The other two are both about dividing a width between two
3265    /// regions, so a screen that is one region had to borrow one of them and
3266    /// then undo it: MNW's five embeds said `list_detail(title, false)` and the
3267    /// host spent a `display: block` cancelling the grid that produced. A host
3268    /// writing CSS to contradict the description rather than to add to it is
3269    /// the thing this member ends.
3270    ///
3271    /// Carries no [`Share`], because there is no division to describe. That is
3272    /// why [`share`](Self::share) answers `None` here.
3273    Single,
3274}
3275
3276impl Arrangement {
3277    /// A list and a detail beside it, at the default share.
3278    #[must_use]
3279    pub const fn list_detail(tabbed: bool) -> Self {
3280        Self::ListDetail {
3281            tabbed,
3282            share: Share::LIST,
3283        }
3284    }
3285
3286    /// A sidebar and content beside it, at the default share.
3287    #[must_use]
3288    pub const fn sidebar_content() -> Self {
3289        Self::SidebarContent {
3290            share: Share::SIDEBAR,
3291        }
3292    }
3293
3294    /// How much of the width the first region takes, when two regions divide it.
3295    ///
3296    /// `None` for [`Single`](Self::Single): one region takes the width, and a
3297    /// renderer that asked how to divide it was asking the wrong question. It
3298    /// answers `Option` rather than a full-width `Share` so that a host cannot
3299    /// quietly draw a one-region screen as a grid with an empty second column.
3300    #[must_use]
3301    pub const fn share(self) -> Option<Share> {
3302        match self {
3303            Self::ListDetail { share, .. } | Self::SidebarContent { share } => Some(share),
3304            Self::Single => None,
3305        }
3306    }
3307
3308    /// The same arrangement, at this share.
3309    ///
3310    /// [`Single`](Self::Single) is returned unchanged: it has no division to
3311    /// set, so a share named for it is a statement about nothing rather than an
3312    /// error worth refusing a screen over.
3313    #[must_use]
3314    pub const fn with_share(self, share: Share) -> Self {
3315        match self {
3316            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
3317            Self::SidebarContent { .. } => Self::SidebarContent { share },
3318            Self::Single => Self::Single,
3319        }
3320    }
3321}
3322
3323/// How wide the content of a whole screen runs.
3324///
3325/// `0eccff0d`, and [`Share`]'s sibling one level up: that one says how a
3326/// screen's width is divided between regions, this says how much of the window
3327/// the screen uses in the first place. Both are the description's, which is
3328/// what answering the two together settled.
3329///
3330/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
3331/// three mutually exclusive classes and the choice is per screen. GoingsOn
3332/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
3333/// token for it, so three apps were solving one thing by hand.
3334///
3335/// # Named for the measure, not for MNW's classes
3336///
3337/// A renderer that is not a browser has to answer this too, and `padded-page`
3338/// tells a terminal nothing. The three say how wide the text runs, which is a
3339/// question every renderer can answer: a webview with a `max-width`, a terminal
3340/// with gutters, an immediate-mode frame with its own width.
3341///
3342/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
3343/// the measurement found three, and a fourth arriving should not be a lockstep
3344/// release across nine repos.
3345#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3346#[non_exhaustive]
3347pub enum Measure {
3348    /// The whole width, with gutters. The default, and 53 of the 69.
3349    ///
3350    /// What a dashboard, a table and a settings screen want: the content is
3351    /// wide because the content *is* wide, and constraining it would waste the
3352    /// window.
3353    #[default]
3354    Wide,
3355    /// Capped at a comfortable page width, centred. 13 of the 69.
3356    ///
3357    /// A form, a sign-in, a purchase. Content that does not get better by
3358    /// getting wider, but is not prose either.
3359    Contained,
3360    /// Capped at a line length that reads well. 3 of the 69.
3361    ///
3362    /// Prose. The narrowest of the three, and the one with a reason outside
3363    /// taste: a line of text past roughly 75 characters costs the reader the
3364    /// return sweep.
3365    Reading,
3366}
3367
3368impl Measure {
3369    /// A stable name, for a renderer that needs to spell it.
3370    ///
3371    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
3372    /// renderers spelling one enum is three chances to spell it differently.
3373    #[must_use]
3374    pub const fn as_str(self) -> &'static str {
3375        match self {
3376            Self::Wide => "wide",
3377            Self::Contained => "contained",
3378            Self::Reading => "reading",
3379        }
3380    }
3381}
3382
3383/// What kind of value a form field takes.
3384///
3385/// The union of the two vocabularies that diverged, which is what triggered
3386/// this crate. They have since converged on their own: both apps now have a
3387/// `renderFormField` emitting the same anatomy, and what is left differing is
3388/// the kind set, the error shape, and whether the return is a string or a node.
3389///
3390/// Validation is deliberately absent. Neither app has a shared story (goingson
3391/// validates after collecting the form data, with per-field transform hooks;
3392/// Balanced Breakfast has `required` and nothing else), and a schema that
3393/// describes fields but not constraints acquires a constraint layer per app,
3394/// which is exactly how the current divergence started. Naming it absent is a
3395/// decision; leaving it unmentioned would not be.
3396/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
3397/// the set keeps growing, so growth must not be a lockstep event. Email, Url
3398/// and Tel arriving in 0.5.0 is the second growth in two releases.
3399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3400#[non_exhaustive]
3401pub enum FieldKind {
3402    /// A single line of text.
3403    Text,
3404    /// A single line of text that must never be echoed, logged or round-tripped
3405    /// through anything that might persist it.
3406    Secret,
3407    /// A number.
3408    Number,
3409    /// A number inside bounds the user drags across, where the range being
3410    /// visible is the point.
3411    ///
3412    /// Not [`Number`](Self::Number) with [`min`](Field::min) and
3413    /// [`max`](Field::max), which is the reading to resist and is the same
3414    /// resistance [`Radio`](Self::Radio) needed against `Select`. A bounded
3415    /// number and a validated number are different *questions*. A validated
3416    /// number is typed and can be wrong: the bounds are a rule the answer is
3417    /// checked against, and being told "must be at least 1" afterwards is the
3418    /// normal course of it. A range cannot be out of range at all, because the
3419    /// bounds are the control's extent rather than a rule, and the two ends are
3420    /// what the question means — audiofiles asks for a classifier threshold
3421    /// between 0 and 1, where 0 is never and 1 is only-on-certainty, and a typed
3422    /// 0.72 says nothing without both ends on screen beside it.
3423    ///
3424    /// A renderer cannot infer which one is meant from `min`/`max` alone, which
3425    /// is why this is a kind and not an inference: goingson's `min="1"` duration
3426    /// is a validated number and would become a slider.
3427    ///
3428    /// The membership test passes without stretching: a webview emits
3429    /// `<input type="range">`, egui has `Slider`, a terminal draws a bar and
3430    /// takes arrow keys, a CLI takes a bounded argument.
3431    ///
3432    /// # It owes its bounds
3433    ///
3434    /// [`min`](Field::min) and [`max`](Field::max) are `Option` for every other
3435    /// kind and are **required** here, in the sense the description can require
3436    /// anything: [`Field::bounded`] is the check, and a range missing one has no
3437    /// extent for a renderer to draw. What a renderer does with an unbounded
3438    /// range is its own call and both answers are honest — fall back to a typed
3439    /// number, or pick a host default — so this is stated rather than enforced,
3440    /// the way every other constraint here is.
3441    ///
3442    /// [`Field::step`] is the third fact and is genuinely optional: absent, the
3443    /// host's own granularity stands.
3444    ///
3445    /// Added 0.28.0, from audiofiles' classifier thresholds and storage cap
3446    /// picker (`fb93426b`), where four sliders were hand-rolled against a
3447    /// vocabulary that could not say what they were.
3448    Range,
3449    /// One question with two ends: a lower value and an upper one, submitted
3450    /// under two names.
3451    ///
3452    /// "Show me samples between 90 and 130 BPM" has a single answer with two
3453    /// ends, and the ends constrain each other: a minimum above the maximum is
3454    /// not a wrong value, it is an empty result nobody asked for. Described as
3455    /// two [`Number`](Self::Number) fields that is unsayable — nothing says they
3456    /// are one question, so a renderer draws two controls with two labels and no
3457    /// relationship, and [`Field::error`] can only be attached to one side of a
3458    /// fault that belongs to both.
3459    ///
3460    /// Not [`Range`](Self::Range), which was the reading to resist and the
3461    /// resistance is the same one `Range` itself needed against `Number`. A
3462    /// range describes *one* value inside an extent; this describes two, and the
3463    /// extent is a bound on each rather than the question's meaning. The two
3464    /// come apart in the answer: a range has a value, an interval has a pair,
3465    /// and either end may be absent while the other stands.
3466    ///
3467    /// # It states both names
3468    ///
3469    /// [`Field::name`] is the lower end and [`Field::upper_name`] is the upper
3470    /// one, stated rather than derived. Measured 2026-08-21, the two sites in
3471    /// this tree disagree about affix order — audiofiles submits `bpm_min` /
3472    /// `bpm_max` and the MNW server submits `min_price` / `max_price` — so any
3473    /// derived rule picks one and renames the other's parameters. One member
3474    /// instead of a naming convention this crate would then own forever.
3475    ///
3476    /// Direction is carried by which member the name sits in, so nothing
3477    /// separate says which end is which.
3478    ///
3479    /// # What it does not enforce
3480    ///
3481    /// The crossing rule. A lower end above the upper one is describable here
3482    /// and always was, exactly as an out-of-[`min`](Field::min) number is: this
3483    /// crate carries constraints and never checks them, and deciding a value is
3484    /// wrong stays with whoever validated. What the description buys is that the
3485    /// fault now has one place to be reported rather than two.
3486    ///
3487    /// # Both ends take the same facts
3488    ///
3489    /// [`min`](Field::min), [`max`](Field::max), [`step`](Field::step) and
3490    /// [`unit`](Field::unit) describe the axis rather than one end of it, so
3491    /// they are read once and applied to both. Six of audiofiles' filter axes
3492    /// are exactly this: one extent, one unit, one granularity, two ends.
3493    ///
3494    /// The bounds are optional here, unlike `Range`. They are a rule the answer
3495    /// is checked against rather than the control's extent, which is
3496    /// [`Number`](Self::Number)'s arrangement and not a slider's.
3497    ///
3498    /// Added 0.34.0, ruled by Max 2026-08-21, from audiofiles' six filter axes
3499    /// and the MNW server's price pair.
3500    Interval,
3501    /// An email address.
3502    ///
3503    /// Distinct from [`Text`](Self::Text) because the distinction is not
3504    /// decoration: a webview renderer emits `type="email"`, which on a touch
3505    /// device changes the keyboard that appears and turns on the platform's own
3506    /// validation. goingson ships to iOS, so collapsing this into text costs a
3507    /// keyboard with no `@` on it.
3508    ///
3509    /// Added 0.5.0, from goingson's contact form.
3510    Email,
3511    /// A URL. Same reasoning as [`Email`](Self::Email).
3512    ///
3513    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
3514    Url,
3515    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
3516    /// clearest case of it: the keyboard is a numeric pad rather than letters.
3517    ///
3518    /// Added 0.5.0, from goingson's contact-phone form.
3519    Tel,
3520    /// A calendar day, with no time of day in it.
3521    ///
3522    /// [`Email`](Self::Email)'s argument, and it carries further: a webview
3523    /// emits `type="date"`, which is a native picker, the platform's own
3524    /// validation, and on a touch device the date keyboard. Described as
3525    /// [`Text`](Self::Text) with a hint reading "YYYY-MM-DD", all three are
3526    /// lost and the hint is doing the platform's job in prose.
3527    ///
3528    /// The membership test passes on every host without stretching: a webview
3529    /// and a Tauri app emit the input, egui has a date picker, a terminal
3530    /// prompts for a day and can validate it, a CLI takes an argument.
3531    ///
3532    /// # The value is ISO 8601, `YYYY-MM-DD`
3533    ///
3534    /// Named here rather than left to each host, because a host that picks
3535    /// differently sends a server something it parses differently, and the
3536    /// failure is silent and per-host. It is `<input type="date">`'s own wire
3537    /// format, so the webview renderer owes nothing to honour it and the other
3538    /// hosts have one spelling to meet. [`DATE_FORMAT`] is the constant, and a
3539    /// test asserts this doc and that constant agree.
3540    ///
3541    /// Added 0.15.0, from the MNW server's git access-token expiry
3542    /// (`user_ssh_keys_tab.html`) and six further sites across the server and
3543    /// goingson.
3544    Date,
3545    /// A calendar day and a time of day together.
3546    ///
3547    /// Apart from [`Date`](Self::Date) because the question is different rather
3548    /// than more precise: "which day does this expire" and "at what moment does
3549    /// this publish" are asked by different screens and answered by different
3550    /// controls. A webview emits `type="datetime-local"` for one and
3551    /// `type="date"` for the other, and a host that collapsed them would ask
3552    /// half the tree for a precision it does not want.
3553    ///
3554    /// Both arrived together on measurement rather than on symmetry: 13 sites
3555    /// of each across the MNW server and goingson, and **zero** of `time`,
3556    /// `month` or `week`, which is why those are not here. A member added for a
3557    /// case nobody has is a member designed against nothing, which is
3558    /// [`File`](Self::File)'s reasoning about `accept` applied to a whole
3559    /// member.
3560    ///
3561    /// # The value is `YYYY-MM-DDTHH:MM`, local, with no zone
3562    ///
3563    /// `<input type="datetime-local">`'s own format, and the "local" is the
3564    /// load-bearing half: the value carries no offset and no `Z`, so the moment
3565    /// it names is only fixed once something supplies a zone. That is the app's
3566    /// business and not the description's. Seconds are absent, which is the
3567    /// browser's own default and is left as the rule rather than restated as a
3568    /// constraint. [`DATETIME_FORMAT`] is the constant.
3569    ///
3570    /// [`Field::min`] and [`Field::max`] already take "the host's own spelling
3571    /// of a bound", so a floor of *not in the past* needs nothing new here: it
3572    /// is a string in this same format.
3573    ///
3574    /// Added 0.15.0, from goingson's snooze picker and day planner and the MNW
3575    /// server's publish-at fields.
3576    DateTime,
3577    /// Several lines of text.
3578    Textarea,
3579    /// Several lines of text the user writes markdown in.
3580    ///
3581    /// The editing counterpart of prose a description carries as markdown
3582    /// source, and the reason it can exist at all is the same one that lets the
3583    /// source be carried: editing markdown is editing text, so a terminal, an
3584    /// immediate-mode host and a webview all have an honest answer, and none of
3585    /// them has to refuse. A kind that meant "rich text" in the WYSIWYG sense
3586    /// would have been a document model, and two of the three hosts would have
3587    /// had to draw something they cannot.
3588    ///
3589    /// What the mark buys over [`Textarea`](Self::Textarea) is that a renderer
3590    /// may offer the affordances markdown has and plain text does not — a
3591    /// preview, a syntax pass, a monospaced face for the source — and that a
3592    /// host reading the value back knows what it is holding. A renderer with
3593    /// none of that draws a textarea, which is why this is additive rather than
3594    /// a second control.
3595    ///
3596    /// It says nothing about **when** the value is saved. Autosave is a clock,
3597    /// clocks are not described here, and the four MNW editors this was measured
3598    /// against each keep their own.
3599    ///
3600    /// Sanitising stays where it already is for markdown that is only displayed:
3601    /// with the renderer, at the point markup is produced. Being described is
3602    /// not a safety property, and a host with its own sanitiser and its own
3603    /// content-security posture still owns both.
3604    ///
3605    /// Added 0.30.0, `f8ad0b32`, from four hand-written MNW section editors —
3606    /// `project-sections.js`, `blog-editor.js`, `partial-item-text-editor.js`
3607    /// and `wizard-item-sections.js` — which are one shape written four times.
3608    Rich,
3609    /// One of a fixed set, offered behind a control that shows one at a time.
3610    Select,
3611    /// One of a fixed set, with every option on screen at once.
3612    ///
3613    /// Not a presentation of [`Select`](Self::Select), which is the reading to
3614    /// resist: what differs is a property of the *question*. A choice that is
3615    /// consequential or irreversible has to be readable without opening
3616    /// anything, because a closed control shows one option and hides the rest,
3617    /// and the one it shows is whichever was current before the user had read
3618    /// the alternatives. audiofiles asks whether a library copies samples into
3619    /// its store or references them where they lie — which cannot be changed
3620    /// afterwards — and had already promoted that out of a checkbox by hand,
3621    /// with a comment giving this reason, before the description could say it.
3622    ///
3623    /// It was described here at 0.8.1 as "the one HTML input type this enum was
3624    /// missing", which was not true then and is not true now: `file` arrived at
3625    /// 0.11.0 and `date` and `datetime-local` at 0.15.0. Everything here is
3626    /// still an `<input type=...>`, a `<select>` or a `<textarea>`, and the way
3627    /// this enum grows is by a site being measured rather than by a list being
3628    /// completed, so "the last one" is not a claim it should make again.
3629    ///
3630    /// Added 0.8.1, from audiofiles' Add Library form.
3631    Radio,
3632    /// On or off.
3633    Checkbox,
3634    /// A file the user picks from wherever the host keeps files.
3635    ///
3636    /// Added 0.11.0, `844b5ae0`, from goingson's project-dashboard attachments
3637    /// column. It was filed as a router finding — a control whose destination is
3638    /// a host capability rather than an address — and splitting it is what made
3639    /// it two answers instead of one member satisfying neither. *Opening* a file
3640    /// is a one-way handoff and needs no new API. *Picking* one returns a value
3641    /// into a write, which is a form concern, which is this.
3642    ///
3643    /// The membership test passes on every host and not by a stretch: a Tauri
3644    /// app opens a native picker, a server renders `<input type="file">`, a
3645    /// terminal prompts for a path, a CLI takes an argument. That is closer to
3646    /// [`Email`](Self::Email), which exists because it changes the keyboard,
3647    /// than to anything bespoke.
3648    ///
3649    /// # The four things an upload says, and where each of them lives
3650    ///
3651    /// | axis | where |
3652    /// |---|---|
3653    /// | what it accepts | [`Field::accept`] |
3654    /// | one file or several | [`Field::multiple`] |
3655    /// | where the bytes go | the router's action, not here |
3656    /// | how far along it is | [`Awaiting`] on that action |
3657    ///
3658    /// Only the first two are this crate's, and that split is the answer to
3659    /// "describe an upload in full" rather than a gap in it. A destination is an
3660    /// address and this crate holds no addresses; progress is a live number and
3661    /// a description is built once, so the number is the renderer's to observe
3662    /// against the size [`Awaiting::amount`] carried before the transfer began.
3663    ///
3664    /// # How the file is handed over is the host's
3665    ///
3666    /// A drop area, a button opening a native picker, a path typed at a prompt:
3667    /// all three are the same field, and every measured site has the first. It
3668    /// is not described for the reason no gesture is — this crate owns no
3669    /// coordinates and no pointer, and a terminal that cannot be dropped on
3670    /// would be refusing a description it can otherwise honour completely.
3671    ///
3672    /// The first two were absent until 0.31.0, and the doc here said why: they
3673    /// were measured rather than deferred, `accept` appearing at zero sites in
3674    /// either app. The count was taken over goingson and Balanced Breakfast, and
3675    /// the MNW server is a third consumer with 14 of them. A member designed
3676    /// against nothing is still the rule; the measurement is what changed.
3677    File,
3678    /// Which theme the app wears.
3679    ///
3680    /// The one member here that names a *subject* rather than a shape of
3681    /// answer, and it is worth saying why that is not the door it looks like.
3682    /// Every other kind is a question a screen might ask about anything; this
3683    /// one is a specific question every app in the family asks, once, on its
3684    /// settings screen, and three of them wrote the same control by hand.
3685    ///
3686    /// # It is furniture, and the measurement is what says so
3687    ///
3688    /// The reading to resist is that this is [`Select`](Self::Select) with a
3689    /// grouped option list, and the grouped select is what was rejected to get
3690    /// here (`70028e00`, ruled by Max 2026-08-28). Grouping was measured across
3691    /// the tree first: `optgroup` appears at exactly **one** live site, in the
3692    /// one app not yet ported, and the non-theme grouping count is **zero**.
3693    /// So the recurring thing was never "option lists that group". It was this
3694    /// picker.
3695    ///
3696    /// # What it carries that a select cannot
3697    ///
3698    /// [`Field::themes`] rather than [`Field::options`], because a theme is
3699    /// four facts and an option is two. The two extra facts are the ones no
3700    /// app can supply without redoing work the theme layer has already done:
3701    /// which [`ThemeVariant`] group a theme is in, and how legible its muted
3702    /// text measured. `Choice::new(id, format!("{name} ({variant})"))` is what
3703    /// the three apps had, and it flattens the group into prose and loses the
3704    /// tier entirely.
3705    ///
3706    /// [`Field::follows`] carries the entry that is not a theme.
3707    ///
3708    /// # The cost, stated rather than discovered later
3709    ///
3710    /// This puts one screen's shape into a vocabulary that otherwise holds
3711    /// none, which was the objection raised against it and accepted going in.
3712    /// The mitigation is narrowness: this describes a theme picker, not a
3713    /// general "list the host resolved" mechanism. A second host-resolved list
3714    /// is when that generalisation gets measured, and not before.
3715    ///
3716    /// A renderer that has not heard of it draws a select over
3717    /// [`Field::themes`]' names and loses the grouping, which is the state
3718    /// every app was in before this member. Degrading to the status quo ante
3719    /// is the floor the member is designed against.
3720    ///
3721    /// Added 0.38.0.
3722    Theme,
3723    /// Carried through the form and never shown.
3724    Hidden,
3725}
3726
3727/// The wire format a [`FieldKind::Date`] value takes: ISO 8601, `YYYY-MM-DD`.
3728///
3729/// A constant rather than a sentence in a doc comment, because the reason to
3730/// name the format at all is that a host picking its own would fail silently
3731/// against a server parsing another. A host that cannot emit the native control
3732/// still has one spelling to meet, and can say which one it meant.
3733pub const DATE_FORMAT: &str = "%Y-%m-%d";
3734
3735/// The wire format a [`FieldKind::DateTime`] value takes: `YYYY-MM-DDTHH:MM`,
3736/// local, carrying no zone and no seconds.
3737///
3738/// [`DATE_FORMAT`]'s sibling and there for its reason. The absent zone is a
3739/// property of the value rather than an omission: the moment is not fixed until
3740/// something outside the description supplies one.
3741pub const DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M";
3742
3743impl FieldKind {
3744    /// Whether the value the kind takes is a moment rather than a string.
3745    ///
3746    /// Named once here for the reason [`offers_options`](Self::offers_options)
3747    /// is: two kinds answer yes, and a host that has to parse or format a value
3748    /// needs to ask without spelling the pair out at each renderer. A third
3749    /// temporal kind should land here and nowhere else.
3750    ///
3751    /// The format each one takes is [`DATE_FORMAT`] and [`DATETIME_FORMAT`].
3752    #[must_use]
3753    pub const fn temporal(self) -> bool {
3754        matches!(self, Self::Date | Self::DateTime)
3755    }
3756
3757    /// Whether the field is drawn at all.
3758    #[must_use]
3759    pub const fn visible(self) -> bool {
3760        !matches!(self, Self::Hidden)
3761    }
3762
3763    /// Whether the value must be kept out of logs and diagnostics.
3764    #[must_use]
3765    pub const fn confidential(self) -> bool {
3766        matches!(self, Self::Secret)
3767    }
3768
3769    /// Where the field's own label sits.
3770    ///
3771    /// A checkbox labels itself on the right of the box; everything else takes
3772    /// a label above. Both webview apps already do this and both special-case
3773    /// it inline, which is the tell that it belongs in the description.
3774    ///
3775    /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
3776    /// naming: its *options* each label themselves, but the field still asks a
3777    /// question above them, so the group takes a label like everything else.
3778    #[must_use]
3779    pub const fn labels_itself(self) -> bool {
3780        matches!(self, Self::Checkbox)
3781    }
3782
3783    /// Whether the kind reads [`Field::options`].
3784    ///
3785    /// Two kinds do, so the pair is named once here rather than spelled out at
3786    /// each renderer and again in [`Field::options`]' own doc, where "every
3787    /// kind but `Select`" was true for exactly one release. A third
3788    /// option-taking kind should land here and nowhere else.
3789    #[must_use]
3790    pub const fn offers_options(self) -> bool {
3791        matches!(self, Self::Select | Self::Radio)
3792    }
3793
3794    /// Whether the kind reads [`Field::themes`] and [`Field::follows`].
3795    ///
3796    /// One member answers yes, and it gets a name for
3797    /// [`takes_files`](Self::takes_files)'s reason rather than in spite of
3798    /// being alone: four renderers ask it before they read either member, and
3799    /// a `matches!` per renderer is where the next one goes missing.
3800    ///
3801    /// Deliberately not folded into
3802    /// [`offers_options`](Self::offers_options). A theme picker offers no
3803    /// [`Choice`]es at all, so a renderer walking `options` for it walks an
3804    /// empty slice and draws an empty control.
3805    ///
3806    /// Added 0.38.0.
3807    #[must_use]
3808    pub const fn offers_themes(self) -> bool {
3809        matches!(self, Self::Theme)
3810    }
3811
3812    /// Whether the value runs to more than one line.
3813    ///
3814    /// Named once here for [`temporal`](Self::temporal)'s reason: two kinds
3815    /// answer yes, every renderer has to ask it before it can size anything,
3816    /// and a `matches!` per renderer is the pair drifting apart one member at a
3817    /// time. What a host does with the markdown, if anything, it reads from the
3818    /// kind itself; this is only whether one line is enough.
3819    #[must_use]
3820    pub const fn multiline(self) -> bool {
3821        matches!(self, Self::Textarea | Self::Rich)
3822    }
3823
3824    /// Whether the value is a file the host picks rather than a string typed
3825    /// into a box.
3826    ///
3827    /// One member answers yes, which is [`visible`](Self::visible)'s and
3828    /// [`confidential`](Self::confidential)'s footing rather than a departure
3829    /// from it: the question gets a name because three renderers ask it before
3830    /// they can read [`Field::accept`] or [`Field::multiple`], and a `matches!`
3831    /// per renderer is where a second file-taking kind would go missing.
3832    #[must_use]
3833    pub const fn takes_files(self) -> bool {
3834        matches!(self, Self::File)
3835    }
3836
3837    /// Whether the value is a quantity, so [`Field::unit`] means something.
3838    ///
3839    /// The numeric kinds and nothing else. A date is a quantity in the sense
3840    /// that it is ordered, and it is not one in the sense that matters here:
3841    /// its unit is fixed by the kind, so `Date` carrying `days` would be the
3842    /// description restating what [`kind`](Field::kind) already said.
3843    ///
3844    /// [`takes_files`](Self::takes_files)'s footing, and for its reason: the
3845    /// renderers ask this before they decide where a unit goes, and a
3846    /// `matches!` per renderer is where the next measurable kind goes missing.
3847    ///
3848    /// Added 0.33.0 with [`Field::unit`]. [`Interval`](Self::Interval) joined at
3849    /// 0.34.0: an axis is measured in something and both its ends are in it.
3850    #[must_use]
3851    pub const fn measurable(self) -> bool {
3852        matches!(self, Self::Number | Self::Range | Self::Interval)
3853    }
3854}
3855
3856/// A family of media a file can belong to.
3857///
3858/// Three members, because three is what a media type's own first segment offers
3859/// that a renderer can do anything with. `text` and `application` are families
3860/// too and neither buys a disclosure — there is no preview of an
3861/// `application/octet-stream` — so naming them would be a member added for a
3862/// case nobody has.
3863///
3864/// It is the answer to "which disclosure", not a validation rule.
3865/// [`Field::accept`] is what a host filters on.
3866#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3867#[non_exhaustive]
3868pub enum Family {
3869    /// A still picture.
3870    Image,
3871    /// Sound.
3872    Audio,
3873    /// Moving pictures, with or without sound.
3874    Video,
3875}
3876
3877impl Family {
3878    /// The wildcard media type that means the whole family.
3879    ///
3880    /// `image/*` and its two siblings, which is what the measured sites write
3881    /// and what a webview puts in an `accept` attribute. Named here so the three
3882    /// renderers do not each spell the star.
3883    #[must_use]
3884    pub const fn wildcard(self) -> &'static str {
3885        match self {
3886            Self::Image => "image/*",
3887            Self::Audio => "audio/*",
3888            Self::Video => "video/*",
3889        }
3890    }
3891
3892    /// The family a media type's first segment names, if it is one of these.
3893    ///
3894    /// Case-insensitive on the segment, because a media type is
3895    /// case-insensitive and half the tree writes them lowercase by habit rather
3896    /// than by rule.
3897    #[must_use]
3898    pub fn of_type(media_type: &str) -> Option<Self> {
3899        let (top, _) = media_type.split_once('/')?;
3900        if top.eq_ignore_ascii_case("image") {
3901            Some(Self::Image)
3902        } else if top.eq_ignore_ascii_case("audio") {
3903            Some(Self::Audio)
3904        } else if top.eq_ignore_ascii_case("video") {
3905            Some(Self::Video)
3906        } else {
3907            None
3908        }
3909    }
3910}
3911
3912/// One entry in a file field's accept list.
3913///
3914/// Three shapes rather than a string, and all three are in the measured sites:
3915/// the MNW server writes `image/*`, `image/jpeg,image/png,image/webp`,
3916/// `.zip,.dmg,.exe,.appimage,.deb,.tar.gz,.clap,.vst3` and, in one place,
3917/// `.csv,text/csv`. A single string would carry all of them and answer nothing
3918/// about any of them.
3919///
3920/// # Why the list is not just a filter
3921///
3922/// It is read twice. Once to decide what the picker offers, which any of the
3923/// three shapes serves, and once to decide **which disclosure** the field gets:
3924/// a preview for a picture, a duration or a waveform for a sound. There is one
3925/// upload shape and a media upload is that shape with more of it shown, so the
3926/// accept list is what says which more. [`family`](Self::family) is that
3927/// question answered once here instead of a media-type parser in each renderer.
3928///
3929/// # A suffix names no family, on purpose
3930///
3931/// `.mp3` is audio in fact, and nothing here says so. A suffix-to-family table
3932/// in a published crate is a mapping that goes stale, disagrees with the host's
3933/// own idea of what a file is, and is wrong the first time somebody hands it a
3934/// container. A call site that wants a picture's preview writes
3935/// [`Family::Image`] or `image/jpeg`; a call site listing installer suffixes
3936/// wants no disclosure anyway, which is the measured case.
3937///
3938/// Added 0.31.0, `f7261a5a`.
3939#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3940#[non_exhaustive]
3941pub enum Accepted<'a> {
3942    /// Every file of a family: `image/*` and its siblings.
3943    Family(Family),
3944    /// One media type, written the way a media type is written:
3945    /// `image/jpeg`, `text/csv`.
3946    Type(&'a str),
3947    /// One file-name suffix, written with its leading dot: `.zip`, `.tar.gz`.
3948    ///
3949    /// A suffix and not an extension, because `.tar.gz` is a measured site and
3950    /// is two dots.
3951    Suffix(&'a str),
3952}
3953
3954impl<'a> Accepted<'a> {
3955    /// The family this entry belongs to, when it names one.
3956    ///
3957    /// [`None`] for a [`Suffix`](Self::Suffix) and for any media type outside
3958    /// the three families, which is the honest answer rather than a missing
3959    /// one: the description did not say.
3960    #[must_use]
3961    pub fn family(self) -> Option<Family> {
3962        match self {
3963            Self::Family(family) => Some(family),
3964            Self::Type(media_type) => Family::of_type(media_type),
3965            Self::Suffix(_) => None,
3966        }
3967    }
3968
3969    /// How a host that wants one string writes this entry.
3970    ///
3971    /// A webview's `accept` attribute takes exactly these spellings, and a
3972    /// terminal listing what it will take reads the same words.
3973    #[must_use]
3974    pub const fn as_str(self) -> &'a str {
3975        match self {
3976            Self::Family(family) => family.wildcard(),
3977            Self::Type(text) | Self::Suffix(text) => text,
3978        }
3979    }
3980}
3981
3982/// One option offered by a field [`FieldKind::offers_options`] accepts.
3983///
3984/// Two strings, because the submitted value and the read label are different
3985/// facts and every renderer that has tried to collapse them has had to
3986/// un-collapse them later. `makeover-webview` invented this shape writing its
3987/// form emitter and it is taken here unchanged; moving it down rather than
3988/// re-deriving it is the point, since the second and third renderers were each
3989/// going to arrive at a near-miss of it.
3990/// `#[non_exhaustive]` as of 0.28.0, which every other type here that a
3991/// renderer matches or builds has carried for releases. It was the omission
3992/// that made [`unavailable`](Self::unavailable) a breaking change across 40
3993/// literal sites in six repos, and it arrives with that member so the price is
3994/// paid once and never again.
3995#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3996#[non_exhaustive]
3997pub struct Choice<'a> {
3998    /// What is submitted.
3999    pub value: &'a str,
4000    /// What is read.
4001    pub label: &'a str,
4002    /// Why it cannot be picked right now, when it cannot.
4003    ///
4004    /// One member rather than an `available: bool` beside a reason, and the
4005    /// conflation is the point: an option greyed out with no explanation is a
4006    /// dead end the user cannot act on, and it is exactly the state the app
4007    /// that found this gap had to patch by hand with a line of prose under the
4008    /// control. Making the reason mandatory means the description cannot say
4009    /// the useless half.
4010    ///
4011    /// The option stays in the list. Dropping it is what an app does today, and
4012    /// it costs the user the knowledge that the thing exists at all —
4013    /// audiofiles' multi-sample mode appears on its own once a second sample is
4014    /// dropped, so a user who never sees it never learns what to drop.
4015    ///
4016    /// **Not [`Field::error`], and not [`Field::hint`].** An error is about the
4017    /// answer and a hint is standing help for the whole question; this is about
4018    /// one option among several, which is the level neither of those reaches.
4019    ///
4020    /// **Not disabled-the-state.** `State::Disabled` is about a whole field
4021    /// refusing to answer. This says the field is live and one of its answers
4022    /// is not available yet, which is a different sentence and the reason the
4023    /// tone rule matters here: the *other* options are still usable.
4024    ///
4025    /// Added 0.28.0, from audiofiles' instrument mode selector (`e761833e`).
4026    pub unavailable: Option<&'a str>,
4027    /// The line under the label that says what picking this means.
4028    ///
4029    /// `5e21dcfc`, measured 2026-08-29. A choice between three plans is a
4030    /// choice nobody can make from three names, and until this existed the
4031    /// description had nowhere to put the sentence that made it makeable. What
4032    /// the corpus did instead is the tell: four of the six measured sites fold
4033    /// it into the label — `<strong>Public</strong>: Anyone can see this
4034    /// repository` in MNW's git settings, the same shape in its project-basics
4035    /// AI tier and its cart's currency conversion, and `Mislabeled (wrong AI
4036    /// tier or category)` in its report modal. The described screens do it too,
4037    /// in miniature: `Every 15 minutes (recommended)`, `Reference samples in
4038    /// place (loose-files mode)`. One fact, six spellings, no member.
4039    ///
4040    /// # Where it goes is the host's, and the rule already exists
4041    ///
4042    /// This is [`unavailable`](Self::unavailable)'s question met a third time
4043    /// and it takes the same answer, which is the strongest evidence one member
4044    /// is right rather than two. A radio group has room and gives the line its
4045    /// own element beside the label. A `<select>`'s option takes no elements,
4046    /// no second line and no title a keyboard reaches, so the line runs into
4047    /// the option's own text — exactly as a precondition does, and as a theme's
4048    /// contrast badge does in brackets. A terminal has rows and puts it on one
4049    /// under the option.
4050    ///
4051    /// # Not a price, and that is a measurement rather than a preference
4052    ///
4053    /// The site that asked for this is MNW's fee calculator, whose tier cards
4054    /// carry a name, a price *and* a description, so a second member for the
4055    /// price was on the table. It loses on the count: the tree's other three
4056    /// priced tier lists — `project.html`, `project_paywall.html`,
4057    /// `index.html` — are not option lists at all. Each card carries its own
4058    /// submit, which makes it a region with a heading, a fact and an act, and
4059    /// it is sayable already. So a price member would have exactly one
4060    /// consumer, and it would mean this crate growing a money type it does not
4061    /// have: [`Unit`] is a time axis, and every amount in the described tree is
4062    /// text.
4063    ///
4064    /// The price therefore leads the line: `$24/mo. 2GB/file, 100GB total.
4065    /// Fits audio, plugins, binaries.` What would reopen it is a **second**
4066    /// priced option list, not a judgement about how that reads.
4067    ///
4068    /// # What it is not
4069    ///
4070    /// Not [`unavailable`](Self::unavailable), which says the option cannot be
4071    /// picked. This says what it means to pick it, and the two are drawn
4072    /// together on an option that carries both: the description that says a
4073    /// tier is out of stock *and* what the tier is has said two things.
4074    ///
4075    /// Not [`Field::hint`], which is standing help for the whole question, and
4076    /// not markup. One line of plain text, for [`Candidate::detail`]'s reason:
4077    /// an option list is a place a renderer lays out, and a description that
4078    /// put a block in one would be handing every host a layout problem for the
4079    /// benefit of one.
4080    ///
4081    /// Added 0.39.0.
4082    pub detail: Option<&'a str>,
4083}
4084
4085impl<'a> Choice<'a> {
4086    /// An option whose submitted value is also its label.
4087    #[must_use]
4088    pub const fn plain(value: &'a str) -> Self {
4089        Self::new(value, value)
4090    }
4091
4092    /// An option that submits one string and reads as another.
4093    ///
4094    /// A constructor rather than a literal, which is what `#[non_exhaustive]`
4095    /// costs and buys: outside this crate the struct cannot be built by naming
4096    /// its members, so every call site goes through here and the next member
4097    /// added breaks none of them.
4098    #[must_use]
4099    pub const fn new(value: &'a str, label: &'a str) -> Self {
4100        Self {
4101            value,
4102            label,
4103            unavailable: None,
4104            detail: None,
4105        }
4106    }
4107
4108    /// The same option, not pickable yet, and why.
4109    ///
4110    /// Builder-shaped because the reason is the rare case: 39 of the 40 option
4111    /// sites measured across the tree do not have one.
4112    #[must_use]
4113    pub const fn unless(mut self, reason: &'a str) -> Self {
4114        self.unavailable = Some(reason);
4115        self
4116    }
4117
4118    /// The same option, with the line that says what picking it means.
4119    ///
4120    /// Builder-shaped for [`unless`](Self::unless)'s reason, and it is the
4121    /// commoner of the two: six measured sites want this and one wants a
4122    /// precondition. See [`detail`](Self::detail).
4123    #[must_use]
4124    pub const fn detailing(mut self, detail: &'a str) -> Self {
4125        self.detail = Some(detail);
4126        self
4127    }
4128
4129    /// Whether the option can be picked right now.
4130    ///
4131    /// The predicate a renderer branches on, so that "unavailable" is read as
4132    /// one condition in one place rather than as `unavailable.is_some()` at
4133    /// three renderers, one of which will invert it.
4134    #[must_use]
4135    pub const fn available(&self) -> bool {
4136        self.unavailable.is_none()
4137    }
4138}
4139
4140/// One entry in a field's suggestion list.
4141///
4142/// A suggestion-only type rather than a fourth member on [`Choice`], ruled by
4143/// Max 2026-08-21 (`1fcf2e9b`). The two are near-identical and that is the
4144/// drift risk the ruling accepted, so the mitigation is written here: **an
4145/// option and a candidate are submitted the same way and read differently.**
4146/// An option is a thing you pick from a known set, and the set is the whole of
4147/// what there is. A candidate is a thing you are being *oriented* toward out of
4148/// a set nobody can see, which is why it carries [`detail`](Self::detail) and
4149/// an option does not.
4150///
4151/// This reverses a position quasi-router stated in its own doc, that a
4152/// candidate is [`Choice`] "because a candidate is submitted under one string
4153/// and read under another, which is what an option is". True and not
4154/// sufficient: how a thing is submitted was never the half that differed.
4155///
4156/// # Why the second string is not folded into the label
4157///
4158/// Because every renderer wants it separately, and the two measured sites both
4159/// draw it by hand today. The MNW server's tag box computes its context as the
4160/// parent path -- "the parent path orients an otherwise ambiguous leaf:
4161/// 'Format' appears under audio, software, writing, and video" -- and a list of
4162/// four identical rows reading "Format" is not a usable list. In a webview the
4163/// second string is styled differently, in a terminal it wants the remaining
4164/// columns rather than a dash, and in neither is it part of what the typed
4165/// value matches against. `Choice::new(slug, format!("{label} - {context}"))`
4166/// loses all three of those facts, which is the condition this type exists to
4167/// end.
4168///
4169/// # No `unavailable`
4170///
4171/// [`Choice::unavailable`] has no counterpart here, and the omission is the
4172/// implementer's call recorded rather than an oversight. A suggestion that
4173/// cannot be picked is arguably not a suggestion: an option list is a fixed set
4174/// a user is owed an explanation about, and a candidate list is whatever a
4175/// route decided to offer, so a route with nothing to say simply does not offer
4176/// the row. Add it if a measured site ever wants it.
4177///
4178/// # What it does not carry, and where that lives
4179///
4180/// What *happens* when a candidate is picked. Picking is local by default -- it
4181/// writes [`value`](Self::value) into the field that owns the list -- and a
4182/// candidate that does something else says so with an action. An action is not
4183/// a word this crate has, exactly as [`Field`] here has no `suggests` member,
4184/// so both live on the router's owned mirror of this type. Ruled the same day
4185/// (`ed1fa86f`).
4186///
4187/// `#[non_exhaustive]` from birth. Non-negotiable and the reason is on the
4188/// sibling: [`Choice`] took it at 0.28.0 only after `unavailable` broke 40
4189/// literal sites in six repos, and a new type repeating that would be the third
4190/// time the tree learned it.
4191///
4192/// Added 0.35.0.
4193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4194#[non_exhaustive]
4195pub struct Candidate<'a> {
4196    /// What is submitted, and what picking writes into the field.
4197    pub value: &'a str,
4198    /// What is read.
4199    pub label: &'a str,
4200    /// The second line: what orients this candidate among rows that read alike.
4201    ///
4202    /// Optional because a candidate list whose labels are already distinct
4203    /// wants nothing here, and a renderer given [`None`] draws one line rather
4204    /// than an empty second one.
4205    pub detail: Option<&'a str>,
4206}
4207
4208impl<'a> Candidate<'a> {
4209    /// A candidate whose submitted value is also its label.
4210    #[must_use]
4211    pub const fn plain(value: &'a str) -> Self {
4212        Self::new(value, value)
4213    }
4214
4215    /// A candidate that submits one string and reads as another.
4216    ///
4217    /// A constructor rather than a literal, which is what `#[non_exhaustive]`
4218    /// costs and buys: outside this crate the struct cannot be built by naming
4219    /// its members, so every call site goes through here and the next member
4220    /// added breaks none of them.
4221    #[must_use]
4222    pub const fn new(value: &'a str, label: &'a str) -> Self {
4223        Self {
4224            value,
4225            label,
4226            detail: None,
4227        }
4228    }
4229
4230    /// The same candidate, with the line that tells it from its neighbours.
4231    #[must_use]
4232    pub const fn detailed(mut self, detail: &'a str) -> Self {
4233        self.detail = Some(detail);
4234        self
4235    }
4236}
4237
4238/// Which ambient mode a theme is written for.
4239///
4240/// The vocabulary's own spelling of what `makeover` calls a theme's variant,
4241/// and the duplication is deliberate rather than an oversight. This crate has
4242/// no dependencies by charter — it emits nothing, reads nothing and resolves
4243/// nothing — so it cannot take the crate that owns the file format, and a
4244/// renderer that must group a picker needs the three groups as values.
4245///
4246/// The two are kept in step by the app that converts between them, which is a
4247/// three-arm `match` at each adopter and the price of the layering. If a fourth
4248/// mode is ever authored, this enum and `makeover::Variant` move together.
4249///
4250/// Three, not two: one shipped theme is high contrast, and an app matching on
4251/// light-or-dark alone files it under the wrong one.
4252///
4253/// Added 0.38.0.
4254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
4255#[non_exhaustive]
4256pub enum ThemeVariant {
4257    /// Written for a light ambient mode.
4258    Light,
4259    /// Written for a dark ambient mode.
4260    Dark,
4261    /// Written to be legible before it is pretty.
4262    HighContrast,
4263}
4264
4265impl ThemeVariant {
4266    /// The machine spelling, matching the theme file's own `meta.variant`.
4267    ///
4268    /// A data attribute, a stored value, a test assertion. Not a heading: what
4269    /// a group is *called* on screen is [`heading`](Self::heading).
4270    #[must_use]
4271    pub const fn as_str(self) -> &'static str {
4272        match self {
4273            ThemeVariant::Light => "light",
4274            ThemeVariant::Dark => "dark",
4275            ThemeVariant::HighContrast => "high-contrast",
4276        }
4277    }
4278
4279    /// What the group of themes in this variant is called on screen.
4280    ///
4281    /// Here rather than at each renderer, which is the whole argument for the
4282    /// member existing: three renderers picking their own headings is one
4283    /// picker reading three ways, and the spellings below are the ones
4284    /// goingson's shipped picker used before it was described.
4285    #[must_use]
4286    pub const fn heading(self) -> &'static str {
4287        match self {
4288            ThemeVariant::Light => "Light",
4289            ThemeVariant::Dark => "Dark",
4290            ThemeVariant::HighContrast => "High Contrast",
4291        }
4292    }
4293}
4294
4295impl std::fmt::Display for ThemeVariant {
4296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4297        f.write_str(self.as_str())
4298    }
4299}
4300
4301/// How legible a theme measured, as a picker reports it.
4302///
4303/// A measurement carried into the description, which is unusual here and is the
4304/// one case that earns it: the number comes off the theme's resolved colours,
4305/// so the layer that loaded the theme is the only party that has it, and an app
4306/// re-deriving it would be parsing every theme file a second time to learn what
4307/// was already known. What a renderer does with it is a badge beside the name.
4308///
4309/// Ordered worst-first, matching `makeover::ContrastTier`, so the two sort the
4310/// same way and an adopter's `match` cannot invert an ordering by accident.
4311///
4312/// Added 0.38.0.
4313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
4314#[non_exhaustive]
4315pub enum Contrast {
4316    /// Muted text below the 3:1 floor for large text and UI parts.
4317    Low,
4318    /// Muted text clears 3:1 but not the 4.5:1 bar for normal text.
4319    Standard,
4320    /// Muted text meets WCAG AA on every panel ground.
4321    High,
4322}
4323
4324impl Contrast {
4325    /// The machine spelling, for a data attribute or a test.
4326    #[must_use]
4327    pub const fn as_str(self) -> &'static str {
4328        match self {
4329            Contrast::Low => "low",
4330            Contrast::Standard => "standard",
4331            Contrast::High => "high",
4332        }
4333    }
4334
4335    /// The short mark shown beside a theme's name.
4336    ///
4337    /// One spelling for the tree, for [`ThemeVariant::heading`]'s reason. These
4338    /// are the marks audiofiles shipped before its picker was described, which
4339    /// is the only implementation that ever drew them.
4340    ///
4341    /// [`Standard`](Self::Standard) is not the absence of a mark: a reader
4342    /// scanning a column of badges learns more from three marks than from two
4343    /// and a gap, and "OK" is the honest reading of a theme that clears the UI
4344    /// floor and misses the text one.
4345    #[must_use]
4346    pub const fn badge(self) -> &'static str {
4347        match self {
4348            Contrast::Low => "low",
4349            Contrast::Standard => "OK",
4350            Contrast::High => "AA",
4351        }
4352    }
4353}
4354
4355impl std::fmt::Display for Contrast {
4356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4357        f.write_str(self.as_str())
4358    }
4359}
4360
4361/// One theme, as a picker offers it.
4362///
4363/// Four facts where a [`Choice`] has two, and the two extra ones are why this
4364/// is its own type rather than options with the variant folded into the label.
4365/// Both are facts the theme layer resolved and neither survives being written
4366/// into a string: a group is structure and a badge is a second column.
4367///
4368/// # No `unavailable`
4369///
4370/// [`Choice::unavailable`]'s counterpart is absent for its own sibling's
4371/// reason. A theme that is installed can be picked, and a theme that is not
4372/// installed is not in the list. There is no third state for a reason to
4373/// explain.
4374///
4375/// `#[non_exhaustive]` from birth, which is the whole of what 0.28.0 cost the
4376/// tree and is not being paid a third time.
4377///
4378/// Added 0.38.0.
4379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4380#[non_exhaustive]
4381pub struct ThemeChoice<'a> {
4382    /// What is submitted, and what the app stores.
4383    pub id: &'a str,
4384    /// What is read.
4385    pub name: &'a str,
4386    /// Which group it belongs to.
4387    pub variant: ThemeVariant,
4388    /// How legible its muted text measured.
4389    pub contrast: Contrast,
4390}
4391
4392impl<'a> ThemeChoice<'a> {
4393    /// A theme, with everything a picker needs to place and mark it.
4394    ///
4395    /// Every fact is an argument and none is a builder, which is the opposite
4396    /// of [`Choice`]'s arrangement and is deliberate: a theme missing its
4397    /// variant has no group to sit in and a theme missing its tier has no badge
4398    /// to draw, so both are the control rather than embellishments on it. The
4399    /// same reasoning [`Field::range`] applies to its bounds.
4400    #[must_use]
4401    pub const fn new(
4402        id: &'a str,
4403        name: &'a str,
4404        variant: ThemeVariant,
4405        contrast: Contrast,
4406    ) -> Self {
4407        Self {
4408            id,
4409            name,
4410            variant,
4411            contrast,
4412        }
4413    }
4414}
4415
4416/// One field of a form.
4417///
4418/// Borrowed rather than owned: a description is built, read once by a renderer,
4419/// and dropped. Nothing here outlives the screen it describes.
4420///
4421/// # What it carries, and what it does not
4422///
4423/// Stated here so the next renderer does not re-ask, which is what the first
4424/// two both did. It carries everything a renderer needs to *draw* the field:
4425/// its kind, what it is called, what it is asked for, its standing help, what
4426/// is wrong with it now, whether it is compulsory, whether it hides behind a
4427/// disclosure, its ghost text, and the options it offers.
4428///
4429/// It does not carry the **current value**, and it is not going to. That is the
4430/// one thing here that is genuinely renderer state: a webview reads it back out
4431/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
4432/// and writes through it, and a terminal keeps an edit buffer. A description
4433/// that carried the value would have to carry a way to write it back, at which
4434/// point it is a form model and no longer a description.
4435///
4436/// **Constraints** are here and enforcement is not, which is one line rather
4437/// than two. [`required`], [`max_length`], [`min`] and [`max`] are facts about
4438/// the *question*, so a renderer can emit its host's idiom for each — an HTML
4439/// attribute, a marked label, a clamped spinner — and the platform helps the
4440/// user before anything is submitted. Deciding that a value is wrong stays with
4441/// whoever validated, and [`error`] is that decision arriving back.
4442///
4443/// The set stops before `pattern`, and stops there on both tests at once. A
4444/// regex has an honest answer in a webview and none anywhere else: egui would
4445/// have to run it per keystroke and decide what a half-typed value means, which
4446/// is enforcement wearing description's clothes. And it is one site in goingson
4447/// and none in Balanced Breakfast, against 8 and 1 for `maxlength`. Measured
4448/// 2026-08-09, `2cbad3e2`.
4449///
4450/// [`error`]: Field::error
4451/// [`required`]: Field::required
4452/// [`max_length`]: Field::max_length
4453/// [`min`]: Field::min
4454/// [`max`]: Field::max
4455/// How a slider's position becomes its value, and how finely it moves.
4456///
4457/// **The data of a slider is a fraction and a function taking numbers to
4458/// numbers.** Stated by Max 2026-08-21, and it corrects a reading this crate
4459/// had carried since [`FieldKind::Range`] arrived at 0.28.0:
4460/// [`min`](Field::min) and [`max`](Field::max) were never the control's extent.
4461/// A slider's extent is always 0 to 1 — a thumb at 40% of a track — and the
4462/// bounds are `f(0)` and `f(1)`. Linear is the constant-slope case, which is
4463/// exactly why nobody noticed the function was there: when `f` is
4464/// `min + t * (max - min)` the extent and the bounds coincide numerically and
4465/// the mapping is invisible.
4466///
4467/// So this is not a scale flag bolted onto a range. Every range described
4468/// before it had a mapping, and four renderers each hard-coded the same one.
4469///
4470/// # Why a closed family and not a function
4471///
4472/// `fn(f64) -> f64` is the literal reading and it does not survive the
4473/// description boundary. A fn pointer cannot be emitted into a browser, and it
4474/// cannot be compared or hashed in a way that means anything, which this struct
4475/// needs. A named family is the same semantics with arbitrary closures given
4476/// up, and nothing measured wants one: the tree has a single non-linear shape
4477/// across five controls and no second shape at all.
4478///
4479/// # Why the step is here
4480///
4481/// Max, in the same breath: if the family is prescriptive anyway, the step
4482/// spacing belongs in it. On a slider the granularity and the mapping are one
4483/// decision — a curve chosen without saying how finely it moves is half an
4484/// answer — and holding them apart is what let a 0-to-1 threshold ship as a
4485/// two-position control, since the host default of 1 was applied to a mapping
4486/// nobody had named. It also un-overloads [`Field::step`], which stays as it
4487/// was for a *typed* value, where there is no mapping and the granularity is a
4488/// plain fact about the number.
4489///
4490/// A future curve carrying a fact of its own — an exponent, an inflection —
4491/// puts it in its own variant rather than on the struct, which is the second
4492/// reason this shape is right.
4493///
4494/// **The step is in the value's own units under every curve.** What a curve
4495/// changes is the mapping, not the units the granularity is measured in: a step
4496/// of `0.001` on an envelope time is three decimals whether the track is
4497/// logarithmic or not, and a renderer that reads the step for display precision
4498/// keeps reading it the same way.
4499///
4500/// Added 0.32.0, from audiofiles' ADSR envelope and its storage cap picker.
4501#[non_exhaustive]
4502#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4503pub enum Curve<'a> {
4504    /// Constant slope: `f(t) = min + t * (max - min)`.
4505    ///
4506    /// What every described range meant before this enum existed, and the
4507    /// default, so a site that says nothing is correct unchanged.
4508    Linear {
4509        /// The granularity, in the value's own units. `None` is the host's own.
4510        step: Option<&'a str>,
4511    },
4512    /// Constant ratio: `f(t) = min * (max / min).powf(t)`.
4513    ///
4514    /// The mapping for a question whose extent spans orders of magnitude and
4515    /// whose interesting half is the small end. audiofiles' envelope times run
4516    /// 0.001 to 5 seconds, where a 5 ms attack and a 50 ms attack are audibly
4517    /// different instruments and a linear track puts both inside its first one
4518    /// percent.
4519    ///
4520    /// # It needs positive bounds
4521    ///
4522    /// A constant ratio is undefined across zero, so this asks for `min > 0`.
4523    /// A range that does not have that is mapped [`Linear`](Self::Linear)ly
4524    /// instead — see [`value_at`](Self::value_at). Stated rather than enforced,
4525    /// the way every other constraint in this crate is, and it is not a
4526    /// hypothetical: an envelope's sustain is a 0-to-1 level and is linear for
4527    /// this reason rather than by oversight.
4528    Logarithmic {
4529        /// The granularity, in the value's own units. `None` is the host's own.
4530        step: Option<&'a str>,
4531    },
4532}
4533
4534impl Default for Curve<'_> {
4535    fn default() -> Self {
4536        Self::Linear { step: None }
4537    }
4538}
4539
4540impl<'a> Curve<'a> {
4541    /// The granularity this curve moves in, whichever curve it is.
4542    ///
4543    /// Every variant carries one, so reading it does not need a match at each
4544    /// of the four renderers.
4545    #[must_use]
4546    pub const fn step(self) -> Option<&'a str> {
4547        // No wildcard: `#[non_exhaustive]` binds downstream, not here, so a
4548        // curve added later has to answer this rather than fall through to a
4549        // granularity nobody chose.
4550        match self {
4551            Self::Linear { step } | Self::Logarithmic { step } => step,
4552        }
4553    }
4554
4555    /// Whether this curve maps as a constant ratio *given these bounds*.
4556    ///
4557    /// The bounds are the argument because [`Logarithmic`](Self::Logarithmic)
4558    /// is a request rather than a guarantee: it needs `0 < min < max`, and a
4559    /// range that does not have that is drawn linearly. A renderer asks this
4560    /// instead of matching on the variant, so the fallback is decided in one
4561    /// place rather than four.
4562    #[must_use]
4563    pub fn is_ratio(self, min: f64, max: f64) -> bool {
4564        matches!(self, Self::Logarithmic { .. }) && min > 0.0 && max > min
4565    }
4566
4567    /// The value at a position along the track, where `position` is 0 to 1.
4568    ///
4569    /// `f`. The whole point of the type, and it lives here rather than in each
4570    /// renderer so that a terminal's bar, an egui slider and a browser's input
4571    /// cannot disagree about where a value sits.
4572    ///
4573    /// A position outside 0 to 1 is clamped, and bounds that are equal or
4574    /// inverted give `min` back: a track with no extent has one value on it.
4575    #[must_use]
4576    pub fn value_at(self, position: f64, min: f64, max: f64) -> f64 {
4577        let position = position.clamp(0.0, 1.0);
4578        // NaN named rather than fallen through: `max <= min` is false for a NaN
4579        // bound, so without it a track with no numbers on it would be mapped as
4580        // if it had two.
4581        if max <= min || min.is_nan() || max.is_nan() {
4582            return min;
4583        }
4584        if self.is_ratio(min, max) {
4585            min * (max / min).powf(position)
4586        } else {
4587            position.mul_add(max - min, min)
4588        }
4589    }
4590
4591    /// The position a value sits at, where the answer is 0 to 1.
4592    ///
4593    /// `f` inverted, which is what a renderer needs to *draw* a value it was
4594    /// handed. Same clamping and the same degenerate answer as
4595    /// [`value_at`](Self::value_at).
4596    #[must_use]
4597    pub fn position_of(self, value: f64, min: f64, max: f64) -> f64 {
4598        if max <= min || min.is_nan() || max.is_nan() {
4599            return 0.0;
4600        }
4601        let value = value.clamp(min, max);
4602        let position = if self.is_ratio(min, max) {
4603            (value / min).ln() / (max / min).ln()
4604        } else {
4605            (value - min) / (max - min)
4606        };
4607        position.clamp(0.0, 1.0)
4608    }
4609}
4610
4611#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4612pub struct Field<'a> {
4613    /// What kind of value it takes.
4614    pub kind: FieldKind,
4615    /// The name the value is submitted under.
4616    ///
4617    /// The *lower* end's name for a [`FieldKind::Interval`], whose upper end is
4618    /// [`upper_name`](Self::upper_name). Every other kind submits one value and
4619    /// this is the whole of it.
4620    pub name: &'a str,
4621    /// The name a [`FieldKind::Interval`]'s upper end is submitted under.
4622    ///
4623    /// [`None`] for every other kind, and sayable-and-ignored there the way
4624    /// [`options`](Self::options) is on a kind that offers none.
4625    ///
4626    /// Stated rather than derived from [`name`](Self::name), and
4627    /// [`FieldKind::Interval`] carries the measurement that decided it: the two
4628    /// sites in this tree disagree about affix order, so a derived rule would
4629    /// rename one of them. Which member a name sits in is also what says which
4630    /// end it is, so nothing separate carries the direction.
4631    ///
4632    /// An interval missing it is an interval with one end that can be submitted,
4633    /// which is a description a renderer may draw honestly and no better than
4634    /// that. [`Field::interval`] is what makes forgetting it unsayable, on the
4635    /// same footing as [`Field::range`] and its bounds.
4636    ///
4637    /// Added 0.34.0.
4638    pub upper_name: Option<&'a str>,
4639    /// What the user is asked for.
4640    pub label: &'a str,
4641    /// Standing help, shown whether or not anything is wrong.
4642    pub hint: Option<&'a str>,
4643    /// What is currently wrong with the value.
4644    pub error: Option<&'a str>,
4645    /// A consequence of the answer the user has given, carrying its own tone.
4646    ///
4647    /// The third message channel, between [`hint`](Self::hint) and
4648    /// [`error`](Self::error) and overlapping neither. A hint is standing help
4649    /// that does not depend on the value; an error says the value is not
4650    /// acceptable. A note is the case in the middle: the value is perfectly
4651    /// acceptable and choosing it costs something the user should know about.
4652    ///
4653    /// The first consumer is audiofiles' export Format field, where choosing
4654    /// WAV or AIFF over Original re-encodes and silently drops embedded BWF,
4655    /// iXML, loop points, cue markers and ID3. That is not a validation
4656    /// failure and it is not standing help — it is true of one answer to one
4657    /// question — and it was hand-drawn in the app's own draw callback for
4658    /// want of anywhere to say it.
4659    ///
4660    /// The tone is carried rather than fixed at [`Tone::Warning`] because the
4661    /// channel is not only for warnings: the same slot says "this is the
4662    /// recommended one" ([`Tone::Success`]) and "this is what that setting
4663    /// implies" ([`Tone::Info`]). A renderer gets the announcement behaviour
4664    /// off the tone for free — makeover-webview emits `data-tone` and treats
4665    /// Warning and Danger as assertive for `aria-live`.
4666    ///
4667    /// It does **not** make the field invalid. [`invalid`](Self::invalid) stays
4668    /// `error.is_some()`, so a note never marks the group as a problem.
4669    ///
4670    /// # Precedence, for a renderer with room for one
4671    ///
4672    /// Error, then note, then hint. A renderer that shows every message shows
4673    /// them in that order too. makeover-tui is the one with room for exactly
4674    /// one line, and it is why the order is decided here rather than three
4675    /// times: what is wrong outranks what it costs, which outranks how it
4676    /// works.
4677    ///
4678    /// Added 0.36.0.
4679    pub note: Option<(Tone, &'a str)>,
4680    /// Ghost text shown while the field is empty.
4681    ///
4682    /// User-facing text, and it sits with `label` and `hint` rather than with
4683    /// the value because it is a property of the *question* and not of the
4684    /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
4685    /// reason and it was not a reading on where it belonged: adding a field to
4686    /// a published struct is a breaking change.
4687    ///
4688    /// Not a substitute for a label. A field labelled only by its placeholder
4689    /// loses its label the moment anything is typed, and no renderer here can
4690    /// make that not happen, so the description keeps both.
4691    pub placeholder: Option<&'a str>,
4692    /// The options offered, in the order they are offered.
4693    ///
4694    /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
4695    /// described with no options is sayable on purpose: it is what an app with
4696    /// an unfinished-loading option list actually has, and a renderer showing
4697    /// an empty control says so on screen rather than in a log.
4698    ///
4699    /// Which option is *current* is not here. That is the value, and the value
4700    /// is renderer state.
4701    pub options: &'a [Choice<'a>],
4702    /// The themes offered, in the order they are offered.
4703    ///
4704    /// Empty for every kind [`FieldKind::offers_themes`] rejects, and sayable
4705    /// as empty for the one that accepts it: an app whose theme directories
4706    /// hold nothing has a picker offering only [`follows`](Self::follows),
4707    /// which is a true description of that machine.
4708    ///
4709    /// **The order is the grouping.** Entries arrive sorted by
4710    /// [`ThemeVariant`] and then by [`Contrast`] within each variant, so a
4711    /// renderer that draws headings walks the run of one variant and a renderer
4712    /// that cannot still gets the useful order. Handing back groups would force
4713    /// the second renderer to flatten what the first wanted.
4714    ///
4715    /// Nothing here sorts. The description carries the order it was given, and
4716    /// the sort belongs with whoever measured the tiers — `makeover::theme_options`
4717    /// is what produces it, and re-sorting here would be this crate deciding a
4718    /// question it cannot see the inputs to.
4719    ///
4720    /// Which theme is *current* is not here. That is the value, and the value
4721    /// is renderer state, exactly as it is for [`options`](Self::options).
4722    ///
4723    /// Added 0.38.0.
4724    pub themes: &'a [ThemeChoice<'a>],
4725    /// The entry that follows the ambient mode instead of naming a theme.
4726    ///
4727    /// [`None`] for a picker that does not offer one, which is a real answer:
4728    /// an app whose host has no ambient mode to follow should not offer a row
4729    /// that does nothing.
4730    ///
4731    /// A [`Choice`] rather than a bare label, because the *value* is the app's.
4732    /// Every store in the family spells it `system` today and none of them is
4733    /// obliged to; a description that hardcoded the spelling would be this
4734    /// crate holding a fact about somebody else's config table.
4735    ///
4736    /// It is not a [`ThemeChoice`] with an absent variant. Following is a
4737    /// standing instruction that resolves differently as the desktop flips, and
4738    /// a theme id is an answer that does not — which is the distinction
4739    /// `makeover::ThemeSelection` exists to hold, carried here rather than
4740    /// blurred.
4741    ///
4742    /// Added 0.38.0.
4743    pub follows: Option<Choice<'a>>,
4744    /// What a file field takes, in the order a host offering the list shows it.
4745    ///
4746    /// Empty for every kind [`FieldKind::takes_files`] rejects, and empty is
4747    /// also a real answer for one that accepts it: a field that takes any file
4748    /// says so by listing nothing, which is what an `<input type="file">` with
4749    /// no `accept` does and what most of the measured sites are.
4750    ///
4751    /// It is a filter and it is the disclosure cue, and [`Accepted`]'s doc
4752    /// carries which reading is which. Nothing here validates: a host may hand
4753    /// back a file the list does not cover, exactly as a browser does when the
4754    /// user switches the picker to "All Files", and deciding a value is wrong
4755    /// stays with whoever validated.
4756    ///
4757    /// Added 0.31.0, `f7261a5a`.
4758    pub accept: &'a [Accepted<'a>],
4759    /// Whether more than one file may be picked at once.
4760    ///
4761    /// Only [`FieldKind::takes_files`] reads it. A multi-valued answer to any
4762    /// other question is a different shape — a set of options, a repeated
4763    /// group — and neither is this flag with a different kind beside it.
4764    ///
4765    /// False is the common case: 4 of the MNW server's 16 file inputs carry it.
4766    ///
4767    /// Added 0.31.0, `f7261a5a`.
4768    pub multiple: bool,
4769    /// Whether the form refuses to submit without it.
4770    pub required: bool,
4771    /// The longest the value may be, in characters.
4772    ///
4773    /// Added 0.11.0 with [`min`](Self::min) and [`max`](Self::max), joining
4774    /// [`required`](Self::required), which had been the only constraint here
4775    /// since before the crate wrote down that it carried none.
4776    pub max_length: Option<u32>,
4777    /// The lowest value accepted, as the host would write it.
4778    ///
4779    /// Text rather than a number, because the bound is only a number for some
4780    /// of the kinds that take one. goingson's own sites are `min="1"` on a
4781    /// duration and `min="2026-08-09T14:30"` on a datetime, and a numeric member
4782    /// could say the first and not the second. The [`kind`](Self::kind) already
4783    /// says how to read it, the same way it does for the value.
4784    pub min: Option<&'a str>,
4785    /// The highest value accepted, as the host would write it. See
4786    /// [`min`](Self::min).
4787    pub max: Option<&'a str>,
4788    /// The granularity the value moves in, as the host would write it.
4789    ///
4790    /// Text for [`min`](Self::min)'s reason, and it earns it twice over: the
4791    /// step of a date is a day and the step of a threshold is 0.01, and a
4792    /// numeric member could say one of them.
4793    ///
4794    /// Absent means the host's own granularity, which is the honest default
4795    /// rather than a missing value: a webview's `<input>` steps by 1 unless told
4796    /// otherwise, and that is the browser's rule and not this crate's to
4797    /// restate.
4798    ///
4799    /// # It is the granularity of a *typed* value
4800    ///
4801    /// [`FieldKind::Range`] reads its own from [`curve`](Self::curve) and
4802    /// ignores this, as of 0.32.0. Until then this member served both, and
4803    /// serving both is what the split fixes: on a slider the granularity and
4804    /// the mapping are one decision, and on a typed number there is no mapping
4805    /// to decide with. See [`Curve`], "Why the step is here".
4806    ///
4807    /// Added 0.28.0 with [`FieldKind::Range`], and narrowed away from it at
4808    /// 0.32.0.
4809    pub step: Option<&'a str>,
4810    /// How a slider's position becomes its value, and how finely it moves.
4811    ///
4812    /// [`FieldKind::Range`]'s, and nothing else reads it: a typed number has a
4813    /// granularity but no mapping, and takes [`step`](Self::step) instead.
4814    ///
4815    /// Defaults to [`Curve::Linear`] with no step, which is what every range
4816    /// described before 0.32.0 meant, so this member is additive and no
4817    /// existing site changes meaning.
4818    ///
4819    /// Added 0.32.0.
4820    pub curve: Curve<'a>,
4821    /// What the number is measured in: `s`, `ms`, `dB`, `GiB`.
4822    ///
4823    /// A fact about the value, not part of the question's name, and that
4824    /// distinction is the whole reason it is a member. The two readings come
4825    /// apart the moment anything reads a field back rather than drawing it: a
4826    /// [`max`](Self::max) of `-96` and a bound of `-96 dBFS` are the same number
4827    /// and not the same answer, and under the convention this replaces the unit
4828    /// could only be recovered by parsing it back out of a label.
4829    ///
4830    /// # Where a renderer draws it
4831    ///
4832    /// Beside the value, wherever that host puts a value. Not in the label: the
4833    /// label is the sentence above the control and that is the one place the
4834    /// convention could put it, which is why it read the same on every host and
4835    /// was wrong on the one host that had somewhere better. egui puts it inside
4836    /// the slider where the readout already is, a terminal appends it to the
4837    /// value in the edit line, a webview sets it adjacent to the input.
4838    ///
4839    /// # Which kinds read it
4840    ///
4841    /// [`FieldKind::measurable`] answers, and it is
4842    /// [`takes_files`](FieldKind::takes_files)'s footing: three renderers ask
4843    /// before they can decide whether to draw this, and a `matches!` per
4844    /// renderer is where the next measurable kind goes missing. A unit on a kind
4845    /// that rejects it is sayable and ignored, the same way
4846    /// [`options`](Self::options) is on a kind that offers none.
4847    ///
4848    /// # Why a string
4849    ///
4850    /// The measured sites are `GiB`, `dBFS`, `s` and `ms`. An enum would have to
4851    /// grow a member for every unit any consumer ever wants, and this crate does
4852    /// not know them; it knows that a number has one.
4853    ///
4854    /// Written as the symbol alone, with no brackets and no leading space. The
4855    /// spacing is the renderer's, because a slider's readout and a sentence want
4856    /// different answers.
4857    ///
4858    /// Added 0.33.0, `32215e21`, on eight sites across four files that had each
4859    /// arrived at "Attack (s)" separately.
4860    pub unit: Option<&'a str>,
4861    /// Whether the field lives behind a "more options" disclosure.
4862    pub extended: bool,
4863    /// Whether this local wall-clock value is submitted as an absolute instant.
4864    ///
4865    /// [`FieldKind::DateTime`] asks for a time the way a person says one --
4866    /// "the 14th at half past two" -- and that names a different moment in
4867    /// Denver than it does in Berlin. A route that stores an instant needs the
4868    /// moment, so somebody has to convert. This member says the description
4869    /// wants that conversion; it does not say how.
4870    ///
4871    /// # The conversion belongs to the renderer
4872    ///
4873    /// Because the renderer is the only party that knows what "your computer's
4874    /// time zone" means for its host. A browser has one and the user is sitting
4875    /// in it; a TUI reads the host clock; an egui app reads the same clock a
4876    /// different way. Nothing above the renderer can answer it, and the
4877    /// alternatives all try: a hidden IANA-zone field needs a host capability
4878    /// for reading the zone that three hosts answer differently, plus a kind
4879    /// that does not exist, plus a wire-contract change; a timezone on the
4880    /// user's profile is a product decision wearing a bug's clothes. Say it
4881    /// here, and the next reader does not propose them again.
4882    ///
4883    /// # What a renderer does
4884    ///
4885    /// Draws the same control it always did -- the flag changes what is
4886    /// *submitted*, not what is shown -- and converts the local value to an
4887    /// absolute instant on the way out. A renderer that cannot convert submits
4888    /// the local value unchanged, which is what every renderer did before this
4889    /// existed.
4890    ///
4891    /// No wire contract moves when a site adopts it: the route was already
4892    /// receiving an instant. What changes is who computed it.
4893    ///
4894    /// # Which kinds read it
4895    ///
4896    /// [`FieldKind::DateTime`]'s. `Date` and `Time` are each half a moment and
4897    /// cannot name one on their own, so the flag is sayable and ignored there,
4898    /// the way [`options`](Self::options) is on a kind that offers none.
4899    ///
4900    /// Added 0.37.0, retiring the MNW server's `data-config="publish-at-iso"`
4901    /// -- the last site of a private per-app vocabulary that this crate exists
4902    /// to replace.
4903    pub as_instant: bool,
4904}
4905
4906impl<'a> Field<'a> {
4907    /// A plain required-nothing field of the given kind.
4908    #[must_use]
4909    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
4910        Self {
4911            kind,
4912            name,
4913            upper_name: None,
4914            label,
4915            hint: None,
4916            error: None,
4917            note: None,
4918            placeholder: None,
4919            options: &[],
4920            themes: &[],
4921            follows: None,
4922            accept: &[],
4923            multiple: false,
4924            required: false,
4925            max_length: None,
4926            min: None,
4927            max: None,
4928            step: None,
4929            curve: Curve::Linear { step: None },
4930            unit: None,
4931            extended: false,
4932            as_instant: false,
4933        }
4934    }
4935
4936    /// A bounded number the user drags across its whole extent.
4937    ///
4938    /// The third under-described kind, and it gets a constructor for
4939    /// [`select`](Self::select)'s reason: a range is the one kind whose bounds
4940    /// are not a rule but the control itself, so a call site that forgot them
4941    /// has a slider with nothing to slide across. Taking them as arguments is
4942    /// what makes that unsayable.
4943    ///
4944    /// The granularity stays a field rather than a fourth argument, and since
4945    /// 0.32.0 it is [`curve`](Self::curve)'s: it is genuinely optional — the
4946    /// host's own is a real answer — and the two bounds are not.
4947    #[must_use]
4948    pub const fn range(name: &'a str, label: &'a str, min: &'a str, max: &'a str) -> Self {
4949        Self {
4950            min: Some(min),
4951            max: Some(max),
4952            ..Self::new(FieldKind::Range, name, label)
4953        }
4954    }
4955
4956    /// One question with two ends, taking the name each end submits under.
4957    ///
4958    /// A constructor for [`range`](Self::range)'s reason inverted: a range's
4959    /// bounds are what a call site cannot forget, and an interval's second name
4960    /// is. An interval built through [`new`](Self::new) has an upper end with
4961    /// nowhere to be submitted, and nothing downstream can invent one, so taking
4962    /// it as an argument is what makes that unsayable.
4963    ///
4964    /// The extent, the granularity and the unit stay members. They describe the
4965    /// axis rather than either end and they are genuinely optional, which is
4966    /// [`FieldKind::Number`]'s arrangement and the one an interval takes.
4967    #[must_use]
4968    pub const fn interval(name: &'a str, upper_name: &'a str, label: &'a str) -> Self {
4969        Self {
4970            upper_name: Some(upper_name),
4971            ..Self::new(FieldKind::Interval, name, label)
4972        }
4973    }
4974
4975    /// A file field, taking the given accept list.
4976    ///
4977    /// The fourth under-described kind and it gets a constructor for
4978    /// [`range`](Self::range)'s reason rather than [`select`](Self::select)'s:
4979    /// a file field with no accept list is not broken, it is a field that takes
4980    /// anything, and the hazard is the opposite one. A call site that meant to
4981    /// restrict and forgot has a picker offering every file on the machine and
4982    /// a server refusing the upload afterwards, which is the failure the list
4983    /// exists to move forward. Taking it as an argument is what makes an
4984    /// accidental omission a deliberate `&[]`.
4985    ///
4986    /// [`multiple`](Self::multiple) stays a field. One file is the common case
4987    /// and the honest default; several is the thing worth saying.
4988    #[must_use]
4989    pub const fn upload(name: &'a str, label: &'a str, accept: &'a [Accepted<'a>]) -> Self {
4990        Self {
4991            accept,
4992            ..Self::new(FieldKind::File, name, label)
4993        }
4994    }
4995
4996    /// A select offering the given options.
4997    ///
4998    /// One of the two kinds under-described by [`Field::new`], so it gets a
4999    /// constructor rather than leaving every call site to remember that a
5000    /// select with an empty `options` renders as an empty select.
5001    #[must_use]
5002    pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
5003        Self::offering(FieldKind::Select, name, label, options)
5004    }
5005
5006    /// A radio group offering the given options.
5007    ///
5008    /// The other. Same hazard as [`select`](Self::select) and a worse one: a
5009    /// radio group with no options draws nothing at all, so a call site that
5010    /// forgot them has an empty rectangle rather than a visibly empty control.
5011    #[must_use]
5012    pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
5013        Self::offering(FieldKind::Radio, name, label, options)
5014    }
5015
5016    /// A theme picker over the themes the host resolved.
5017    ///
5018    /// A constructor for [`select`](Self::select)'s reason and one of its own.
5019    /// The shared reason: a theme picker built through [`new`](Self::new) has
5020    /// an empty [`themes`](Self::themes) list and draws an empty control. Its
5021    /// own: the list is the *only* thing this kind takes that a call site
5022    /// cannot get wrong by omission and can get wrong by substitution, since
5023    /// [`options`](Self::options) is right there and reads as if it would work.
5024    ///
5025    /// [`following`](Self::following) is the builder rather than a fourth
5026    /// argument, because a picker with no follow-the-system row is a real
5027    /// picker and every renderer draws it honestly.
5028    #[must_use]
5029    pub const fn theme(name: &'a str, label: &'a str, themes: &'a [ThemeChoice<'a>]) -> Self {
5030        Self {
5031            themes,
5032            ..Self::new(FieldKind::Theme, name, label)
5033        }
5034    }
5035
5036    /// The same picker, offering a row that tracks the ambient mode.
5037    ///
5038    /// The [`Choice`] carries the value the app's own store spells it with.
5039    #[must_use]
5040    pub const fn following(mut self, follow: Choice<'a>) -> Self {
5041        self.follows = Some(follow);
5042        self
5043    }
5044
5045    /// The shared body of the two constructors that take options.
5046    ///
5047    /// Private, and keyed on the kind rather than exposed, because the two
5048    /// public names are the point: a call site says which question it is
5049    /// asking, not which flag it is setting.
5050    const fn offering(
5051        kind: FieldKind,
5052        name: &'a str,
5053        label: &'a str,
5054        options: &'a [Choice<'a>],
5055    ) -> Self {
5056        Self {
5057            options,
5058            ..Self::new(kind, name, label)
5059        }
5060    }
5061
5062    /// Whether the field is currently reporting a problem.
5063    ///
5064    /// Read this rather than testing `error.is_some()` at each renderer: the
5065    /// error state has to mark the field's whole group and not only the
5066    /// message, because a renderer with no descendant selectors (egui, a
5067    /// terminal) cannot find the group from the message. goingson already marks
5068    /// the group and Balanced Breakfast does not, so goingson's shape is the
5069    /// one taken here.
5070    ///
5071    /// [`note`](Self::note) is deliberately not consulted. A note says the
5072    /// answer costs something, not that it is unacceptable, and a field the
5073    /// user may submit as it stands is not invalid.
5074    #[must_use]
5075    pub const fn invalid(&self) -> bool {
5076        self.error.is_some()
5077    }
5078
5079    /// Whether the field carries both ends of its extent.
5080    ///
5081    /// Only [`FieldKind::Range`] owes them, and it owes them absolutely: a
5082    /// slider with one end missing has no extent to draw. Named here rather
5083    /// than left to each renderer to test `min.is_some() && max.is_some()`,
5084    /// which is three renderers arriving at the same condition and one of them
5085    /// getting it wrong, and named as a question about the *field* rather than
5086    /// about the kind because the kind cannot see the bounds.
5087    ///
5088    /// It is a check and not a guarantee. Nothing here refuses to build an
5089    /// unbounded range — [`Field::range`] is what makes the bounded one easy —
5090    /// so a renderer asks this and falls back to whatever its host does
5091    /// honestly with a number.
5092    #[must_use]
5093    pub const fn bounded(&self) -> bool {
5094        self.min.is_some() && self.max.is_some()
5095    }
5096
5097    /// Whether anything in [`accept`](Self::accept) names a media family.
5098    ///
5099    /// The question a renderer asks before it decides to keep room for a
5100    /// preview, and it is deliberately the *whole list* rather than one entry:
5101    /// the media dropzone this was measured against takes `image/*,video/*`, so
5102    /// there is no single family to return and there is still a disclosure to
5103    /// offer. Which one it turns out to be is known once a file is picked, which
5104    /// is renderer-side and after the description is gone.
5105    ///
5106    /// False for an empty list, for a list of suffixes, and for `text/csv`. A
5107    /// renderer that wants the family of a particular entry reads
5108    /// [`Accepted::family`].
5109    #[must_use]
5110    pub fn accepts_media(&self) -> bool {
5111        self.accept.iter().any(|one| one.family().is_some())
5112    }
5113}
5114
5115/// How much room a placement asks for.
5116///
5117/// A column says it, and so does a [`Field`]. An intent, so the actual floor
5118/// stays with `makeover-geometry`. goingson's task table spells these as
5119/// `minmax(200px, 1fr)`, `140px` and content-sized; only the first three words
5120/// of that survive deferral.
5121/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
5122/// renderer matches on this and a vocabulary that grows must not break every
5123/// renderer when it does.
5124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5125#[non_exhaustive]
5126pub enum Width {
5127    /// Takes what it needs and no more.
5128    Content,
5129    /// A fixed share, the same at every width.
5130    Fixed,
5131    /// Absorbs whatever is left over.
5132    ///
5133    /// **Several fills divide what is left equally.** Stated because it would
5134    /// otherwise be undefined and each renderer would invent something, and
5135    /// stated this way because equal division is the only sharing rule that
5136    /// answers to "Any width, one answer" without a tiebreak: allocating in
5137    /// declaration order makes the result depend on the order the description
5138    /// was written in, which is a fact about the source file and not about the
5139    /// screen. It documents what both renderers already do — CSS grid gives
5140    /// `1fr 1fr`, ratatui gives each a `Constraint::Fill(1)` — rather than
5141    /// changing anything.
5142    ///
5143    /// So a row of fills is a legal thing to describe, and there is no rule
5144    /// against it. Measured 2026-08-16, every table in the tree uses exactly
5145    /// one, which is the discipline this would otherwise have had to forbid.
5146    Fill,
5147}
5148
5149/// What a member is worth when there is not room for all of them.
5150///
5151/// Written for table columns and no longer only theirs. Three shapes ask the
5152/// same question and this answers all three: a table too narrow for its
5153/// columns, a row too narrow for its parts (see [`RowPart::priority`]), and a
5154/// group of regions sharing one run of room -- goingson's tab strip and the
5155/// [`Region::Band`] beside it, which is the case wiki `layout-room-and-fallback`
5156/// was ruled on. It is what any member of a group is worth, not a table
5157/// concept, and [`Fallback::Shed`] is what reads it.
5158///
5159/// The doc below is the column argument, which is where the type was measured;
5160/// the sentence that gave it away is [`Priority::Essential`]'s, which was
5161/// already written about a row.
5162///
5163/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
5164/// drops. This replaces addressing columns by position, which is what both
5165/// webview apps do today and is a live bug rather than only verbosity. goingson
5166/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
5167/// inserting a column silently hides the wrong one.
5168/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
5169/// whole point of the type, so a new tier has to be declared in its place in
5170/// the sequence rather than appended.
5171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5172#[non_exhaustive]
5173pub enum Priority {
5174    /// Dropped first.
5175    Optional,
5176    /// Dropped once the optional members are gone.
5177    Secondary,
5178    /// Never dropped. Without it the group does not identify itself.
5179    Essential,
5180}
5181
5182/// How much room a group has, measured against its own allocation.
5183///
5184/// Never authored. A renderer computes it from what the group was given and
5185/// what the group's own contents ask for, in that renderer's units: a webview
5186/// from `min-content` under a container query, a terminal from cell widths,
5187/// egui from the galley. Nothing in the description says a number, which is the
5188/// point -- an authored breakpoint rots and this cannot.
5189///
5190/// # Why not [`Depth`]-style two members and no more
5191///
5192/// Two is what the measurement supports. The goingson case that produced this
5193/// type is a window 913px wide -- makeover-geometry's `SizeClass::Expanded` --
5194/// holding a group that has run out of room. A third tier would be a guess
5195/// about a shape nothing in the tree has yet.
5196///
5197/// # Why it is not `SizeClass`
5198///
5199/// Because 913 is exactly the case that proves they are different facts. The
5200/// window is roomy and the group is not, so a type that answered for both would
5201/// have to be wrong about one of them. Sharing the name would also invite
5202/// `@media` thinking straight back in, which is what put a `position: absolute`
5203/// in goingson's stylesheet in the first place. Container semantics instead: a
5204/// group narrowed by a sidebar behaves the same as one narrowed by the window,
5205/// and there is one code path rather than two.
5206///
5207/// Ordered least room first, [`Priority`]'s convention, so a group nesting
5208/// another takes the minimum of the two and relief still resolves inside-out.
5209#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
5210#[non_exhaustive]
5211pub enum Room {
5212    /// Not everything the group contains fits, and the group's [`Fallback`]
5213    /// decides what happens.
5214    Tight,
5215    /// Everything fits as described.
5216    Ample,
5217}
5218
5219/// What a group does when it is [`Room::Tight`].
5220///
5221/// Authored, and required: the field carrying this has no `Default` and a group
5222/// cannot be described without saying what it does when it runs out of room.
5223/// Max ruled on that 2026-08-18 -- more intentionality from layout designers is
5224/// acceptable so long as the constraints are solvable, because the goal is
5225/// enabling good layouts rather than rescuing bad ones. A default here would be
5226/// the crate guessing, and the guess would be silently wrong on the screens
5227/// that matter.
5228///
5229/// Relief resolves inside-out. A group asks its children to fall back before
5230/// falling back itself, or an outer group collapses while an inner one still
5231/// had slack.
5232///
5233/// # No `Swap`
5234///
5235/// An authored alternate group for the tight case is deliberately out of the
5236/// first cut. It doubles the description for that group and the two halves can
5237/// drift, which is the failure this vocabulary exists to end. Add it when a
5238/// site proves it needs one.
5239///
5240/// `#[non_exhaustive]`, [`Width`]'s reasoning. Unlike [`Priority`] there is no
5241/// order to preserve, so a member can be appended.
5242#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5243#[non_exhaustive]
5244pub enum Fallback {
5245    /// One row becomes two. Every member stays, in the order described.
5246    Wrap,
5247    /// A row becomes a column. Every member stays, full width.
5248    Stack,
5249    /// Members drop by [`Priority`], down to [`Priority::Essential`].
5250    ///
5251    /// What a narrow table already does with its columns, applied to a group.
5252    /// What drops is gone from the screen, so this is right when the dropped
5253    /// members are facts the reader can do without and wrong when they are the
5254    /// only way to act.
5255    Shed,
5256    /// The members [`Shed`](Self::Shed) would drop move into one overflow
5257    /// control instead.
5258    ///
5259    /// The answer when a group holds actions. A control is not a fact: dropping
5260    /// it does not cost the reader a detail, it costs them the only way to act,
5261    /// which is [`RowPart::priority`]'s argument one level up.
5262    Menu,
5263}
5264
5265/// One column of a table.
5266///
5267/// Described once. The grid track, the cell order and the drop behaviour are
5268/// all derived from this, rather than being three hand-written encodings that
5269/// must agree and are never checked against each other.
5270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5271pub struct Column<'a> {
5272    /// The heading, and the name the cell is addressed by.
5273    pub name: &'a str,
5274    /// How much room it asks for.
5275    pub width: Width,
5276    /// What it is worth when room runs out.
5277    pub priority: Priority,
5278    /// Whether the user can reorder the table by this column.
5279    ///
5280    /// `ce620871`. What reordering *calls* is not here — that is an address, and
5281    /// this crate names none — so a host pairs this with the route the way it
5282    /// pairs a row's parts with the row's activation. This says the affordance
5283    /// exists, which is what a renderer needs to draw a header a user can press
5284    /// rather than a heading they cannot.
5285    pub sortable: bool,
5286    /// Which way the table is ordered by this column, if it is.
5287    ///
5288    /// `None` on every column but the one in force. A renderer draws the caret
5289    /// from this and a webview sets `aria-sort`, which is why it is per column
5290    /// rather than a single fact on the table: the host idiom is a property of
5291    /// the header cell.
5292    ///
5293    /// Independent of [`sortable`](Self::sortable) rather than implied by it,
5294    /// because both combinations mean something. A column sorted and not
5295    /// sortable is a list ordered by a key the user cannot change, which is a
5296    /// real thing to describe and a caret worth drawing.
5297    pub sorted: Option<Sort>,
5298}
5299
5300/// Which way a column is ordered.
5301///
5302/// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
5303/// `None`, and folding it in here would be the same absence said twice.
5304#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5305pub enum Sort {
5306    /// Smallest, earliest or first alphabetically at the top.
5307    Ascending,
5308    /// The other way.
5309    Descending,
5310}
5311
5312impl Sort {
5313    /// The other direction, for a header that flips when pressed.
5314    #[must_use]
5315    pub const fn reversed(self) -> Self {
5316        match self {
5317            Self::Ascending => Self::Descending,
5318            Self::Descending => Self::Ascending,
5319        }
5320    }
5321
5322    /// What a webview writes into `aria-sort`.
5323    ///
5324    /// Named here rather than in the webview renderer because a terminal and an
5325    /// immediate-mode painter both want the same two words for a caret's label,
5326    /// and three renderers picking their own is the drift this crate ends.
5327    #[must_use]
5328    pub const fn as_str(self) -> &'static str {
5329        match self {
5330            Self::Ascending => "ascending",
5331            Self::Descending => "descending",
5332        }
5333    }
5334
5335    /// The caret a renderer draws for this direction.
5336    ///
5337    /// Here for [`as_str`](Self::as_str)'s reason, said about a glyph rather
5338    /// than a word: three renderers picking their own is the drift this crate
5339    /// ends. They had picked their own — two on the solid triangles and
5340    /// `makeover-webview` on the arrows U+2191/U+2193 — and agreeing by
5341    /// coincidence in three files is not agreement.
5342    ///
5343    /// Settled 2026-08-16 (Max): the solid triangles, U+25B2 and U+25BC. The
5344    /// reason generalizes past this pair and is the house rule now — prefer the
5345    /// bolder, simpler glyph over the thinner or more complicated one. A third
5346    /// spelling is not open for re-argument.
5347    ///
5348    /// **Bare, with no spacing.** Where the gap goes is each renderer's
5349    /// business: `makeover-tui` and `makeover-immediate` carry a leading space
5350    /// inside their `TableStyle` string and a webview emits its own in
5351    /// `content`, so folding a space in here would make one of the two wrong.
5352    ///
5353    /// Neither face the web apps self-host carries these — IBM Plex Mono has one
5354    /// glyph in the whole geometric-shapes block and Lato has none — so a
5355    /// browser falls back per glyph until the in-house face ships with them
5356    /// drawn in (makeover `6d6d9146`, wiki `typography-standard`). Cosmetic
5357    /// drift in one renderer, not a reason to spell it three ways.
5358    #[must_use]
5359    pub const fn glyph(self) -> &'static str {
5360        match self {
5361            Self::Ascending => "\u{25B2}",
5362            Self::Descending => "\u{25BC}",
5363        }
5364    }
5365}
5366
5367impl<'a> Column<'a> {
5368    /// A column that absorbs slack and drops after the optional ones.
5369    #[must_use]
5370    pub const fn new(name: &'a str) -> Self {
5371        Self {
5372            name,
5373            width: Width::Fill,
5374            priority: Priority::Secondary,
5375            sortable: false,
5376            sorted: None,
5377        }
5378    }
5379
5380    /// Whether this column survives at the given cutoff.
5381    ///
5382    /// A renderer narrows by raising the cutoff, and never by counting
5383    /// positions.
5384    #[must_use]
5385    pub const fn kept_at(&self, cutoff: Priority) -> bool {
5386        (self.priority as u8) >= (cutoff as u8)
5387    }
5388}
5389
5390/// What a table cell holds.
5391///
5392/// [`RowPart`] for tables, and it exists for the same reason: a part that
5393/// carries a control is not text, and a renderer with one class for the whole
5394/// cell paints it as though it were. `makeover-webview` emitted a single
5395/// `.cell` until 0.25.0, so a button in a cell inherited the cell's content
5396/// colour, which is the exact drift [`RowPart::intent`] prevents for rows and
5397/// prevented for nothing here.
5398///
5399/// Four members, and the count is what quasi's `Cell` was measured to carry:
5400/// a value, tokens (33 cells across 22 server templates), actions (30 rows
5401/// carrying a control, 5 beside a value) and a link (35 cells across 18
5402/// templates). Nothing was added past what something holds.
5403///
5404/// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
5405/// lockstep event across three renderers.
5406///
5407/// # No hover-reveal
5408///
5409/// [`RowPart`] carried a `revealed_on_hover` until 0.13.0 retired it, and this
5410/// enum never gets one. A cell's actions are shown at rest in every consumer
5411/// measured, and a member nothing uses is one three renderers owe an answer
5412/// for.
5413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5414#[non_exhaustive]
5415pub enum CellPart {
5416    /// The cell's own text.
5417    Value,
5418    /// Small labelled things in the cell: a status badge, a chip.
5419    Tokens,
5420    /// Controls that act on what the row is about.
5421    Actions,
5422    /// The cell's value, where the value is itself a link.
5423    Link,
5424}
5425
5426impl CellPart {
5427    /// The content intent the part takes.
5428    ///
5429    /// One part is text and three are not, so three answer with the intent
5430    /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
5431    /// text side narrower: a cell's secondary and muted readings are the
5432    /// column's business, not the cell's.
5433    #[must_use]
5434    pub const fn intent(self) -> &'static str {
5435        match self {
5436            Self::Value => "content",
5437            // A token carries its own tone, and a part-level intent underneath
5438            // it would fight the token sitting on it.
5439            Self::Tokens => "content",
5440            // Actions carry controls rather than text.
5441            Self::Actions => "content",
5442            // A link takes the action colour from the control it is, rather
5443            // than the cell's text colour from the cell it sits in.
5444            Self::Link => "content",
5445        }
5446    }
5447}
5448
5449/// A named dimension a set can be narrowed by.
5450///
5451/// One word for six things that were six mechanisms. MNW's discover page filters
5452/// by free text, a flat any-of over item types, a tree of tags, a numeric range
5453/// over price, a nested one-of over AI tier, and a browse position in the tag
5454/// tree held separately from the tag selection — and the last two being separate
5455/// is the whole reason a filter row there needs a tick box *and* a chevron. The
5456/// panel is a mixed bag of hand-written controls because nothing named the thing
5457/// they all are.
5458///
5459/// Deliberately wider than that one page. audiofiles' library browser and
5460/// goingson's filters are the same shape, and a word that only fitted discover
5461/// would be discover's markup with a neutral name on it.
5462///
5463/// # What it does not say
5464///
5465/// **What picking a value calls.** This crate names no address, so a facet is
5466/// paired with routes the way a column's [`sortable`](Column::sortable) flag is
5467/// paired with what reordering calls.
5468///
5469/// **How a tree is drawn.** Indented rows, a column of panes, a breadcrumb and a
5470/// list: all four are honest renderings of the same described facet, and a
5471/// terminal will not pick the same one a browser does. [`FacetValue::depth`] is
5472/// what a renderer needs to draw any of them; the choice is not described.
5473///
5474/// **Which values to show.** A tag tree has thousands of nodes and a panel shows
5475/// a handful. Deciding which handful is the app's — it is the same question as
5476/// which rows go in a table, and no table member answers it either.
5477#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5478#[non_exhaustive]
5479pub struct Facet<'a> {
5480    /// What the dimension is called, as the user reads it.
5481    pub name: &'a str,
5482    /// How many of its values may be in force, and in what shape.
5483    pub mode: Selecting,
5484    /// The values on offer, in the order they are drawn.
5485    ///
5486    /// A [`Selecting::Text`] facet has none: the value is whatever was typed,
5487    /// and a description that listed the possible strings would be listing the
5488    /// corpus. A [`Selecting::Range`] facet has none either, for the reason
5489    /// [`FieldKind::Range`] takes bounds rather than options — the ends are the
5490    /// question and the values between them are not enumerable.
5491    pub values: &'a [FacetValue<'a>],
5492}
5493
5494impl<'a> Facet<'a> {
5495    /// A dimension with values to pick from.
5496    #[must_use]
5497    pub const fn new(name: &'a str, mode: Selecting, values: &'a [FacetValue<'a>]) -> Self {
5498        Self { name, mode, values }
5499    }
5500
5501    /// Whether the facet is narrowing the set right now.
5502    ///
5503    /// The question a renderer asks to decide whether to offer a way out of it,
5504    /// and the reason it is derived rather than carried: a facet with nothing
5505    /// standing is unengaged by construction, so a member saying so could
5506    /// disagree with the values beside it. [`Standing::Inherited`] does not
5507    /// count — something further up is what is doing the narrowing, and clearing
5508    /// a child that was never picked clears nothing.
5509    ///
5510    /// Always false for [`Selecting::Text`] and [`Selecting::Range`], which
5511    /// carry no values. A host that wants a clear affordance on those knows
5512    /// whether its own box is empty; the description does not hold the typed
5513    /// string.
5514    #[must_use]
5515    pub fn engaged(&self) -> bool {
5516        self.values.iter().any(|value| value.standing.is_picked())
5517    }
5518
5519    /// The deepest value in the facet, or zero when it is flat.
5520    ///
5521    /// What an indenting renderer needs to reserve a gutter before it draws the
5522    /// first row, which is "First paint is final paint" applied to a tree: a
5523    /// gutter widened as deeper values arrive is the reflow that rule forbids.
5524    #[must_use]
5525    pub fn reach(&self) -> u8 {
5526        self.values
5527            .iter()
5528            .map(|value| value.depth)
5529            .max()
5530            .unwrap_or(0)
5531    }
5532}
5533
5534/// How many of a [`Facet`]'s values may be in force, and in what shape.
5535///
5536/// Five, and the fifth is what made this an enum rather than a bool. `one-of`,
5537/// `any-of`, a range and free text are the four a form vocabulary already has in
5538/// [`FieldKind`]; a tree's selection is none of them, and describing tags as
5539/// any-of was what forced browsing to be a second mechanism beside filtering.
5540#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5541#[non_exhaustive]
5542pub enum Selecting {
5543    /// Exactly one value, and picking another replaces it.
5544    ///
5545    /// MNW's AI tier, whose three options are nested ranges rather than
5546    /// independent values, so two of them at once means nothing.
5547    OneOf,
5548    /// Any number of values, each independent of the others.
5549    AnyOf,
5550    /// A low end, a high end, or both.
5551    ///
5552    /// Carries no values for [`FieldKind::Range`]'s reason: the ends are the
5553    /// question.
5554    Range,
5555    /// Whatever the user types.
5556    Text,
5557    /// A position in a tree, edited by taking branches in and pruning branches
5558    /// out.
5559    ///
5560    /// The one mode that is not reducible to the others, and the one gesture
5561    /// that replaced two. Picking a value narrows the set to it *and* reveals
5562    /// its children, so browsing a tree and filtering by it stop being separate
5563    /// mechanisms with separate state. What a selection then is: a set of
5564    /// branches taken and a set pruned, resolved nearest-ancestor-first, so
5565    /// `music` in and `music/synths` out is sayable and no flat mode can say it.
5566    ///
5567    /// Resolution happens in the app, and what reaches a renderer is the
5568    /// [`Standing`] each drawn value ended up with. A renderer walking ancestors
5569    /// itself would be a renderer that can disagree with the results beside it.
5570    Subtree,
5571}
5572
5573impl Selecting {
5574    /// Whether the mode picks from values the description lists.
5575    ///
5576    /// False for [`Text`](Self::Text) and [`Range`](Self::Range), which are the
5577    /// two whose answer is not one of a set. A renderer asks this before it
5578    /// looks at [`Facet::values`], the way it asks
5579    /// [`FieldKind::offers_options`] before it looks at [`Field::options`].
5580    #[must_use]
5581    pub const fn offers_values(self) -> bool {
5582        matches!(self, Self::OneOf | Self::AnyOf | Self::Subtree)
5583    }
5584
5585    /// Whether a value can be pruned as well as picked.
5586    ///
5587    /// [`Subtree`](Self::Subtree) alone. Excluding a value from a flat facet is
5588    /// the same fact as not picking it, so an exclude affordance there would be
5589    /// a second control for a state the first one already holds.
5590    #[must_use]
5591    pub const fn prunes(self) -> bool {
5592        matches!(self, Self::Subtree)
5593    }
5594
5595    /// Whether picking a second value keeps the first.
5596    #[must_use]
5597    pub const fn accumulates(self) -> bool {
5598        matches!(self, Self::AnyOf | Self::Subtree)
5599    }
5600}
5601
5602/// One value a [`Facet`] offers, as it currently stands.
5603#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5604#[non_exhaustive]
5605pub struct FacetValue<'a> {
5606    /// What identifies it, and what a host keys its route on.
5607    ///
5608    /// [`Choice::value`]'s split, and a tree is why it is not optional: two
5609    /// leaves under different parents are legitimately both called "Ambient",
5610    /// and the path is the only thing telling them apart. It is also what
5611    /// nearest-ancestor-wins resolves over, so an app that carried only labels
5612    /// could not compute the [`standing`](Self::standing) it hands back here.
5613    pub value: &'a str,
5614    /// What it is called, as the user reads it.
5615    ///
5616    /// The leaf's own name rather than its path: a facet drawn as an indented
5617    /// tree repeats every ancestor on every line otherwise, and one drawn as a
5618    /// breadcrumb has the ancestors already.
5619    pub label: &'a str,
5620    /// How many members of the set carry it.
5621    ///
5622    /// Optional, and settled that way rather than made mandatory: a count is a
5623    /// measured fact the app may not have. Counting a tag subtree under an
5624    /// active text search is a second query, and an app that will not pay for it
5625    /// should be able to describe the facet anyway rather than write a zero that
5626    /// reads as "none of them". That is [`Awaiting::amount`]'s rule in a second
5627    /// place — state a number when it was measured, and nothing when it was not.
5628    pub count: Option<u64>,
5629    /// Whether it is narrowing the set, and how it came to be.
5630    pub standing: Standing,
5631    /// How far down the tree it sits, counting from zero at the root.
5632    ///
5633    /// Always zero for a flat facet, which is what makes an indenting renderer
5634    /// one code path rather than two. A renderer that draws no tree at all still
5635    /// reads this, since a value's depth is what distinguishes two same-named
5636    /// leaves under different parents.
5637    pub depth: u8,
5638    /// Whether taking it reveals values under it.
5639    ///
5640    /// Distinct from having a nonzero [`depth`](Self::depth): a leaf deep in the
5641    /// tree branches no further, and a root with children does. Both facts are
5642    /// needed and neither implies the other, which is why the pair is two
5643    /// members rather than one count.
5644    pub branching: bool,
5645}
5646
5647impl<'a> FacetValue<'a> {
5648    /// An unpicked value at the root of the facet.
5649    #[must_use]
5650    pub const fn new(value: &'a str, label: &'a str) -> Self {
5651        Self {
5652            value,
5653            label,
5654            count: None,
5655            standing: Standing::Open,
5656            depth: 0,
5657            branching: false,
5658        }
5659    }
5660
5661    /// A value whose identifier is also what the user reads.
5662    ///
5663    /// [`Choice::of`]'s convenience, and it is the flat case: a type or a tier
5664    /// is its own name, and only a tree needs a path that is not one.
5665    #[must_use]
5666    pub const fn of(value: &'a str) -> Self {
5667        Self::new(value, value)
5668    }
5669
5670    /// How many members carry it, when that was measured.
5671    #[must_use]
5672    pub const fn counted(mut self, count: u64) -> Self {
5673        self.count = Some(count);
5674        self
5675    }
5676
5677    /// How it stands in the current selection.
5678    #[must_use]
5679    pub const fn standing(mut self, standing: Standing) -> Self {
5680        self.standing = standing;
5681        self
5682    }
5683
5684    /// Where it sits in the tree, and whether anything hangs off it.
5685    #[must_use]
5686    pub const fn at(mut self, depth: u8, branching: bool) -> Self {
5687        self.depth = depth;
5688        self.branching = branching;
5689        self
5690    }
5691}
5692
5693/// Whether a [`FacetValue`] is narrowing the set, and how it came to be.
5694///
5695/// Four rather than a bool, and the two extra members are what a tree costs. A
5696/// pruned branch and an untaken one are not the same state — one was decided
5697/// against and the other was never reached — and a child under a taken parent is
5698/// in force without anybody having picked it. A renderer given a bool either
5699/// marks every descendant of a taken branch, which reads as forty deliberate
5700/// choices, or marks none of them, which reads as unfiltered.
5701#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
5702#[non_exhaustive]
5703pub enum Standing {
5704    /// Not picked, and nothing above it is either.
5705    #[default]
5706    Open,
5707    /// Picked here. The set is narrowed to it and whatever hangs off it.
5708    Taken,
5709    /// In force because something above it was taken.
5710    Inherited,
5711    /// Pruned out, though something above it was taken.
5712    ///
5713    /// The state that only [`Selecting::Subtree`] can reach, and the reason
5714    /// exclusion is drawn as a visible affordance beside each label rather than
5715    /// as a modifier on the ordinary one: a gesture a terminal cannot express is
5716    /// a gesture half the renderers would have to leave out, and an affordance
5717    /// nothing teaches is one users do not find.
5718    Pruned,
5719}
5720
5721impl Standing {
5722    /// Whether the user decided this value, either way.
5723    ///
5724    /// True for [`Taken`](Self::Taken) and [`Pruned`](Self::Pruned) — both are
5725    /// choices, and both are things a "clear this" affordance has to clear.
5726    /// [`Inherited`](Self::Inherited) is not: clearing it clears nothing,
5727    /// because the decision is further up.
5728    #[must_use]
5729    pub const fn is_picked(self) -> bool {
5730        matches!(self, Self::Taken | Self::Pruned)
5731    }
5732
5733    /// Whether the value narrows the set in.
5734    ///
5735    /// [`Taken`](Self::Taken) and [`Inherited`](Self::Inherited): one was picked
5736    /// and one came down from above, and to the set they mean the same thing.
5737    /// The pair is named here so a renderer colouring in-force values does not
5738    /// have to know which is which.
5739    #[must_use]
5740    pub const fn in_force(self) -> bool {
5741        matches!(self, Self::Taken | Self::Inherited)
5742    }
5743
5744    /// The content intent the value takes.
5745    ///
5746    /// [`Pruned`](Self::Pruned) reads back a step, which is the three-tone rule
5747    /// above rather than a new decision: a pruned branch is still a live control
5748    /// — pressing it takes the prune off — so it may not wear `content-muted`,
5749    /// and it is not the thing itself either.
5750    #[must_use]
5751    pub const fn intent(self) -> &'static str {
5752        match self {
5753            Self::Taken | Self::Inherited | Self::Open => "content",
5754            Self::Pruned => "content-secondary",
5755        }
5756    }
5757}
5758
5759#[cfg(test)]
5760mod tests {
5761    use super::*;
5762
5763    #[test]
5764    fn a_markdown_field_is_multiline_and_offers_nothing() {
5765        // The editing counterpart of markdown prose is still text: every host
5766        // can draw it, which is the whole reason the kind was addable.
5767        assert!(FieldKind::Rich.multiline());
5768        assert!(FieldKind::Textarea.multiline());
5769        assert!(!FieldKind::Text.multiline());
5770        // It is not a chooser and not a moment.
5771        assert!(!FieldKind::Rich.offers_options());
5772        assert!(!FieldKind::Rich.temporal());
5773        assert!(FieldKind::Rich.visible());
5774    }
5775
5776    #[test]
5777    fn only_the_numeric_kinds_are_measurable() {
5778        assert!(FieldKind::Number.measurable());
5779        assert!(FieldKind::Range.measurable());
5780        // An axis is measured in something and both its ends are in it, so the
5781        // unit is read once for the pair rather than per end.
5782        assert!(FieldKind::Interval.measurable());
5783        // A date is ordered and is not a quantity with a unit to choose: its
5784        // unit is fixed by the kind, so saying one would restate `kind`.
5785        for kind in [
5786            FieldKind::Text,
5787            FieldKind::Date,
5788            FieldKind::DateTime,
5789            FieldKind::Select,
5790            FieldKind::Checkbox,
5791            FieldKind::File,
5792        ] {
5793            assert!(!kind.measurable(), "{kind:?}");
5794        }
5795    }
5796
5797    #[test]
5798    fn a_field_carries_no_unit_until_one_is_given() {
5799        // Additive: absent is what every field described before 0.33.0 meant.
5800        let plain = Field::new(FieldKind::Number, "attack", "Attack");
5801        assert_eq!(plain.unit, None);
5802        let measured = Field {
5803            unit: Some("s"),
5804            ..Field::range("attack", "Attack", "0.001", "5")
5805        };
5806        assert_eq!(measured.unit, Some("s"));
5807        assert!(measured.kind.measurable());
5808    }
5809
5810    #[test]
5811    fn an_interval_states_both_ends_names() {
5812        // Stated rather than derived: the two measured sites disagree about
5813        // affix order, so a rule here would rename one of them.
5814        let suffixed = Field::interval("bpm_min", "bpm_max", "BPM");
5815        assert_eq!(suffixed.name, "bpm_min");
5816        assert_eq!(suffixed.upper_name, Some("bpm_max"));
5817        let prefixed = Field::interval("min_price", "max_price", "Price");
5818        assert_eq!(prefixed.name, "min_price");
5819        assert_eq!(prefixed.upper_name, Some("max_price"));
5820        assert_eq!(suffixed.kind, FieldKind::Interval);
5821    }
5822
5823    #[test]
5824    fn every_other_kind_has_no_upper_end() {
5825        // Additive: absent is what every field described before 0.34.0 meant.
5826        for kind in [FieldKind::Text, FieldKind::Number, FieldKind::Range] {
5827            assert_eq!(Field::new(kind, "n", "N").upper_name, None, "{kind:?}");
5828        }
5829        assert_eq!(Field::range("t", "T", "0", "1").upper_name, None);
5830    }
5831
5832    #[test]
5833    fn an_interval_owes_no_bounds_and_takes_the_axis_facts_once() {
5834        // A range's bounds are the control's extent and are owed; an interval's
5835        // are a rule on each end, which is Number's arrangement.
5836        let plain = Field::interval("bpm_min", "bpm_max", "BPM");
5837        assert!(!plain.bounded());
5838        let axis = Field {
5839            min: Some("0"),
5840            max: Some("300"),
5841            step: Some("1"),
5842            unit: Some("BPM"),
5843            ..Field::interval("bpm_min", "bpm_max", "BPM")
5844        };
5845        assert!(axis.bounded());
5846        assert_eq!(axis.unit, Some("BPM"));
5847        // Nothing here checks the crossing rule, exactly as nothing checks
5848        // `min` for a number: the description carries constraints and whoever
5849        // validated decides a value is wrong.
5850        assert!(axis.error.is_none());
5851    }
5852
5853    #[test]
5854    fn only_a_subtree_prunes_and_only_the_listing_modes_offer_values() {
5855        // Excluding a value from a flat facet is the same fact as not picking
5856        // it, so the affordance exists in exactly one mode.
5857        assert!(Selecting::Subtree.prunes());
5858        for mode in [
5859            Selecting::OneOf,
5860            Selecting::AnyOf,
5861            Selecting::Range,
5862            Selecting::Text,
5863        ] {
5864            assert!(!mode.prunes(), "{mode:?}");
5865        }
5866        // Text and Range answer with something that is not one of a set.
5867        assert!(!Selecting::Text.offers_values());
5868        assert!(!Selecting::Range.offers_values());
5869        assert!(Selecting::OneOf.offers_values());
5870        assert!(Selecting::AnyOf.accumulates());
5871        assert!(!Selecting::OneOf.accumulates());
5872    }
5873
5874    #[test]
5875    fn an_inherited_value_is_in_force_without_having_been_picked() {
5876        // The distinction a bool cannot hold, and the reason Standing has four
5877        // members: a child under a taken parent narrows the set, and clearing
5878        // it clears nothing.
5879        assert!(Standing::Inherited.in_force());
5880        assert!(!Standing::Inherited.is_picked());
5881        assert!(Standing::Taken.in_force());
5882        assert!(Standing::Taken.is_picked());
5883        // A prune is a decision that takes the value out.
5884        assert!(Standing::Pruned.is_picked());
5885        assert!(!Standing::Pruned.in_force());
5886        assert!(!Standing::Open.is_picked());
5887        assert!(!Standing::Open.in_force());
5888        // A pruned branch still answers a press, so it may not read as inert.
5889        assert_ne!(Standing::Pruned.intent(), "content-muted");
5890    }
5891
5892    #[test]
5893    fn a_facet_is_engaged_by_a_decision_and_not_by_an_inherited_value() {
5894        let inherited = [
5895            FacetValue::of("music")
5896                .standing(Standing::Taken)
5897                .at(0, true),
5898            FacetValue::new("music/synths", "synths")
5899                .standing(Standing::Inherited)
5900                .at(1, false),
5901        ];
5902        let facet = Facet::new("Tag", Selecting::Subtree, &inherited);
5903        assert!(facet.engaged());
5904        // The gutter an indenting renderer reserves before its first paint.
5905        assert_eq!(facet.reach(), 1);
5906
5907        let untouched = [
5908            FacetValue::of("music").at(0, true),
5909            FacetValue::new("music/synths", "synths")
5910                .standing(Standing::Inherited)
5911                .at(1, false),
5912        ];
5913        // Inherited alone is something further up doing the narrowing, and
5914        // there is nothing further up here.
5915        assert!(!Facet::new("Tag", Selecting::Subtree, &untouched).engaged());
5916
5917        // A text facet lists nothing, so it is flat and never reads as engaged
5918        // from its values: the typed string is not held here.
5919        let typed = Facet::new("Search", Selecting::Text, &[]);
5920        assert!(!typed.engaged());
5921        assert_eq!(typed.reach(), 0);
5922    }
5923
5924    #[test]
5925    fn a_count_is_absent_rather_than_zero_when_it_was_not_measured() {
5926        // Awaiting::amount's rule in a second place: a written zero reads as
5927        // "none of them", which is a different claim from "not counted".
5928        assert_eq!(FacetValue::of("Ambient").count, None);
5929        assert_eq!(FacetValue::of("Ambient").counted(0).count, Some(0));
5930    }
5931
5932    #[test]
5933    fn one_kind_takes_files_and_the_two_file_members_are_its_alone() {
5934        assert!(FieldKind::File.takes_files());
5935        for kind in [
5936            FieldKind::Text,
5937            FieldKind::Textarea,
5938            FieldKind::Rich,
5939            FieldKind::Select,
5940            FieldKind::Checkbox,
5941            FieldKind::Hidden,
5942        ] {
5943            assert!(!kind.takes_files());
5944        }
5945        // The default is a field that takes any one file, which is what an
5946        // input with no accept and no multiple already is.
5947        let plain = Field::new(FieldKind::File, "cover", "Cover");
5948        assert!(plain.accept.is_empty());
5949        assert!(!plain.multiple);
5950    }
5951
5952    #[test]
5953    fn an_accept_list_says_which_disclosure_and_a_suffix_says_none() {
5954        // The three shapes are the MNW server's own three, and the family is
5955        // the question a renderer asks before it keeps room for a preview.
5956        assert_eq!(
5957            Accepted::Family(Family::Image).family(),
5958            Some(Family::Image)
5959        );
5960        assert_eq!(Accepted::Type("image/jpeg").family(), Some(Family::Image));
5961        assert_eq!(Accepted::Type("audio/flac").family(), Some(Family::Audio));
5962        assert_eq!(
5963            Accepted::Type("video/quicktime").family(),
5964            Some(Family::Video)
5965        );
5966        // A media type outside the three families names none, and neither does
5967        // a suffix. `.mp3` is audio in fact and this crate will not infer it:
5968        // the table that said so would rot.
5969        assert_eq!(Accepted::Type("text/csv").family(), None);
5970        assert_eq!(Accepted::Suffix(".mp3").family(), None);
5971        assert_eq!(Accepted::Suffix(".tar.gz").family(), None);
5972        // Media types are case-insensitive and half the tree writes them
5973        // lowercase by habit rather than by rule.
5974        assert_eq!(Accepted::Type("IMAGE/PNG").family(), Some(Family::Image));
5975    }
5976
5977    #[test]
5978    fn every_accepted_entry_has_one_spelling_a_host_can_write() {
5979        assert_eq!(Accepted::Family(Family::Image).as_str(), "image/*");
5980        assert_eq!(Accepted::Family(Family::Audio).as_str(), "audio/*");
5981        assert_eq!(Accepted::Family(Family::Video).as_str(), "video/*");
5982        assert_eq!(Accepted::Type("text/csv").as_str(), "text/csv");
5983        assert_eq!(Accepted::Suffix(".tar.gz").as_str(), ".tar.gz");
5984    }
5985
5986    #[test]
5987    fn a_list_accepting_two_families_still_has_a_disclosure_to_offer() {
5988        // The measured dropzone: `accept="image/*,video/*"`. There is no single
5989        // family to return and there is still a preview to keep room for, which
5990        // is why the question is asked of the list rather than of one entry.
5991        const MEDIA: &[Accepted<'_>] = &[
5992            Accepted::Family(Family::Image),
5993            Accepted::Family(Family::Video),
5994        ];
5995        assert!(Field::upload("media", "Media", MEDIA).accepts_media());
5996        // An installer's suffix list wants no disclosure, which is the measured
5997        // case rather than a hypothetical one.
5998        const BUILDS: &[Accepted<'_>] = &[Accepted::Suffix(".zip"), Accepted::Suffix(".dmg")];
5999        assert!(!Field::upload("build", "Build", BUILDS).accepts_media());
6000        // And a field that takes anything says so by listing nothing.
6001        assert!(!Field::upload("any", "File", &[]).accepts_media());
6002    }
6003
6004    #[test]
6005    fn an_upload_carries_its_list_and_takes_one_file_until_it_says_otherwise() {
6006        const IMAGES: &[Accepted<'_>] = &[
6007            Accepted::Type("image/jpeg"),
6008            Accepted::Type("image/png"),
6009            Accepted::Type("image/webp"),
6010        ];
6011        let avatar = Field::upload("avatar", "Avatar", IMAGES);
6012        assert_eq!(avatar.kind, FieldKind::File);
6013        assert_eq!(avatar.accept, IMAGES);
6014        assert!(!avatar.multiple);
6015        let several = Field {
6016            multiple: true,
6017            ..avatar
6018        };
6019        assert!(several.multiple);
6020    }
6021
6022    #[test]
6023    fn the_four_readiness_states_are_one_axis_and_only_one_shows_content() {
6024        // Mutually exclusive is the test for one enum against several fields: a
6025        // region shows its content, or that it is coming, or that there is none,
6026        // or that it broke. Never two.
6027        assert!(Readiness::Ready.shows_content());
6028        for state in [Readiness::Pending, Readiness::Empty, Readiness::Failed] {
6029            assert!(!state.shows_content());
6030        }
6031    }
6032
6033    #[test]
6034    fn a_region_shows_all_of_its_children_unless_it_says_otherwise() {
6035        // The default is the behaviour every region had before this member
6036        // existed, which is what keeps it additive: a description written
6037        // against 0.22.0 says the same thing under 0.23.0.
6038        assert_eq!(Showing::default(), Showing::All);
6039        assert!(!Showing::All.selective());
6040    }
6041
6042    #[test]
6043    fn only_a_disclosure_can_show_nothing() {
6044        // The two derived idioms differ in one respect and this is it. A
6045        // carousel's row moves between frames and never reaches empty; a
6046        // disclosure's summary line is the same control wearing its closed
6047        // state, so a renderer has to know which it is drawing.
6048        assert!(Showing::AtMostOne.dismissible());
6049        assert!(!Showing::One.dismissible());
6050        assert!(!Showing::All.dismissible());
6051
6052        // Both are selective, though. Deriving chrome is one question and
6053        // whether that chrome closes is another.
6054        assert!(Showing::One.selective());
6055        assert!(Showing::AtMostOne.selective());
6056    }
6057
6058    #[test]
6059    fn an_empty_region_is_not_a_broken_one() {
6060        // An empty list is the normal state of a new install. Drawing it in a
6061        // danger tone reports a fault where there is none, and this is the one
6062        // place the distinction is carried.
6063        assert_eq!(Readiness::Empty.tone(), Tone::Neutral);
6064        assert_eq!(Readiness::Failed.tone(), Tone::Danger);
6065        assert_eq!(Readiness::Pending.tone(), Tone::Neutral);
6066    }
6067
6068    #[test]
6069    fn a_column_can_be_sorted_without_being_sortable() {
6070        // Both combinations mean something, which is why the two fields are
6071        // independent rather than one implying the other. A list ordered by a
6072        // key the user cannot change is a real thing with a caret worth drawing.
6073        let fixed = Column {
6074            sorted: Some(Sort::Descending),
6075            ..Column::new("Created")
6076        };
6077
6078        assert!(!fixed.sortable);
6079        assert_eq!(fixed.sorted.map(Sort::as_str), Some("descending"));
6080
6081        let offered = Column {
6082            sortable: true,
6083            ..Column::new("Name")
6084        };
6085        assert_eq!(offered.sorted, None);
6086    }
6087
6088    #[test]
6089    fn a_direction_flips_and_says_what_it_is() {
6090        assert_eq!(Sort::Ascending.reversed(), Sort::Descending);
6091        assert_eq!(Sort::Descending.reversed().reversed(), Sort::Descending);
6092        assert_eq!(Sort::Ascending.as_str(), "ascending");
6093    }
6094
6095    #[test]
6096    fn a_direction_carries_its_caret_and_the_two_are_not_the_same_glyph() {
6097        // The spelling every renderer reads, so that agreeing is composition
6098        // rather than three files happening to hold the same literal.
6099        assert_eq!(Sort::Ascending.glyph(), "\u{25B2}");
6100        assert_eq!(Sort::Descending.glyph(), "\u{25BC}");
6101        assert_ne!(Sort::Ascending.glyph(), Sort::Descending.glyph());
6102        // Bare. The gap is the renderer's, and a space here would be a second
6103        // one wherever a renderer already carries its own.
6104        for d in [Sort::Ascending, Sort::Descending] {
6105            assert_eq!(d.glyph().trim(), d.glyph());
6106        }
6107    }
6108
6109    #[test]
6110    fn a_figure_carries_its_tone_because_no_renderer_can_derive_it() {
6111        // Three of goingson's five sites tone the figure by their own means, so
6112        // tone is carried at every site that needs it and derived at none. The
6113        // same reasoning `Meter` reached, from a different direction.
6114        let streak = Figure::new("0", "Current Streak").tone(Tone::Warning);
6115        assert_eq!(streak.tone, Tone::Warning);
6116        assert_eq!(Figure::new("17", "Total").tone, Tone::Neutral);
6117    }
6118
6119    #[test]
6120    fn a_figures_change_is_the_toned_part_and_is_absent_by_default() {
6121        // 0.13.0. The MNW server's stat card is a label, a value and a delta,
6122        // across four screens, and the delta is what reads as good or bad. Tone
6123        // had no consumer before this: the figure itself is an ordinary fact.
6124        let views = Figure::new("1,204", "Views")
6125            .change("+12.5%")
6126            .tone(Tone::Success);
6127        assert_eq!(views.change, Some("+12.5%"));
6128        assert_eq!(views.tone, Tone::Success);
6129
6130        // A figure with nothing to compare against says so by having no change,
6131        // rather than by carrying an empty string a renderer has to test for.
6132        assert_eq!(Figure::new("3.1%", "Conversion").change, None);
6133    }
6134
6135    #[test]
6136    fn a_figures_value_is_text_because_only_the_app_knows_what_it_is() {
6137        // "84%", "12/30", "3d". A figure is whatever the app computed, already
6138        // formatted, and that is the line between this and `Meter`: a meter is
6139        // a proportion a renderer draws, a figure is a fact it sets in type.
6140        for value in ["84%", "12/30", "3d"] {
6141            assert_eq!(Figure::new(value, "Rate").value, value);
6142        }
6143    }
6144
6145    #[test]
6146    fn a_proportion_is_a_row_part_and_takes_no_intent_of_its_own() {
6147        // The meter carries the tone, so a part-level intent underneath would
6148        // fight it. Same answer `Tokens` needed, for the same reason.
6149        assert_eq!(RowPart::Proportion.intent(), RowPart::Tokens.intent());
6150    }
6151
6152    #[test]
6153    fn a_file_field_is_drawn_and_offers_no_options() {
6154        // It is a control the user operates, unlike `Hidden`, and it does not
6155        // pick from a list the description carries, unlike `Select`.
6156        assert!(FieldKind::File.visible());
6157        assert!(!FieldKind::File.offers_options());
6158        assert!(!FieldKind::File.confidential());
6159    }
6160
6161    #[test]
6162    fn a_constraint_is_a_fact_about_the_question_and_not_a_verdict() {
6163        // The whole model: the description carries the rule, the renderer emits
6164        // its host's idiom, and `error` is what arrives back when someone
6165        // validated. Nothing here decides a value is wrong.
6166        let field = Field {
6167            max_length: Some(100),
6168            min: Some("1"),
6169            max: Some("240"),
6170            required: true,
6171            ..Field::new(FieldKind::Number, "minutes", "Minutes")
6172        };
6173        assert!(!field.invalid());
6174
6175        // A bound is text because it is only a number for some of the kinds
6176        // that take one. goingson has both shapes live.
6177        let when = Field {
6178            min: Some("2026-08-09T14:30"),
6179            ..Field::new(FieldKind::Text, "starts", "Starts")
6180        };
6181        assert_eq!(when.min, Some("2026-08-09T14:30"));
6182    }
6183
6184    #[test]
6185    fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
6186        // The whole reason this is a pair. goingson's `Task::time_progress`
6187        // clamps to 100 and then carries `is_over_estimate` beside it to say
6188        // what the clamp dropped; a meter says both from one fact.
6189        let over = Meter::new(45, 30);
6190        assert_eq!(over.percent(), 100);
6191        assert!(over.overflowing());
6192
6193        let exact = Meter::new(30, 30);
6194        assert_eq!(exact.percent(), over.percent());
6195        assert!(!exact.overflowing());
6196    }
6197
6198    #[test]
6199    fn an_empty_set_does_not_divide_by_zero() {
6200        // Sayable on purpose, so it has to be answerable. A meter over an
6201        // unloaded count is what an app actually has for a frame.
6202        let none = Meter::new(0, 0);
6203        assert_eq!(none.percent(), 0);
6204        assert!(none.is_empty());
6205        assert!(!none.overflowing());
6206    }
6207
6208    #[test]
6209    fn the_ratio_survives_where_a_percentage_would_not() {
6210        // Given 43 nothing can recover "3 of 7", which is why the numbers are
6211        // carried and the label names only the noun.
6212        let m = Meter::new(3, 7).label("subtasks");
6213        assert_eq!(m.percent(), 42);
6214        assert_eq!((m.done, m.total), (3, 7));
6215        assert_eq!(m.label, Some("subtasks"));
6216    }
6217
6218    #[test]
6219    fn tone_is_carried_because_no_renderer_can_derive_it() {
6220        // The same fullness means opposite things on two of goingson's bars,
6221        // and only the app knows which.
6222        let subtasks = Meter::new(9, 10).tone(Tone::Success);
6223        let estimate = Meter::new(9, 10).tone(Tone::Danger);
6224        assert_eq!(subtasks.percent(), estimate.percent());
6225        assert_ne!(subtasks.tone, estimate.tone);
6226        // Untoned by default: a bar says nothing about status until something
6227        // says so, the same way a row is not selectable until told.
6228        assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
6229    }
6230
6231    #[test]
6232    fn an_act_is_reachable_until_it_is_disabled() {
6233        // The one member a renderer must branch on, and since 0.19.0 the only
6234        // member there is. A stated state is not by itself a reason to stop
6235        // answering, which is the distinction `State` makes and every
6236        // hand-rolled button in the tree had to remember.
6237        assert!(!Act::new("Save").disabled());
6238        assert!(Act::new("Save").state(State::Disabled).disabled());
6239    }
6240
6241    #[test]
6242    fn an_act_carries_its_key_because_a_terminal_has_nothing_else() {
6243        // No key is the ordinary case, and the webview hosts that ignore it
6244        // are why it stayed optional.
6245        assert_eq!(Act::new("Delete").key, None);
6246        let quit = Act::new("Quit").key("q").tone(Tone::Danger);
6247        assert_eq!(quit.key, Some("q"));
6248        assert_eq!(quit.tone, Tone::Danger);
6249    }
6250
6251    #[test]
6252    fn a_meter_does_not_overflow_on_large_counts() {
6253        // done * 100 in u32 would wrap somewhere past 42 million. Counts that
6254        // size are not tasks, but a description layer that silently reports 3%
6255        // for a full bar is worse than one that is slow.
6256        let big = Meter::new(u32::MAX, u32::MAX);
6257        assert_eq!(big.percent(), 100);
6258        assert!(!big.overflowing());
6259    }
6260
6261    #[test]
6262    fn inset_is_raised_with_the_light_moved() {
6263        let (rl, rd) = Bevel::Raised.edges();
6264        let (il, id) = Bevel::Inset.edges();
6265        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
6266        assert_eq!((il, id), (rd, rl));
6267    }
6268
6269    #[test]
6270    fn pressing_twice_is_a_no_op() {
6271        for b in [Bevel::Raised, Bevel::Inset] {
6272            assert_eq!(b.pressed().pressed(), b);
6273        }
6274    }
6275
6276    #[test]
6277    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
6278        // The bug this vocabulary exists to make unrepresentable.
6279        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
6280        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
6281        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
6282        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
6283    }
6284
6285    #[test]
6286    fn state_is_orthogonal_to_depth() {
6287        // The reason State is its own axis and not a Depth member: a disabled
6288        // button and a disabled field are both disabled and are not the same
6289        // shape, which one shared variant could not have said.
6290        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
6291        assert_eq!(Depth::Well.fill(), Some(Fill::Well));
6292        assert!(State::Disabled.suppresses_interaction());
6293    }
6294
6295    #[test]
6296    fn only_disabled_stops_answering() {
6297        // Kept in spirit from the version where `Focus` was the counter-example:
6298        // suppressing interaction is `Disabled`'s alone, so a member added here
6299        // later does not get to inherit it by being a state.
6300        assert!(State::Disabled.suppresses_interaction());
6301    }
6302
6303    #[test]
6304    fn disabled_resolves_against_an_intent_makeover_already_derives() {
6305        // No new token, so this costs no `makeover` release.
6306        assert_eq!(State::Disabled.token(), "content-muted");
6307    }
6308
6309    #[test]
6310    fn flat_has_neither_edge_nor_fill() {
6311        assert_eq!(Depth::Flat.bevel(), None);
6312        assert_eq!(Depth::Flat.fill(), None);
6313    }
6314
6315    #[test]
6316    fn sunken_is_recessed_by_colour_with_no_edge() {
6317        // The one member carrying a fill without a bevel. A renderer that
6318        // assumes the two arrive together drops the fill silently, which is
6319        // exactly what makeover-webview did before 0.3.0.
6320        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
6321        assert_eq!(Depth::Sunken.bevel(), None);
6322    }
6323
6324    #[test]
6325    fn sunken_and_flat_are_different_claims() {
6326        // Both edgeless, and only one of them needs a colour. Collapsing them
6327        // is what left an unchosen tab unsayable.
6328        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
6329        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
6330    }
6331
6332    #[test]
6333    fn a_sunken_surface_is_not_a_well() {
6334        // Authored in opposite directions: makeover derives surface-well by
6335        // inverting against the theme's content colour, while surface-sunken is
6336        // authored and may sit darker than raised.
6337        assert_ne!(Fill::Sunken, Fill::Well);
6338        assert_eq!(Fill::Sunken.token(), "surface-sunken");
6339        assert_eq!(Fill::Well.token(), "surface-well");
6340    }
6341
6342    #[test]
6343    fn every_selector_describes_both_of_its_states() {
6344        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
6345        // unchosen option fell through to Flat at every renderer.
6346        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
6347            assert_ne!(
6348                s.chosen(),
6349                s.unchosen(),
6350                "{s:?} cannot tell picked from unpicked"
6351            );
6352        }
6353    }
6354
6355    #[test]
6356    fn only_a_tab_inverts_the_other_way() {
6357        // Tabs recede so the chosen one comes forward; a segment and a toggle
6358        // stand up so the chosen one is held in. That inversion is the whole
6359        // content of "picked" once colour is deferred, and it is why the three
6360        // are not one member with a flag.
6361        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
6362        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
6363
6364        for s in [Selector::Segmented, Selector::Toggle] {
6365            assert_eq!(s.unchosen(), Depth::Raised);
6366            assert_eq!(s.chosen(), Depth::Well);
6367            // Held in is what pressing produces: one appearance, two reasons.
6368            assert_eq!(s.unchosen().pressed(), s.chosen());
6369        }
6370    }
6371
6372    #[test]
6373    fn pressing_a_card_makes_a_well() {
6374        assert_eq!(Depth::Raised.pressed(), Depth::Well);
6375        assert_eq!(
6376            Depth::Raised.pressed().bevel(),
6377            Depth::Raised.bevel().map(Bevel::pressed)
6378        );
6379        // Only raised regions respond to being pressed.
6380        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
6381        assert_eq!(Depth::Well.pressed(), Depth::Well);
6382        // An overlay is a surface, not a control.
6383        assert_eq!(Depth::Overlay.pressed(), Depth::Overlay);
6384    }
6385
6386    #[test]
6387    fn an_overlay_is_lifted_rather_than_edged() {
6388        // The wave-2 rule: a surface over the page takes elevation, a surface
6389        // in the page takes a bevel. Both halves come off the one Depth, so
6390        // they cannot disagree.
6391        assert_eq!(Depth::Overlay.fill(), Some(Fill::Overlay));
6392        assert_eq!(Depth::Overlay.bevel(), None);
6393
6394        // Three depths have no bevel and they are not the same claim. Flat has
6395        // nothing to separate from, Sunken's colour is doing the separating,
6396        // and an overlay is separated by the lift.
6397        assert_ne!(Depth::Overlay.fill(), Depth::Sunken.fill());
6398        assert_ne!(Depth::Overlay.fill(), Depth::Flat.fill());
6399    }
6400
6401    #[test]
6402    fn a_note_is_neither_a_hint_nor_an_error() {
6403        // audiofiles' export Format field: choosing WAV over Original
6404        // re-encodes and drops the embedded metadata. Perfectly valid, and it
6405        // costs something.
6406        let format = Field {
6407            note: Some((Tone::Warning, "Re-encoding drops embedded BWF and iXML")),
6408            ..Field::select("format", "Format", &[])
6409        };
6410        assert!(!format.invalid(), "a note is not a validation failure");
6411        assert!(format.hint.is_none());
6412        assert!(format.error.is_none());
6413        assert_eq!(format.note.unwrap().0, Tone::Warning);
6414
6415        // The default is no note, so the 15 in-tree `..Field::new(..)`
6416        // literals absorb the member with no call-site edit.
6417        assert!(Field::new(FieldKind::Text, "title", "Title").note.is_none());
6418    }
6419
6420    #[test]
6421    fn neutral_is_content_not_muted_content() {
6422        // Neutral means "no status", and that is all it means. It answered
6423        // `content-muted` until 2026-08-27, which muted a figure's headline
6424        // number to the colour of its own caption. What makes a badge quiet
6425        // is `Token::Badge` answering no click, which lives on the renderer.
6426        assert_eq!(Tone::Neutral.token(), "content");
6427        assert!(!Token::Badge.interactive());
6428        assert_eq!(State::Disabled.token(), "content-muted");
6429    }
6430
6431    #[test]
6432    fn intents_name_makeover_tokens_and_nothing_else() {
6433        assert_eq!(Edge::Light.token(), "bevel-light");
6434        assert_eq!(Edge::Dark.token(), "bevel-dark");
6435        assert_eq!(Fill::Raised.token(), "surface-raised");
6436        assert_eq!(Fill::Well.token(), "surface-well");
6437        // No value ever leaves this crate.
6438        for t in [
6439            Edge::Light.token(),
6440            Edge::Dark.token(),
6441            Tone::Danger.token(),
6442            Tone::Neutral.token(),
6443            State::Disabled.token(),
6444        ] {
6445            assert!(!t.starts_with('#'), "{t} looks like a value");
6446            assert!(
6447                !t.chars().next().unwrap().is_ascii_digit(),
6448                "{t} is a value"
6449            );
6450        }
6451    }
6452
6453    #[test]
6454    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
6455        // The one line that runs through all three apps' taxonomies.
6456        assert!(!Token::Badge.interactive());
6457        assert!(Token::Chip { removable: false }.interactive());
6458        assert!(Token::Chip { removable: true }.interactive());
6459
6460        // A badge is a label, so giving it an edge would lie about it.
6461        assert_eq!(Token::Badge.depth(false), Depth::Flat);
6462        assert_eq!(Token::Badge.depth(true), Depth::Flat);
6463
6464        // A latched chip wears the same shape a pressed one does.
6465        let chip = Token::Chip { removable: false };
6466        assert_eq!(chip.depth(false), Depth::Raised);
6467        assert_eq!(chip.depth(true), Depth::Raised.pressed());
6468    }
6469
6470    #[test]
6471    fn a_toast_and_a_banner_differ_in_more_than_placement() {
6472        assert!(Notice::Toast.transient());
6473        assert!(!Notice::Banner.transient());
6474        // A toast floats above the page; a banner rests in the flow.
6475        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
6476        assert_eq!(Notice::Banner.fill(), Fill::Raised);
6477    }
6478
6479    #[test]
6480    fn emphasis_falls_off_down_the_row() {
6481        // `revealed_on_hover` was asserted here until 0.13.0 retired it. It said
6482        // a row's actions stay hidden until hover, which stopped being true when
6483        // makeover-webview 0.23.0 showed them at rest, and nothing had consumed
6484        // it for a release either way.
6485        assert_eq!(RowPart::Primary.intent(), "content");
6486        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
6487        assert_eq!(RowPart::Meta.intent(), "content-muted");
6488    }
6489
6490    #[test]
6491    fn a_token_part_carries_no_intent_of_its_own() {
6492        // Each token carries its own tone, so a part-level intent underneath
6493        // would fight the thing sitting on it. Same reasoning as actions, which
6494        // is why they answer alike.
6495        assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
6496        assert_eq!(RowPart::Tokens.intent(), "content");
6497    }
6498
6499    #[test]
6500    fn the_two_temporal_kinds_are_the_two_that_name_a_moment() {
6501        // The pair is named once so a host with parsing to do asks here rather
6502        // than spelling it out, which is `offers_options`' reason.
6503        assert!(FieldKind::Date.temporal());
6504        assert!(FieldKind::DateTime.temporal());
6505
6506        for kind in [
6507            FieldKind::Text,
6508            FieldKind::Secret,
6509            FieldKind::Number,
6510            FieldKind::Email,
6511            FieldKind::Url,
6512            FieldKind::Tel,
6513            FieldKind::Range,
6514            FieldKind::Textarea,
6515            FieldKind::Rich,
6516            FieldKind::Select,
6517            FieldKind::Radio,
6518            FieldKind::Checkbox,
6519            FieldKind::File,
6520            FieldKind::Hidden,
6521        ] {
6522            assert!(!kind.temporal(), "{kind:?}");
6523        }
6524    }
6525
6526    #[test]
6527    fn a_date_carries_no_time_and_a_datetime_carries_no_zone() {
6528        // The formats are the whole reason the members are worth naming apart
6529        // from text, so the doc comments and the constants have to agree. A
6530        // host reading one and meeting the other is the silent failure.
6531        assert_eq!(DATE_FORMAT, "%Y-%m-%d");
6532        assert!(!DATE_FORMAT.contains("%H"), "a day carries no hour");
6533
6534        assert_eq!(DATETIME_FORMAT, "%Y-%m-%dT%H:%M");
6535        assert!(
6536            DATETIME_FORMAT.starts_with(DATE_FORMAT),
6537            "a moment starts with the day it is on"
6538        );
6539        // Local, and that is a property of the value rather than an omission.
6540        assert!(!DATETIME_FORMAT.contains("%Z"), "no zone name");
6541        assert!(!DATETIME_FORMAT.ends_with('Z'), "not UTC-stamped");
6542        assert!(!DATETIME_FORMAT.contains("%S"), "no seconds by default");
6543    }
6544
6545    #[test]
6546    fn a_temporal_kind_takes_a_label_above_it_and_offers_no_options() {
6547        // Neither is a checkbox and neither is a fixed set, so both fall where
6548        // text does. Asserted because a new kind lands in three predicates and
6549        // only one of them is the interesting one.
6550        for kind in [FieldKind::Date, FieldKind::DateTime] {
6551            assert!(kind.visible(), "{kind:?}");
6552            assert!(!kind.confidential(), "{kind:?}");
6553            assert!(!kind.labels_itself(), "{kind:?}");
6554            assert!(!kind.offers_options(), "{kind:?}");
6555        }
6556    }
6557
6558    #[test]
6559    fn a_cell_part_names_an_intent_and_only_the_value_is_text() {
6560        // The table half of what RowPart::intent does for rows. A cell holding
6561        // a control and a cell holding text answered alike until 0.14.0, and a
6562        // control in a cell took the cell's text colour.
6563        assert_eq!(CellPart::Value.intent(), "content");
6564
6565        for part in [CellPart::Tokens, CellPart::Actions, CellPart::Link] {
6566            // Each for its own reason -- a token carries its tone, an action is
6567            // a control, a link takes the action colour -- and all three reach
6568            // the intent inheriting already gives.
6569            assert_eq!(part.intent(), CellPart::Value.intent(), "{part:?}");
6570        }
6571    }
6572
6573    #[test]
6574    fn every_cell_part_answers_with_a_token_and_never_a_value() {
6575        for part in [
6576            CellPart::Value,
6577            CellPart::Tokens,
6578            CellPart::Actions,
6579            CellPart::Link,
6580        ] {
6581            let intent = part.intent();
6582            assert!(!intent.is_empty(), "{part:?} names nothing");
6583            assert!(!intent.starts_with('#'), "{part:?} looks like a value");
6584        }
6585    }
6586
6587    #[test]
6588    fn a_separator_is_what_tells_a_section_from_a_subsection() {
6589        assert!(Heading::Section.separated());
6590        assert!(!Heading::Subsection.separated());
6591        assert!(!Heading::Page.separated());
6592    }
6593
6594    #[test]
6595    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
6596        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
6597        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
6598        // The exception, and the whole folder semantic: the open tab joins its
6599        // pane rather than sinking away from it.
6600        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
6601
6602        // A held-in segment is indistinguishable from a pressed raised one,
6603        // which is the economy the light model buys over a colour swap.
6604        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
6605
6606        // A toggle stands alone; the other two are built out of parts that
6607        // touch.
6608        assert!(Selector::Segmented.abutting());
6609        assert!(Selector::Tabs.abutting());
6610        assert!(!Selector::Toggle.abutting());
6611    }
6612
6613    #[test]
6614    fn columns_are_peers_and_a_split_is_not() {
6615        // The distinction the member exists for. A split's two panes stand in a
6616        // master-detail relationship; columns choose nothing about each other.
6617        // Both are flat, so depth cannot tell them apart and the doc has to.
6618        assert_eq!(Region::Columns.depth(), Depth::Flat);
6619        assert_eq!(Region::Split.depth(), Depth::Flat);
6620        assert_ne!(Region::Columns, Region::Split);
6621    }
6622
6623    #[test]
6624    fn columns_carry_no_count_and_no_share() {
6625        // The two things a board is always asked to carry and must not. How
6626        // many is what the children say; how wide is settled by "peers are
6627        // equal".
6628        //
6629        // The guard is the binding itself and it is a compile-time one: adding
6630        // a field to `Columns` stops this line compiling, which is a better
6631        // failure than any assertion about it. Written out rather than inlined
6632        // for exactly that reason.
6633        let columns: Region<'_> = Region::Columns;
6634        assert_eq!(columns.name(), None);
6635    }
6636
6637    #[test]
6638    fn columns_are_described_and_the_escape_hatch_is_still_one_member() {
6639        // A board's contents are ordinary description all the way down, so a
6640        // renderer that does not lay them across still draws every column.
6641        // Stacking them vertically is honouring this member, not degrading it.
6642        assert!(Region::Columns.described());
6643        assert!(!Region::Bespoke { name: "timeline" }.described());
6644    }
6645
6646    #[test]
6647    fn a_span_never_has_zero_minutes_however_it_is_asked_for() {
6648        // Every renderer divides by this. A caller passing a backwards or empty
6649        // span is a bug, but it is not a bug worth a panic three renderers deep.
6650        assert_eq!(Span::new(600, 600).length(), 1);
6651        assert_eq!(Span::new(600, 300).length(), 1);
6652        assert_eq!(Span::DAY.length(), 1440);
6653    }
6654
6655    #[test]
6656    fn a_span_can_run_past_midnight_without_a_second_date() {
6657        // 22:00 to 02:00. The alternative was carrying a date, which drags a
6658        // timezone into the vocabulary for the sake of one night shift.
6659        let overnight = Span::new(1320, 1560);
6660        assert_eq!(overnight.length(), 240);
6661        assert!(overnight.holds(1500));
6662        assert!(!overnight.holds(1200));
6663    }
6664
6665    #[test]
6666    fn overlap_is_computed_rather_than_declared() {
6667        // The reason Placement carries no `conflicts` flag: the times already
6668        // say it, and a second source for one fact is how a stale conflict
6669        // badge outlives the conflict.
6670        let morning = Placement::new(540, 60); // 09:00-10:00
6671        let overlapping = Placement::new(570, 60); // 09:30-10:30
6672        let after = Placement::new(600, 60); // 10:00-11:00
6673
6674        assert!(morning.overlaps(overlapping));
6675        assert!(overlapping.overlaps(morning), "overlap is symmetric");
6676        // Touching end to end is not overlapping: `to` is exclusive, so a
6677        // 10:00 start does not collide with a 10:00 end.
6678        assert!(!morning.overlaps(after));
6679        assert!(!after.overlaps(morning));
6680    }
6681
6682    #[test]
6683    fn a_placement_is_always_drawable() {
6684        assert_eq!(Placement::new(540, 0).length(), 1);
6685        assert_eq!(Placement::new(540, 30).end(), 570);
6686    }
6687
6688    #[test]
6689    fn a_track_places_the_fraction_every_renderer_would_otherwise_compute() {
6690        let day = Track::DAY;
6691        assert!((day.fraction(0) - 0.0).abs() < f32::EPSILON);
6692        assert!((day.fraction(720) - 0.5).abs() < f32::EPSILON);
6693        // Clamped rather than off the end: an event running past the span's
6694        // close draws at the edge, which beats panicking or drawing nowhere.
6695        assert!((day.fraction(2000) - 1.0).abs() < f32::EPSILON);
6696    }
6697
6698    #[test]
6699    fn a_track_counts_its_slots_and_never_divides_by_zero() {
6700        assert_eq!(Track::DAY.slots(), 96);
6701        assert_eq!(Track::over(Span::new(540, 1020)).slots(), 32);
6702        // A span that does not divide evenly keeps a slot for its tail.
6703        assert_eq!(Track::over(Span::new(0, 50)).slots(), 4);
6704        // slot: 0 is a caller bug that reads as one slot, not a panic.
6705        let degenerate = Track {
6706            span: Span::DAY,
6707            slot: 0,
6708            tick: 60,
6709            unit: Unit::Minutes,
6710        };
6711        assert_eq!(degenerate.slots(), 1);
6712    }
6713
6714    #[test]
6715    fn a_track_carries_facts_and_no_presentation() {
6716        // The guard on the thing the withdrawn refusal was right about. If a
6717        // pixel measure, a scroll offset or a colour ever lands on Track, the
6718        // member has stopped being a fact about the data and the timeline
6719        // really has become a component library wearing a description's name.
6720        let day = Track::DAY;
6721        assert_eq!(day.span, Span::DAY);
6722        assert_eq!(day.slot, 15);
6723        assert_eq!(day.tick, 60);
6724        assert_eq!(day.unit, Unit::Minutes);
6725
6726        // Three fields when this was written, and the fourth came here to say
6727        // why, which is the whole point of the assertion. `unit` is what the
6728        // integers COUNT -- a fact about the data, unavailable from the numbers
6729        // themselves, and the absence of it is what let a month strip render
6730        // under a wall clock. A fifth field still has to argue, and "the
6731        // renderer would find it handy" is still not the argument.
6732        // Destructured rather than rebuilt: this is the form that names every
6733        // field and stops compiling when a fifth arrives, without binding
6734        // anything a lint has to forgive.
6735        let Track {
6736            span: _,
6737            slot: _,
6738            tick: _,
6739            unit: _,
6740        } = day;
6741    }
6742
6743    #[test]
6744    fn a_day_strip_is_the_same_arithmetic_under_a_different_unit() {
6745        // The probe that found the defect, kept as a test. Fifteen days from
6746        // day three, on a thirty-one day month: the geometry was always right
6747        // and only the label was wrong, which is why `unit` is a fact and not
6748        // presentation.
6749        let march = Track::days(Span::new(0, 31));
6750        assert_eq!(march.slots(), 31);
6751        assert_eq!(march.unit, Unit::Days);
6752
6753        let leave = Placement::new(2, 15);
6754        assert!((march.fraction(leave.at()) - 2.0 / 31.0).abs() < 0.0001);
6755        assert!((march.fraction(leave.end()) - 17.0 / 31.0).abs() < 0.0001);
6756    }
6757
6758    #[test]
6759    fn a_pane_is_looked_into_and_a_band_is_not() {
6760        assert_eq!(Region::Pane.depth(), Depth::Well);
6761        assert_eq!(Region::Modal.depth(), Depth::Raised);
6762        for r in [
6763            Region::Band,
6764            Region::Sidebar,
6765            Region::Group,
6766            Region::Split,
6767            Region::TabGroup,
6768        ] {
6769            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
6770        }
6771    }
6772
6773    #[test]
6774    fn exactly_one_region_is_opaque() {
6775        // The escape hatch is one member and stays one member. If a second
6776        // undescribed region ever appears, the description has started
6777        // conceding rather than deferring.
6778        for r in [
6779            Region::Band,
6780            Region::Sidebar,
6781            Region::Pane,
6782            Region::Group,
6783            Region::Split,
6784            Region::TabGroup,
6785            Region::Modal,
6786            // A widget is described, and that is the whole of what separates it
6787            // from a bespoke here. Both carry a name this crate never reads;
6788            // only one of them has contents under it that a renderer which does
6789            // not know the name can still walk.
6790            Region::Widget { name: "carousel" },
6791        ] {
6792            assert!(r.described(), "{r:?} should be describable");
6793        }
6794        assert!(!Region::Bespoke { name: "day-plan" }.described());
6795    }
6796
6797    #[test]
6798    fn a_picture_that_says_nothing_is_a_claim_and_not_an_oversight() {
6799        // The distinction a renderer with no graphics protocol runs on: draw
6800        // the words, or draw nothing. Standing in for a decorative rule with
6801        // the word "decoration" is worse than leaving the space empty.
6802        assert!(Image::new("The library view, mid-import").speaks());
6803        assert!(!Image::new("").speaks());
6804    }
6805
6806    #[test]
6807    fn a_caption_and_alt_text_are_not_the_same_line() {
6808        // A caption is content everybody reads; alt text stands in for the
6809        // picture. A screenshot with a caption still needs alt text.
6810        let shot = Image::new("A file list with three rows selected").caption("The library view");
6811        assert_eq!(shot.caption, Some("The library view"));
6812        assert!(shot.speaks());
6813        assert_ne!(shot.alt, shot.caption.unwrap());
6814    }
6815
6816    #[test]
6817    fn a_picture_can_say_how_much_room_to_hold() {
6818        // The whole point: a renderer reserves from the ratio, so the space is
6819        // right at any width. A fixed height would only be right at one.
6820        let shot = Image::new("a screenshot").intrinsic(5120, 3412);
6821        let e = shot.intrinsic.expect("carried");
6822        assert_eq!((e.width, e.height), (5120, 3412));
6823        assert!((e.ratio().unwrap() - 1.5006).abs() < 0.001);
6824    }
6825
6826    #[test]
6827    fn a_picture_with_no_dimensions_reserves_nothing_rather_than_guessing() {
6828        // `None` is honest: a creator upload whose size was never recorded does
6829        // not know it. A renderer must not invent one.
6830        assert_eq!(Image::new("unknown upload").intrinsic, None);
6831        assert_eq!(Extent::new(0, 10).ratio(), None);
6832        assert_eq!(Extent::new(10, 0).ratio(), None);
6833    }
6834
6835    #[test]
6836    fn a_picture_is_wanted_now_unless_the_app_says_otherwise() {
6837        // Eager is the safe default and lazy is the opt-in, because deferring
6838        // something already on screen saves nothing and moves its shift later.
6839        assert_eq!(Image::new("hero").loading, Loading::Eager);
6840        assert_eq!(Loading::default(), Loading::Eager);
6841        assert_eq!(Image::new("frame 2").lazy().loading, Loading::Lazy);
6842    }
6843
6844    #[test]
6845    fn a_picture_keeps_its_own_proportions_unless_told_otherwise() {
6846        // The default is the one that shows the whole picture at its own shape,
6847        // so a renderer ignoring Fit entirely is still right about the common
6848        // case. The shipped MNW carousel sets no object-fit at all, which is
6849        // this.
6850        assert_eq!(Image::new("a").fit, Fit::Natural);
6851        assert_eq!(Fit::default(), Fit::Natural);
6852        assert_eq!(Image::new("a").fit(Fit::Cover).fit, Fit::Cover);
6853    }
6854
6855    #[test]
6856    fn a_group_contains_a_section_without_claiming_to_be_a_pane() {
6857        // The whole of why this is a member rather than a `Pane`. A pane is
6858        // looked into and scrolls; a group is neither, and four groups inside a
6859        // settings pane described as panes are four wells inside a well.
6860        assert_eq!(Region::Pane.depth(), Depth::Well);
6861        assert_eq!(Region::Group.depth(), Depth::Flat);
6862        assert_ne!(Region::Group, Region::Pane);
6863
6864        // Described, and it carries no name: a group is a primitive every
6865        // renderer draws from scratch, which is what separates it from the two
6866        // members that do carry one.
6867        assert!(Region::Group.described());
6868        assert_eq!(Region::Group.name(), None);
6869    }
6870
6871    #[test]
6872    fn a_section_heading_names_a_block_that_now_exists() {
6873        // `Heading::Section` has said "names a block within the screen" since
6874        // 0.2.0 and there was no block. The pairing is the point, and it is the
6875        // reason a group carries no heading of its own: the heading is an
6876        // ordinary node in the body, and a group without one is legal.
6877        assert!(Heading::Section.separated());
6878        assert_eq!(Region::Group.depth(), Depth::Flat);
6879    }
6880
6881    #[test]
6882    fn a_widget_inherits_its_depth_the_way_a_bespoke_does() {
6883        // Stronger than the bespoke case: a widget is drawn by whichever
6884        // renderer recognises the name, so a depth chosen here would be this
6885        // crate deciding a carousel is raised on every host.
6886        assert_eq!(Region::Widget { name: "carousel" }.depth(), Depth::Flat);
6887        assert_eq!(Region::Widget { name: "pager" }.depth(), Depth::Flat);
6888    }
6889
6890    #[test]
6891    fn a_name_is_readable_without_asking_which_member_carried_it() {
6892        // A renderer dispatching on a name wants the string, not the member.
6893        // Writing that `matches!` at each renderer is how the two drift apart.
6894        assert_eq!(Region::Widget { name: "carousel" }.name(), Some("carousel"));
6895        assert_eq!(
6896            Region::Bespoke { name: "day-plan" }.name(),
6897            Some("day-plan")
6898        );
6899
6900        for r in [
6901            Region::Band,
6902            Region::Sidebar,
6903            Region::Pane,
6904            Region::Group,
6905            Region::Split,
6906            Region::TabGroup,
6907            Region::Modal,
6908        ] {
6909            assert_eq!(r.name(), None, "{r:?} names nothing an app chose");
6910        }
6911    }
6912
6913    #[test]
6914    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
6915        // The app owns the contents, not the placement. An app that wants its
6916        // timeline in a well frames it in a Pane.
6917        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
6918        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
6919    }
6920
6921    #[test]
6922    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
6923        // The argument the member exists for: goingson's day-plan has to be
6924        // routable, or the description covers only the boring screens and the
6925        // interesting four need a second path beside the router.
6926        let day_plan = [
6927            Region::Band,
6928            Region::Bespoke { name: "day-plan" },
6929            Region::Sidebar,
6930        ];
6931        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
6932        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
6933    }
6934
6935    #[test]
6936    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
6937        let secret = Field::new(FieldKind::Secret, "password", "Password");
6938        assert!(secret.kind.confidential());
6939        assert!(secret.kind.visible());
6940
6941        assert!(!FieldKind::Hidden.visible());
6942        // Nothing else is confidential, or the marker means nothing.
6943        for k in [
6944            FieldKind::Text,
6945            FieldKind::Number,
6946            FieldKind::Textarea,
6947            FieldKind::Rich,
6948            FieldKind::Select,
6949            FieldKind::Checkbox,
6950            FieldKind::Hidden,
6951        ] {
6952            assert!(!k.confidential(), "{k:?} should not be confidential");
6953        }
6954
6955        // Only a checkbox carries its own label.
6956        assert!(FieldKind::Checkbox.labels_itself());
6957        assert!(!FieldKind::Text.labels_itself());
6958    }
6959
6960    #[test]
6961    fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
6962        let text = Field::new(FieldKind::Text, "title", "Title");
6963        assert!(text.options.is_empty());
6964        assert_eq!(text.placeholder, None);
6965
6966        let sizes = [Choice::plain("small"), Choice::plain("large")];
6967        let select = Field::select("size", "Size", &sizes);
6968        assert_eq!(select.kind, FieldKind::Select);
6969        assert_eq!(select.options.len(), 2);
6970    }
6971
6972    #[test]
6973    fn a_choice_says_what_submits_and_what_is_read_apart() {
6974        // The whole reason it is two strings. `plain` is the case where they
6975        // coincide, and it is a shorthand rather than the general shape.
6976        let plain = Choice::plain("7");
6977        assert_eq!((plain.value, plain.label), ("7", "7"));
6978
6979        let spelled = Choice::new("7", "One week");
6980        assert_ne!(spelled.value, spelled.label);
6981        assert!(
6982            spelled.available(),
6983            "an option is pickable until it says not"
6984        );
6985    }
6986
6987    #[test]
6988    fn a_candidate_carries_the_line_that_tells_it_from_its_neighbours() {
6989        // The gap this type was born for: two candidates whose labels read
6990        // alike, told apart by the second string and by nothing else. The
6991        // measured site is the MNW tag box, where "Format" is a leaf under
6992        // audio, software, writing and video.
6993        let audio = Candidate::new("audio/format", "Format").detailed("Audio");
6994        let writing = Candidate::new("writing/format", "Format").detailed("Writing");
6995
6996        assert_eq!(audio.label, writing.label);
6997        assert_ne!(audio.detail, writing.detail);
6998        assert_ne!(
6999            audio, writing,
7000            "two rows a user cannot tell apart are two rows the type can"
7001        );
7002    }
7003
7004    #[test]
7005    fn a_candidate_is_read_differently_from_an_option_and_written_the_same() {
7006        // The ruling's own distinction, held as a test so the two types do not
7007        // drift back together. Submitting is identical; the second line is the
7008        // whole of what differs, and it is absent by default because a list of
7009        // distinct labels wants nothing there.
7010        let candidate = Candidate::plain("rust");
7011        assert_eq!((candidate.value, candidate.label), ("rust", "rust"));
7012        assert_eq!(
7013            candidate.detail, None,
7014            "one line unless the route says otherwise"
7015        );
7016
7017        let option = Choice::plain("rust");
7018        assert_eq!(
7019            (candidate.value, candidate.label),
7020            (option.value, option.label)
7021        );
7022    }
7023
7024    #[test]
7025    fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
7026        // Both offer a fixed set and both read `options`, so the two
7027        // constructors differ in exactly one thing. That one thing is the
7028        // point: a renderer decides whether the alternatives are readable
7029        // without opening anything, and it can only decide that if the
7030        // description said which question was asked.
7031        let styles = [
7032            Choice::new("copy", "Copy samples in"),
7033            Choice::new("reference", "Reference in place"),
7034        ];
7035        let radio = Field::radio("storage", "Storage style", &styles);
7036        let select = Field::select("storage", "Storage style", &styles);
7037
7038        assert_eq!(radio.kind, FieldKind::Radio);
7039        assert_ne!(radio.kind, select.kind);
7040        assert_eq!(radio.options, select.options);
7041        assert_eq!(
7042            Field {
7043                kind: select.kind,
7044                ..radio
7045            },
7046            select
7047        );
7048    }
7049
7050    #[test]
7051    fn an_unavailable_option_cannot_be_silent_about_it() {
7052        // The whole content of the one-member shape: saying an option is not
7053        // pickable and saying why are the same act, so the greyed-out-with-no-
7054        // reason state is unsayable rather than merely discouraged.
7055        let multi =
7056            Choice::new("multi", "Multi-sample").unless("Drop a second sample onto the keyboard.");
7057        assert!(!multi.available());
7058        assert_eq!(
7059            multi.unavailable,
7060            Some("Drop a second sample onto the keyboard.")
7061        );
7062
7063        // And the option is still in the list, carrying what it submits, so a
7064        // renderer draws it rather than the app dropping it.
7065        assert_eq!(multi.value, "multi");
7066        assert_eq!(multi.label, "Multi-sample");
7067    }
7068
7069    #[test]
7070    fn an_option_can_say_what_picking_it_means_and_why_it_cannot_be_picked() {
7071        // `5e21dcfc`. Two different sentences about one option, and an option
7072        // that has both has said two things: what the tier is, and that it is
7073        // not available yet. Folding them would be the label-folding this
7074        // member exists to end.
7075        let tier = Choice::new("24", "Small Files")
7076            .detailing("$24/mo. 2GB/file, 100GB total. Fits audio, plugins, binaries.")
7077            .unless("Sold out while the founder window is open.");
7078
7079        assert_eq!(
7080            tier.detail,
7081            Some("$24/mo. 2GB/file, 100GB total. Fits audio, plugins, binaries.")
7082        );
7083        assert_eq!(
7084            tier.unavailable,
7085            Some("Sold out while the founder window is open.")
7086        );
7087        assert!(!tier.available());
7088
7089        // Neither is implied by the other, which is what keeps a renderer from
7090        // reading a detail as a reason: an ordinary option with a second line
7091        // is still pickable.
7092        let plain = Choice::new("free", "Free").detailing("No charge. Available to everyone.");
7093        assert!(plain.available());
7094        assert_eq!(plain.detail, Some("No charge. Available to everyone."));
7095        assert_eq!(Choice::new("free", "Free").detail, None);
7096    }
7097
7098    #[test]
7099    fn a_range_carries_both_ends_and_a_validated_number_need_not() {
7100        // The distinction the kind exists for, asserted rather than only
7101        // written down: bounds are a rule for one and the control itself for
7102        // the other.
7103        let threshold = Field::range("review", "Review above", "0", "1");
7104        assert_eq!(threshold.kind, FieldKind::Range);
7105        assert!(threshold.bounded());
7106        assert_eq!(threshold.min, Some("0"));
7107        assert_eq!(threshold.max, Some("1"));
7108        // Granularity is the host's until an app says otherwise.
7109        assert_eq!(threshold.step, None);
7110
7111        // goingson's duration: a typed number with a floor, and it must not
7112        // read as a slider.
7113        let minutes = Field {
7114            min: Some("1"),
7115            ..Field::new(FieldKind::Number, "minutes", "Minutes")
7116        };
7117        assert_ne!(minutes.kind, FieldKind::Range);
7118        assert!(!minutes.bounded(), "one end is a rule, not an extent");
7119    }
7120
7121    #[test]
7122    fn a_range_described_with_one_end_says_so_rather_than_being_refused() {
7123        // Nothing here enforces the pair, for the reason nothing here enforces
7124        // `required`: the description states the constraint and the renderer
7125        // asks. What it must not do is look bounded.
7126        let half = Field {
7127            max: Some("1"),
7128            ..Field::new(FieldKind::Range, "review", "Review above")
7129        };
7130        assert!(!half.bounded());
7131    }
7132
7133    #[test]
7134    fn exactly_the_option_taking_kinds_say_so() {
7135        // The renderers branch on this rather than on a list of their own, so
7136        // a kind added without a decision here renders its options nowhere.
7137        assert!(FieldKind::Select.offers_options());
7138        assert!(FieldKind::Radio.offers_options());
7139        for kind in [
7140            FieldKind::Text,
7141            FieldKind::Secret,
7142            FieldKind::Number,
7143            FieldKind::Email,
7144            FieldKind::Url,
7145            FieldKind::Tel,
7146            FieldKind::Range,
7147            FieldKind::Textarea,
7148            FieldKind::Rich,
7149            FieldKind::Checkbox,
7150            FieldKind::Hidden,
7151        ] {
7152            assert!(!kind.offers_options(), "{kind:?} does not offer options");
7153        }
7154    }
7155
7156    #[test]
7157    fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
7158        // The near-miss: each option is labelled beside its own button, so a
7159        // renderer could plausibly read the group as self-labelling and drop
7160        // the question. Checkbox is the only kind that does that.
7161        assert!(!FieldKind::Radio.labels_itself());
7162        assert!(FieldKind::Checkbox.labels_itself());
7163    }
7164
7165    #[test]
7166    fn a_select_with_no_options_is_sayable() {
7167        // An app whose option list has not loaded has exactly this. Making it
7168        // unrepresentable would push the state somewhere less visible, and a
7169        // renderer drawing an empty select reports it on screen.
7170        let loading = Field::select("project", "Project", &[]);
7171        assert!(loading.options.is_empty());
7172    }
7173
7174    #[test]
7175    fn the_description_carries_the_question_and_never_the_answer() {
7176        // The line 0.8.0 drew. Placeholder and options are properties of what
7177        // is being asked; the current value is what came back, and no field
7178        // here holds one.
7179        let f = Field {
7180            placeholder: Some("yyyy-mm-dd"),
7181            ..Field::new(FieldKind::Text, "due", "Due")
7182        };
7183        assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
7184        // A placeholder is not a label, and having one does not excuse the
7185        // field from carrying the other.
7186        assert_eq!(f.label, "Due");
7187    }
7188
7189    #[test]
7190    fn a_field_reports_its_own_error_state() {
7191        let mut f = Field::new(FieldKind::Text, "title", "Title");
7192        assert!(!f.invalid());
7193        f.error = Some("Required");
7194        assert!(f.invalid());
7195    }
7196
7197    #[test]
7198    fn columns_drop_by_priority_and_never_by_position() {
7199        let cols = [
7200            Column {
7201                width: Width::Fill,
7202                priority: Priority::Essential,
7203                ..Column::new("Title")
7204            },
7205            Column {
7206                width: Width::Fixed,
7207                priority: Priority::Secondary,
7208                ..Column::new("Due")
7209            },
7210            Column {
7211                width: Width::Fixed,
7212                priority: Priority::Optional,
7213                ..Column::new("Estimate")
7214            },
7215        ];
7216
7217        // Widest: everything survives.
7218        assert_eq!(
7219            cols.iter()
7220                .filter(|c| c.kept_at(Priority::Optional))
7221                .count(),
7222            3
7223        );
7224        // Narrower: the optional column goes first.
7225        let kept: Vec<_> = cols
7226            .iter()
7227            .filter(|c| c.kept_at(Priority::Secondary))
7228            .map(|c| c.name)
7229            .collect();
7230        assert_eq!(kept, ["Title", "Due"]);
7231        // Narrowest: only what identifies the row.
7232        let kept: Vec<_> = cols
7233            .iter()
7234            .filter(|c| c.kept_at(Priority::Essential))
7235            .map(|c| c.name)
7236            .collect();
7237        assert_eq!(kept, ["Title"]);
7238    }
7239
7240    #[test]
7241    fn inserting_a_column_does_not_move_what_gets_dropped() {
7242        // The bug the ordinal form has and this form cannot: goingson hides
7243        // `nth-child(n+5)` against a seven-column table, so a column inserted
7244        // anywhere to the left silently hides a different one.
7245        let before = [
7246            Column::new("Title"),
7247            Column {
7248                width: Width::Fixed,
7249                priority: Priority::Optional,
7250                ..Column::new("Estimate")
7251            },
7252        ];
7253        let after = [
7254            Column::new("Title"),
7255            Column::new("Project"), // inserted
7256            Column {
7257                width: Width::Fixed,
7258                priority: Priority::Optional,
7259                ..Column::new("Estimate")
7260            },
7261        ];
7262
7263        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
7264            cols.iter()
7265                .filter(|c| !c.kept_at(Priority::Secondary))
7266                .map(|c| c.name)
7267                .collect()
7268        }
7269        assert_eq!(dropped(&before), ["Estimate"]);
7270        assert_eq!(dropped(&after), ["Estimate"]);
7271    }
7272
7273    #[test]
7274    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
7275        // goingson uses the tab group inside the content region rather than
7276        // instead of one, so it is not a third arrangement.
7277        let go = Arrangement::list_detail(true);
7278        let plain = Arrangement::list_detail(false);
7279        assert_ne!(go, plain);
7280        assert_ne!(go, Arrangement::sidebar_content());
7281    }
7282
7283    #[test]
7284    fn a_share_is_a_proportion_and_resolves_the_same_way_everywhere() {
7285        // The point of the member: a terminal reading columns and a webview
7286        // reading a grid honour one fact, so two hosts showing one screen agree
7287        // about its proportions.
7288        assert_eq!(Share::LIST.as_percent(), 40);
7289        assert_eq!(Share::LIST.of(100), 40);
7290        assert_eq!(
7291            Share::SIDEBAR.of(96),
7292            24,
7293            "quasi-tui's 24 columns, said as a quarter"
7294        );
7295    }
7296
7297    #[test]
7298    fn a_region_never_resolves_to_nothing() {
7299        // A region the description named should be visible. A zero-width one
7300        // reads on screen as a region that vanished, which is the hardest kind
7301        // of bug to find from what is drawn.
7302        assert_eq!(Share::percent(5).of(1), 1);
7303        assert_eq!(Share::percent(5).of(0), 1);
7304    }
7305
7306    #[test]
7307    fn a_share_outside_the_range_is_clamped_rather_than_refused() {
7308        assert_eq!(Share::percent(0), Share::percent(5));
7309        assert_eq!(Share::percent(200), Share::percent(95));
7310    }
7311
7312    #[test]
7313    fn the_share_rides_on_the_arrangement_that_knows_which_question_it_is() {
7314        // How much a sidebar takes and how much a list side takes are different
7315        // questions, and this enum is the only thing that knows which is being
7316        // asked.
7317        assert_eq!(Arrangement::sidebar_content().share(), Some(Share::SIDEBAR));
7318        assert_eq!(Arrangement::list_detail(false).share(), Some(Share::LIST));
7319        // One region divides nothing, so there is no share to answer with.
7320        assert_eq!(Arrangement::Single.share(), None);
7321        assert_eq!(
7322            Arrangement::Single.with_share(Share::percent(20)),
7323            Arrangement::Single
7324        );
7325
7326        let narrow = Arrangement::sidebar_content().with_share(Share::percent(20));
7327        assert_eq!(narrow.share(), Some(Share::percent(20)));
7328        assert!(matches!(narrow, Arrangement::SidebarContent { .. }));
7329    }
7330
7331    #[test]
7332    fn a_measure_defaults_to_the_one_53_of_69_templates_asked_for() {
7333        // The default is meaningful: a screen nobody said anything about uses
7334        // the window it was given.
7335        assert_eq!(Measure::default(), Measure::Wide);
7336        assert_eq!(Measure::Reading.as_str(), "reading");
7337    }
7338
7339    #[test]
7340    fn readiness_names_the_state_and_not_the_shimmer() {
7341        // Two members and no third. If a skeleton ever appears in this enum,
7342        // the deferral rule has been broken.
7343        assert_ne!(Readiness::Ready, Readiness::Pending);
7344    }
7345
7346    #[test]
7347    fn a_window_with_no_length_still_answers_what_it_can() {
7348        // The uncounted case is the common one, not the degenerate one: a query
7349        // that asked for 51 to learn there were more than 50 knows there are,
7350        // and not how many.
7351        let uncounted = Window::new(100, 50);
7352        assert_eq!(uncounted.index(), Some(2));
7353        assert_eq!(uncounted.windows(), None);
7354        assert!(uncounted.has_before());
7355        // Unknown length cannot rule out more, and offering a way forward that
7356        // turns out empty is the cheaper mistake.
7357        assert!(uncounted.has_after());
7358    }
7359
7360    #[test]
7361    fn a_counted_window_knows_where_it_ends() {
7362        let last = Window::new(350, 50).of(400);
7363        assert_eq!(last.index(), Some(7));
7364        assert_eq!(last.windows(), Some(8));
7365        assert!(last.has_before());
7366        assert!(!last.has_after());
7367
7368        let first = Window::new(0, 50).of(400);
7369        assert!(!first.has_before());
7370        assert!(first.has_after());
7371    }
7372
7373    #[test]
7374    fn a_window_that_does_not_divide_evenly_rounds_up() {
7375        // 401 rows in pages of 50 is eight pages and a straggler, which is nine
7376        // pages. Rounding down would make the last one unreachable.
7377        assert_eq!(Window::new(0, 50).of(401).windows(), Some(9));
7378    }
7379
7380    #[test]
7381    fn a_zero_count_answers_none_rather_than_dividing() {
7382        let empty = Window::new(0, 0).of(400);
7383        assert_eq!(empty.index(), None);
7384        assert_eq!(empty.windows(), None);
7385        // And it still clamps rather than panicking.
7386        assert_eq!(Window::new(900, 0).of(400).clamped().from, 399);
7387    }
7388
7389    #[test]
7390    fn a_window_past_the_end_clamps_inside_rather_than_vanishing() {
7391        // `Slot::current`'s reasoning, one layer down: a description pointing
7392        // past the end is a host bug, and answering it by drawing nothing
7393        // reports a region that vanished.
7394        assert_eq!(Window::new(900, 50).of(400).clamped().from, 350);
7395        // Nothing to clamp against when the length is unknown.
7396        assert_eq!(Window::new(900, 50).clamped().from, 900);
7397    }
7398
7399    #[test]
7400    fn a_carousel_frame_is_a_window_of_one() {
7401        // The shape a carousel instantiates. Same code as a paged list, which is
7402        // the whole reason `Window` exists rather than two copies of it.
7403        let third = Window::frame(2, 5);
7404        assert_eq!(third.index(), Some(2));
7405        assert_eq!(third.windows(), Some(5));
7406        assert!(third.has_before());
7407        assert!(third.has_after());
7408
7409        let last = Window::frame(4, 5);
7410        assert!(!last.has_after());
7411    }
7412
7413    #[test]
7414    fn numbered_pages_read_from_one_and_load_more_has_no_page() {
7415        // The page number is read aloud, so it is one-based; `Window::index` is
7416        // the zero-based form for indexing.
7417        let third = Paging::pages(100, 50).of(400);
7418        assert_eq!(third.page(), Some(3));
7419        assert_eq!(third.pages_total(), Some(8));
7420        assert_eq!(third.total(), Some(400));
7421        assert!(third.has_previous());
7422        assert!(third.has_more());
7423
7424        // Load-more grew a window from the start, so "page 2" would name
7425        // nothing and the type says so rather than inventing one.
7426        let grown = Paging::more(150).of(400);
7427        assert_eq!(grown.page(), None);
7428        assert_eq!(grown.pages_total(), None);
7429        assert_eq!(grown.shown(), 150);
7430        assert!(!grown.has_previous());
7431        assert!(grown.has_more());
7432    }
7433
7434    #[test]
7435    fn an_uncounted_paging_offers_forward_and_admits_no_total() {
7436        // What a host that will not pay for a COUNT describes. `None` here is
7437        // permanent: a total arriving later would widen the text that prints it,
7438        // which is the reflow "first paint is final paint" forbids.
7439        let feed = Paging::more(50);
7440        assert_eq!(feed.total(), None);
7441        assert_eq!(feed.pages_total(), None);
7442        assert_eq!(feed.remaining(), None);
7443        assert!(feed.has_more());
7444    }
7445
7446    #[test]
7447    fn what_is_left_is_derived_and_never_underflows() {
7448        assert_eq!(Paging::more(150).of(400).remaining(), Some(250));
7449        assert_eq!(Paging::pages(350, 50).of(400).remaining(), Some(0));
7450        // A host that overshot its own total gets zero rather than a wrapped
7451        // usize, which would print as "18446744073709551516 remaining".
7452        assert_eq!(Paging::more(500).of(400).remaining(), Some(0));
7453    }
7454
7455    #[test]
7456    fn a_group_out_of_room_is_not_the_same_fact_as_a_narrow_window() {
7457        // The case the type exists for: 913px is a roomy window holding a group
7458        // that has run out of room, so room is measured against the group's own
7459        // allocation and never against the viewport.
7460        assert!(Room::Tight < Room::Ample);
7461        // A group nesting another has whichever room is scarcer, which is what
7462        // makes relief resolve inside-out rather than by declaration order.
7463        assert_eq!(Room::Ample.min(Room::Tight), Room::Tight);
7464    }
7465
7466    #[test]
7467    fn a_fallback_is_authored_and_a_group_cannot_omit_it() {
7468        // No `Default`. The compiler is what enforces rule 2, so the assertion
7469        // that matters is one this file cannot write; what it can say is that
7470        // the four authored answers are distinct and none is privileged.
7471        let all = [
7472            Fallback::Wrap,
7473            Fallback::Stack,
7474            Fallback::Shed,
7475            Fallback::Menu,
7476        ];
7477        for (i, a) in all.iter().enumerate() {
7478            for b in &all[i + 1..] {
7479                assert_ne!(a, b);
7480            }
7481        }
7482    }
7483
7484    #[test]
7485    fn shedding_stops_at_essential_whatever_the_group_holds() {
7486        // Priority is read the same way for a group member as for a column,
7487        // which is the whole claim of generalising it off `Column`.
7488        let members = [
7489            ("tabs", Priority::Essential),
7490            ("search", Priority::Secondary),
7491            ("count", Priority::Optional),
7492        ];
7493        let kept: Vec<_> = members
7494            .iter()
7495            .filter(|(_, p)| *p >= Priority::Essential)
7496            .map(|(n, _)| *n)
7497            .collect();
7498        assert_eq!(kept, ["tabs"]);
7499    }
7500
7501    #[test]
7502    fn a_role_says_what_a_part_is_worth_when_the_run_does_not_fit() {
7503        // The row still identifies itself after everything droppable has gone,
7504        // which is the property the ladder exists for.
7505        assert_eq!(RowPart::Primary.priority(), Priority::Essential);
7506        // A control is not a fact. Room comes out of what the row says, never
7507        // out of what it offers.
7508        assert_eq!(RowPart::Actions.priority(), Priority::Essential);
7509        assert_eq!(RowPart::Meta.priority(), Priority::Optional);
7510        assert_eq!(RowPart::Proportion.priority(), Priority::Optional);
7511        assert_eq!(RowPart::Secondary.priority(), Priority::Secondary);
7512        // Tokens sit in the middle deliberately: a toned badge is often the
7513        // most scannable thing in a row, so it does not go first.
7514        assert_eq!(RowPart::Tokens.priority(), Priority::Secondary);
7515    }
7516
7517    #[test]
7518    fn a_run_is_one_line_unless_the_description_says_two() {
7519        // The default is what every part did before flows existed, so a
7520        // description written against the old vocabulary keeps its rendering.
7521        assert_eq!(Flow::default(), Flow::Tight);
7522        assert_eq!(Flow::Tight.lines(), 1);
7523        assert_eq!(Flow::Relaxed.lines(), 2);
7524    }
7525
7526    #[test]
7527    fn an_unknown_flow_reads_as_one_line() {
7528        // `#[non_exhaustive]`'s cost, taken deliberately. A tier added upstream
7529        // reaches an old renderer as one line rather than as a build break, and
7530        // one line is the reading that cannot break a neighbour's layout. The
7531        // match in `lines` is what this holds; it fails if a new tier is given
7532        // an arm that returns something unbounded.
7533        for flow in [Flow::Tight, Flow::Relaxed] {
7534            assert!((1..=2).contains(&flow.lines()));
7535        }
7536    }
7537
7538    #[test]
7539    fn an_awaiting_mark_is_indeterminate_until_something_is_measured() {
7540        // The default is the common case: a call waits, and nothing about it is
7541        // countable. A determinate bar is the exception and says so.
7542        assert_eq!(Awaiting::default(), Awaiting::unmeasured());
7543        assert!(!Awaiting::unmeasured().is_determinate());
7544        assert!(Awaiting::of(40 * 1024 * 1024).is_determinate());
7545        assert_eq!(Awaiting::of(7).amount, Some(7));
7546    }
7547
7548    // A slider is a fraction and a mapping
7549    //
7550    // `Curve` is the one thing in this crate that computes rather than
7551    // describes, and it does so because four renderers would otherwise each
7552    // write these two formulas and drift. So the formulas are pinned here.
7553
7554    /// The bounds of audiofiles' envelope attack, the curve's first consumer.
7555    const ATTACK: (f64, f64) = (0.001, 5.0);
7556
7557    #[test]
7558    fn a_curve_is_linear_with_no_step_until_a_field_says_otherwise() {
7559        assert_eq!(Curve::default(), Curve::Linear { step: None });
7560        let plain = Field::range("t", "T", "0", "1");
7561        assert_eq!(plain.curve, Curve::Linear { step: None });
7562        assert_eq!(plain.curve.step(), None);
7563    }
7564
7565    #[test]
7566    fn every_curve_carries_its_own_granularity() {
7567        assert_eq!(Curve::Linear { step: Some("0.01") }.step(), Some("0.01"));
7568        assert_eq!(
7569            Curve::Logarithmic {
7570                step: Some("0.001")
7571            }
7572            .step(),
7573            Some("0.001")
7574        );
7575    }
7576
7577    #[test]
7578    fn both_ends_of_the_track_are_the_bounds_under_either_curve() {
7579        // `min` and `max` are `f(0)` and `f(1)`. That is the whole reframe, and
7580        // it has to hold for a mapping that is not the identity or the bounds
7581        // have stopped meaning what the field says they mean.
7582        let (min, max) = ATTACK;
7583        for curve in [
7584            Curve::Linear { step: None },
7585            Curve::Logarithmic { step: None },
7586        ] {
7587            assert!((curve.value_at(0.0, min, max) - min).abs() < 1e-12);
7588            assert!((curve.value_at(1.0, min, max) - max).abs() < 1e-12);
7589        }
7590    }
7591
7592    #[test]
7593    fn a_linear_midpoint_is_the_average_and_a_ratio_midpoint_is_the_geometric_mean() {
7594        let (min, max) = ATTACK;
7595        let linear = Curve::Linear { step: None }.value_at(0.5, min, max);
7596        assert!((linear - 2.5005).abs() < 1e-9);
7597
7598        // The reason the envelope is not linear: half way along a log track is
7599        // 70 ms, and half way along a linear one is 2.5 seconds. Every attack a
7600        // sampler is actually played with lives below the first.
7601        let ratio = Curve::Logarithmic { step: None }.value_at(0.5, min, max);
7602        assert!((ratio - (min * max).sqrt()).abs() < 1e-12);
7603        assert!(ratio < 0.08);
7604    }
7605
7606    #[test]
7607    fn a_position_and_a_value_round_trip_under_either_curve() {
7608        let (min, max) = ATTACK;
7609        for curve in [
7610            Curve::Linear { step: None },
7611            Curve::Logarithmic { step: None },
7612        ] {
7613            for position in [0.0, 0.1, 0.25, 0.5, 0.75, 0.99, 1.0] {
7614                let back = curve.position_of(curve.value_at(position, min, max), min, max);
7615                assert!(
7616                    (back - position).abs() < 1e-9,
7617                    "{curve:?} lost {position} (got {back})"
7618                );
7619            }
7620        }
7621    }
7622
7623    #[test]
7624    fn a_ratio_curve_across_zero_is_drawn_linearly_rather_than_refused() {
7625        // An envelope's sustain is a 0-to-1 level. A constant ratio is
7626        // undefined there, and the answer is the linear mapping rather than a
7627        // NaN reaching a renderer that would paint it.
7628        let curve = Curve::Logarithmic { step: None };
7629        assert!(!curve.is_ratio(0.0, 1.0));
7630        assert!((curve.value_at(0.5, 0.0, 1.0) - 0.5).abs() < 1e-12);
7631        assert!(curve.value_at(0.5, -96.0, -20.0).is_finite());
7632        assert!(curve.is_ratio(ATTACK.0, ATTACK.1));
7633    }
7634
7635    #[test]
7636    fn a_track_with_no_extent_has_one_value_on_it() {
7637        for curve in [
7638            Curve::Linear { step: None },
7639            Curve::Logarithmic { step: None },
7640        ] {
7641            assert!((curve.value_at(0.7, 4.0, 4.0) - 4.0).abs() < f64::EPSILON);
7642            assert!(curve.position_of(4.0, 4.0, 4.0).abs() < f64::EPSILON);
7643            // Inverted bounds are the same degenerate answer, not a negative
7644            // extent a renderer would draw backwards.
7645            assert!((curve.value_at(0.7, 9.0, 2.0) - 9.0).abs() < f64::EPSILON);
7646        }
7647    }
7648
7649    #[test]
7650    fn a_position_or_a_value_outside_the_track_is_clamped_to_it() {
7651        let (min, max) = ATTACK;
7652        let curve = Curve::Logarithmic { step: None };
7653        assert!((curve.value_at(-3.0, min, max) - min).abs() < 1e-12);
7654        assert!((curve.value_at(4.0, min, max) - max).abs() < 1e-12);
7655        assert!(curve.position_of(0.0, min, max).abs() < 1e-12);
7656        assert!((curve.position_of(500.0, min, max) - 1.0).abs() < 1e-12);
7657    }
7658
7659    #[test]
7660    fn a_typed_number_keeps_its_own_step_and_a_range_reads_its_curve() {
7661        // The split the 0.32.0 narrowing is: two granularities that were one
7662        // member, and the kinds that take them do not overlap.
7663        let typed = Field {
7664            step: Some("5"),
7665            ..Field::new(FieldKind::Number, "port", "Port")
7666        };
7667        assert_eq!(typed.step, Some("5"));
7668
7669        let slid = Field {
7670            curve: Curve::Logarithmic {
7671                step: Some("0.001"),
7672            },
7673            ..Field::range("attack", "Attack", "0.001", "5")
7674        };
7675        assert_eq!(slid.step, None);
7676        assert_eq!(slid.curve.step(), Some("0.001"));
7677    }
7678
7679    #[test]
7680    fn a_theme_picker_offers_themes_and_no_options() {
7681        // The substitution hazard the constructor exists against: `options` is
7682        // right there and reads as if it would work, and a renderer walking it
7683        // for a theme picker draws an empty control.
7684        let themes = [
7685            ThemeChoice::new("goingson", "GoingsOn", ThemeVariant::Light, Contrast::High),
7686            ThemeChoice::new("dracula", "Dracula", ThemeVariant::Dark, Contrast::Standard),
7687        ];
7688        let field = Field::theme("theme", "Theme", &themes);
7689
7690        assert_eq!(field.kind, FieldKind::Theme);
7691        assert!(field.kind.offers_themes());
7692        assert!(!field.kind.offers_options());
7693        assert_eq!(field.themes.len(), 2);
7694        assert!(field.options.is_empty());
7695        assert_eq!(field.follows, None);
7696    }
7697
7698    #[test]
7699    fn following_carries_the_store_s_own_spelling() {
7700        // Not hardcoded here: the value belongs to the app's config table, and
7701        // this crate holds no facts about somebody else's store.
7702        let field =
7703            Field::theme("theme", "Theme", &[]).following(Choice::new("system", "Follow System"));
7704        let follow = field.follows.expect("the row was offered");
7705        assert_eq!(follow.value, "system");
7706        assert_eq!(follow.label, "Follow System");
7707    }
7708
7709    #[test]
7710    fn a_picker_with_nothing_resolved_is_sayable() {
7711        // A machine whose theme directories hold nothing. The description is
7712        // true and a renderer says so on screen rather than in a log, which is
7713        // `Field::options`' own arrangement.
7714        let field = Field::theme("theme", "Theme", &[]);
7715        assert!(field.themes.is_empty());
7716    }
7717
7718    #[test]
7719    fn every_kind_but_theme_offers_no_themes() {
7720        for kind in [
7721            FieldKind::Text,
7722            FieldKind::Select,
7723            FieldKind::Radio,
7724            FieldKind::Checkbox,
7725            FieldKind::File,
7726            FieldKind::Hidden,
7727        ] {
7728            assert!(
7729                !kind.offers_themes(),
7730                "{kind:?} does not read Field::themes"
7731            );
7732        }
7733    }
7734
7735    #[test]
7736    fn a_contrast_tier_reads_worst_first() {
7737        // Matches `makeover::ContrastTier`, so an adopter's conversion cannot
7738        // invert an ordering by accident and a sort agrees across the seam.
7739        assert!(Contrast::Low < Contrast::Standard);
7740        assert!(Contrast::Standard < Contrast::High);
7741    }
7742
7743    #[test]
7744    fn the_groups_and_badges_have_one_spelling_each() {
7745        // The whole argument for these living here: three renderers picking
7746        // their own is one picker reading three ways.
7747        assert_eq!(ThemeVariant::Light.heading(), "Light");
7748        assert_eq!(ThemeVariant::Dark.heading(), "Dark");
7749        assert_eq!(ThemeVariant::HighContrast.heading(), "High Contrast");
7750
7751        assert_eq!(ThemeVariant::HighContrast.as_str(), "high-contrast");
7752
7753        assert_eq!(Contrast::High.badge(), "AA");
7754        assert_eq!(Contrast::Standard.badge(), "OK");
7755        assert_eq!(Contrast::Low.badge(), "low");
7756    }
7757
7758    #[test]
7759    fn the_variant_spelling_matches_the_theme_file_s_own() {
7760        // The seam this enum is duplicated across. `makeover::parse_meta` reads
7761        // `meta.variant` as one of these three strings; a rename on either side
7762        // that does not move together silently regroups every picker.
7763        for (variant, spelling) in [
7764            (ThemeVariant::Light, "light"),
7765            (ThemeVariant::Dark, "dark"),
7766            (ThemeVariant::HighContrast, "high-contrast"),
7767        ] {
7768            assert_eq!(variant.as_str(), spelling);
7769            assert_eq!(variant.to_string(), spelling);
7770        }
7771    }
7772}