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//! # Reach, focus and the focus ring
303//!
304//! Three terms, and no others, for what 0.19.0 moved out of the description.
305//! **Reach** is which things can take focus and in what order; a browser reads
306//! it off the document, a TUI derives it from draw order, egui from its own id
307//! stack. **Focus** is which reached thing has the keyboard right now: the
308//! renderer's, live, never described and never round-tripped through a
309//! description. The **focus ring** is the visible cue; the token (`focus-ring`,
310//! derived by `makeover` from the action colour) is the one shared artifact and
311//! the drawing is the renderer's. Retired as names for any of this: "focus
312//! stroke", "focus cue", "wants focus". "Caret" is a different thing — the text
313//! cursor inside a field — and keeps its name.
314//!
315//! # The three tones, and what a colour claims
316//!
317//! One rule, settled 2026-08-16, for how colour says whether a thing can be
318//! used. Every renderer answers to it, and it is stated here because the
319//! description is what names the intents.
320//!
321//! | the thing | intent |
322//! |-----------|--------|
323//! | active, emphasised, the thing itself | `content` |
324//! | inactive but usable: it still answers a press | `content-secondary` |
325//! | inert: disabled, or not a control at all | `content-muted` |
326//!
327//! `content-muted` is the one with a claim in it. [`State::Disabled`] resolves
328//! to it, so a live control wearing it is telling the user it will not answer —
329//! and being wrong about that is worse than being quiet, because the user's
330//! response is to stop trying. A sortable column heading that was never sorted,
331//! and every unchosen option in a radio group, both read as dead lists that way;
332//! those are the two this rule was written out of. What is legitimately muted is
333//! a caption, a hint, a placeholder, a meter's reading, an axis label: text that
334//! was never going to answer anything.
335//!
336//! The three are one ramp and not three colours. `makeover`'s `Emphasis` derives
337//! the quieter two from the ink, so "one step back" means the same distance in
338//! every theme and a renderer cannot land between them by picking its own.
339//!
340//! # First paint is final paint
341//!
342//! One rule, settled 2026-08-16. Nothing may change size or position after it is
343//! first drawn, and nothing may stand in for content that has not arrived yet.
344//! Both halves are absolute.
345//!
346//! It is stated here, rather than left to each renderer, because a renderer can
347//! only reserve space the description gave it enough to size. A member whose
348//! size depends on its content therefore owes whatever makes it sizeable while
349//! the content is still absent, and that is the second admission test for a new
350//! member: not only does it compose something this crate already names, it can
351//! be laid out before it is filled.
352//!
353//! The mechanism is a reservation, and [`Sort`]'s caret is the worked example.
354//! The caret is drawn into a box its own width whether or not the column is
355//! sorted, so pressing a heading cannot reflow the row it sits in. The box names
356//! no magnitude, which is what keeps it out of `makeover-geometry`'s territory.
357//! Reserve from what is known; never discover geometry from what has not
358//! arrived.
359//!
360//! The trap is an `Option` that means "not yet". [`Readiness::Pending`] is the
361//! honest way to say a region is still waiting. An optional *measurement* is
362//! not: a count that shows up later widens the text that prints it and moves
363//! everything beside it, which is the reflow this rule exists to forbid. So an
364//! `Option` on a measurement means the host will never know it — a property of
365//! the query, fixed for the life of the screen — and a renderer sizes for the
366//! answer it was handed rather than for the one it hopes is coming.
367//!
368//! # Any width, one answer
369//!
370//! The sibling of the rule above, and settled the same day. That one is
371//! independence from *when*; this one is independence from *how you got here*.
372//!
373//! A rendering is a pure function of the description and the viewport. The same
374//! description at the same width is the same output, whatever widths came
375//! before it. No renderer may carry geometry across frames, and none may narrow
376//! by counting.
377//!
378//! The failure this forbids is ordinary enough to be the default everywhere
379//! else: a page that hides its sidebar below some width, remembers that it hid
380//! it, and does not bring it back the same way. Layout there is a function of
381//! `(width, history)`, so dragging a window to 900 wide is a different screen
382//! depending on whether you came from 1400 or from 600. Nobody chose that; it
383//! is what measuring and remembering produce.
384//!
385//! The mechanism is [`Width`] for what grows and [`Priority`] for what drops.
386//! Both are declared, both are read off the description, and neither needs a
387//! measurement. A renderer narrows by raising a cutoff over a total order,
388//! never by counting what fits and stopping — `makeover-tui`'s table states
389//! that as its own rule and tests it, and `makeover-webview` reaches the same
390//! place with `@media` and `display: none`, which is path-independent by
391//! construction because CSS has nowhere to keep the previous width.
392//!
393//! Two things follow for anything new. A member that would need last frame's
394//! size to lay out this frame is refused, the same way a member that cannot be
395//! sized before it is filled is refused. And a fact about what disappears
396//! belongs in the description, because a host that has to infer it can only
397//! infer it from a measurement.
398//!
399//! # Where the description stops
400//!
401//! The rule is that a member is added when an app needs a fact the vocabulary
402//! cannot state, and refused when what it wants is presentation it should be
403//! asking a renderer for. That is the whole test. It is not a quota, and the
404//! goal is every screen described.
405//!
406//! ## What the timeline refusal got wrong, 2026-08-15
407//!
408//! This section used to read "a day-plan timeline, a kanban board and a
409//! calendar are not describable here and will not become describable", and it
410//! propagated: 12 files across three apps, three libraries and the design wiki
411//! cited it, including audiofiles and the MNW server, neither of which has a
412//! timeline. It is withdrawn, and [`Track`] is the member it was refusing.
413//!
414//! The error was pricing. The argument assumed a timeline needs a component
415//! library's worth of vocabulary, and nobody measured it. Held against
416//! goingson's `day-planning-render.js`, the members it actually needed and
417//! could not get were two integers: where a thing starts, and how long it
418//! lasts. Labels, gridlines, item bodies and tones were all furniture this
419//! crate already named. A refusal that expensive should have carried a
420//! measurement, and did not.
421//!
422//! The reasoning underneath it survives and is still the test: slot heights,
423//! gridline colour, how overlapping things stack, which hour scrolls into view.
424//! Those are presentation, they stay the renderer's, and [`Track`] carries none
425//! of them. What changed is the conclusion, not the principle.
426//!
427//! ## The other two, measured 2026-08-15
428//!
429//! The same sentence refused a kanban board and a calendar. Both were counted
430//! the way the timeline should have been, and neither came out where the
431//! refusal put it.
432//!
433//! **Kanban: one member, and it is [`Region::Columns`].** Held against
434//! goingson's `tasks-kanban.js`, every card fact was already sayable — title,
435//! project, due date, the blocked and unblocks badges, subtask progress, the
436//! open action and the context menu are `Row`'s existing parts. A column is a
437//! heading, a count and a list. What nothing could say was that the columns are
438//! *peers*: [`Arrangement`] offers list-detail and sidebar-content, and a board
439//! described as either is a lie about the screen. Dragging a card between
440//! columns never entered into it — a drop's effect is "set status", a discrete
441//! action `Row`'s menu already carries, and the drag itself is affordance.
442//!
443//! **Calendar: no members, no consumer, and a sharper reason (Max,
444//! 2026-08-15).** The month grid's primacy in calendar apps is an artifact of
445//! paper: paper cannot be queried, so it has to show every day at once as a
446//! fallback index. Routes, search and ranking do that job better, which is the
447//! argument `events-calendar.js` already lost to a segmented list on
448//! 2026-08-11.
449//!
450//! Three jobs survive that reasoning, and only one of them needs a grid:
451//!
452//! 1. **Spans across days** — a stretch of leave, a trip, a sprint. You cannot
453//!    see "away the 3rd to the 17th" in a list without diffing dates. This is
454//!    [`Track`] with [`Unit::Days`], not a calendar, and
455//!    [`Track::days`] is it.
456//! 2. **Density at a glance** — which weeks were heavy. That is a heatmap, and
457//!    goingson describes both of its heatmaps as lists already.
458//! 3. **Weekday periodicity** — "every other Tuesday", "the 15th is a
459//!    Saturday". This is the only job that needs the seven-column wrap, because
460//!    alignment is the whole of what makes it visible.
461//!
462//! So the open question is not "is a calendar describable" but "is job 3 worth
463//! a member", and nothing in the tree asks for job 3 yet. GoingsOn
464//! quasicoherent `4a1237b6`.
465//!
466//! A month grid renders today as a
467//! [`Table`](crate::Column): seven weekday columns, weeks as rows, blanks for
468//! the offset. goingson's monthly review reached this conclusion before this
469//! note did and describes its month as a list of days that had something on
470//! them, marking today with an ordinary badge. What the tree actually contains
471//! is two completion heatmaps — one scalar per day — and no calendar at all:
472//! `events-calendar.js` was deleted 2026-08-11 in favour of a segmented list,
473//! and no MNW template mentions one. So the refusal was defending a screen
474//! nobody has. If one is built, measure again; the facts already fit and only
475//! the grid's shape would be in question.
476//!
477//! The pattern worth keeping from all three: one sentence refused three things
478//! for one reason, and the reason was wrong three different ways. Count the
479//! members.
480//!
481//! [`Region::Bespoke`] remains for the genuinely app-owned, and its
482//! justification does not depend on the withdrawn claim. The
483//! description names the *place* and the app owns the contents, so a screen
484//! containing a timeline is still a whole screen and still routable. Without
485//! it, the four goingson screens that make the app worth using would need a
486//! second, undescribed path beside the router, and two paths is how a
487//! vocabulary starts drifting from its app again.
488//!
489//! [`Region::Widget`] sits between that limit and the primitives, and it does
490//! not move the limit. A widget is an assembly of members this crate *already*
491//! has, under a name a renderer may or may not recognise. Anything that needs a
492//! member the vocabulary does not have is still a finding about the vocabulary
493//! or still bespoke; naming an assembly buys no new expressive power, which is
494//! exactly why it is safe to let the set grow outside this crate.
495
496#![forbid(unsafe_code)]
497
498/// A colour intent this crate refers to but never resolves.
499///
500/// The string is the token name `makeover` publishes, so a renderer can look
501/// it up without this crate knowing what colour came back.
502pub trait Intent {
503    /// The `makeover` intent token this resolves against.
504    fn token(self) -> &'static str;
505}
506
507/// Which way the light falls across a two-tone edge.
508///
509/// The whole content of a bevel, once colour and thickness are deferred. The
510/// light is always assumed to come from the top left: every consumer measured
511/// agreed on that and none of them ever varied it, so it is an invariant here
512/// rather than a parameter.
513///
514/// # The two corners that belong to both edges
515///
516/// Top-right and bottom-left are where the lit run meets the shaded one, and
517/// the description's claim is that they belong to *both*. How a renderer says
518/// that is its own business, because the answer is bounded by resolution and
519/// not by taste:
520///
521/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
522///   to one tone thickens that edge by a cell and reads as one run overrunning
523///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
524///   splits it and recovers real information. Its box-drawing fallback cannot:
525///   a single stroke has no half to give, so there both corners go to dark.
526/// - A pixel bevel is a one-point stroke by default, which makes the corner a
527///   one-point square. There is nothing to divide — a diagonal seam across one
528///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
529///   already produces. So `makeover-immediate` mitres and is *not* diverging;
530///   it is the same rule at a resolution where the split degenerates.
531///
532/// Stated here so the difference reads as a decision rather than as drift. A
533/// renderer with room to divide the corner should; one without should mitre or
534/// pick the shaded tone, and neither is a bug.
535#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
536pub enum Bevel {
537    /// Lit from the top left: light on top and left, dark on bottom and right.
538    Raised,
539    /// The same edge inverted, which is also the pressed state of anything
540    /// that draws itself [`Bevel::Raised`].
541    Inset,
542}
543
544impl Bevel {
545    /// The edge intents, as `(top_left, bottom_right)`.
546    ///
547    /// Split out from any painting because the inversion *is* the idea, and
548    /// it is the one part every renderer implements identically.
549    #[must_use]
550    pub const fn edges(self) -> (Edge, Edge) {
551        match self {
552            Self::Raised => (Edge::Light, Edge::Dark),
553            Self::Inset => (Edge::Dark, Edge::Light),
554        }
555    }
556
557    /// Pressing inverts. A raised control reads as inset while held.
558    ///
559    /// Stated here rather than left to each consumer because a cascade can
560    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
561    /// resolves this per call site, eighteen times.
562    #[must_use]
563    pub const fn pressed(self) -> Self {
564        match self {
565            Self::Raised => Self::Inset,
566            Self::Inset => Self::Raised,
567        }
568    }
569}
570
571/// One side of a bevel, named by the intent it takes.
572#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
573pub enum Edge {
574    /// The lit side.
575    Light,
576    /// The shadowed side.
577    Dark,
578}
579
580impl Intent for Edge {
581    fn token(self) -> &'static str {
582        match self {
583            Self::Light => "bevel-light",
584            Self::Dark => "bevel-dark",
585        }
586    }
587}
588
589/// A surface intent a region is filled with.
590///
591/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
592/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
593/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
594/// `makeover-immediate` at compile time and left neither able to move until
595/// both published. The vocabulary exists to grow and the renderers exist to
596/// disagree about how much of it they answer, so growth must not be a
597/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
598/// resolved through a fallible lookup, and a missing intent is answered with
599/// structure rather than with a substituted colour.
600///
601/// [`Sunken`]: Fill::Sunken
602#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
603#[non_exhaustive]
604pub enum Fill {
605    /// The page behind everything.
606    Page,
607    /// A surface lifted off the page: cards, controls, menus, toasts.
608    Raised,
609    /// A surface floating above the page rather than resting on it.
610    Overlay,
611    /// The inside of a well.
612    Well,
613    /// A surface set back from the one it sits on, by colour and nothing else.
614    ///
615    /// Not a well. A well is a hole with an edge, and the two are authored in
616    /// opposite directions: `makeover` derives `surface-well` by inverting
617    /// against the theme's own content colour, while `surface-sunken` is
618    /// authored and free to sit darker than raised (goingson's does). Naming
619    /// only the well left the recessed-with-no-edge surface unsayable, which is
620    /// what an unchosen tab is: it recedes so the chosen one can come forward,
621    /// and it carries no bevel of its own.
622    ///
623    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
624    /// and could not delete the line because no member described it.
625    Sunken,
626}
627
628// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
629// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
630// had something to paint. makeover-tui found that wrong within a day: page is
631// the surface a well is usually cut into, so on a terminal that substitution
632// produces exactly the invisibility it was meant to prevent, and the right
633// answer there is a drawn edge rather than a different colour.
634//
635// Substituting one intent for another is renderer policy. The description says
636// what the region is and stops.
637
638impl Intent for Fill {
639    fn token(self) -> &'static str {
640        match self {
641            Self::Page => "surface-page",
642            Self::Raised => "surface-raised",
643            Self::Overlay => "surface-overlay",
644            Self::Well => "surface-well",
645            Self::Sunken => "surface-sunken",
646        }
647    }
648}
649
650/// How a region sits relative to the surface behind it.
651///
652/// Fill and bevel are named together because naming them apart is what let
653/// them disagree. Every consumer measured had at least one region carrying a
654/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
655/// and recorded the bug in its doc comment, and Balanced Breakfast still had
656/// twelve of them a year later. A single name for the pair makes that
657/// unrepresentable.
658/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
659/// release: a depth this renderer has no drawing for should cost it a
660/// wildcard arm, not a compile error and a wait on someone else's publish.
661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
662#[non_exhaustive]
663pub enum Depth {
664    /// Level with its surroundings. No edge.
665    Flat,
666    /// A card laid on the panel it sits in.
667    Raised,
668    /// A hole in the panel, with content down inside it. For anything the
669    /// user looks *into*: a table body, a tag tree, a text field.
670    Well,
671    /// Set back from what it sits on, by colour alone. No edge.
672    ///
673    /// The one member carrying a fill without a bevel, so a renderer cannot
674    /// assume the two arrive together. That is deliberate and it is still the
675    /// pairing rule: both halves come off the same `Depth`, so they cannot
676    /// disagree, and here one half is legitimately absent.
677    ///
678    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
679    /// Recessed and level-with are different claims, and only one of them
680    /// needs a colour.
681    Sunken,
682    /// A surface sitting *over* the page rather than in it. A modal, a popover,
683    /// a menu.
684    ///
685    /// Takes elevation and no bevel: a surface overlaying the page is lifted
686    /// off it, and a surface in the page is cut into it. That is the same
687    /// pairing rule the rest of the enum holds, applied to the one case where
688    /// the separation is not an edge at all — the lift and the scrim behind it
689    /// are already saying where the surface is.
690    ///
691    /// Every renderer had the surface before it had this variant.
692    /// `makeover-tui` carries `Palette::overlay`, `makeover-immediate` gained
693    /// `Palette::elevation` at 0.10.0, and `makeover-webview` emits
694    /// `--elevation-overlay`. What was missing was the route from a description
695    /// to any of them, which is why this is one variant rather than a feature.
696    Overlay,
697}
698
699impl Depth {
700    /// The edge this depth is drawn with, if it has one.
701    #[must_use]
702    pub const fn bevel(self) -> Option<Bevel> {
703        match self {
704            // Sunken joins Flat here, for the opposite reason: Flat has no edge
705            // because nothing separates it from its surroundings, and Sunken has
706            // none because its colour is already doing the separating.
707            Self::Flat | Self::Sunken => None,
708            // A third reason to have no edge, which is why it gets its own arm
709            // rather than joining the two above: an overlay is separated by the
710            // lift and by the scrim behind it, so an edge would be a second
711            // answer to a question already answered.
712            Self::Overlay => None,
713            Self::Raised => Some(Bevel::Raised),
714            Self::Well => Some(Bevel::Inset),
715        }
716    }
717
718    /// The surface this depth is filled with.
719    ///
720    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
721    /// which is the difference between level-with and painted-the-same-colour.
722    #[must_use]
723    pub const fn fill(self) -> Option<Fill> {
724        match self {
725            Self::Flat => None,
726            Self::Raised => Some(Fill::Raised),
727            Self::Well => Some(Fill::Well),
728            Self::Sunken => Some(Fill::Sunken),
729            Self::Overlay => Some(Fill::Overlay),
730        }
731    }
732
733    /// Pressing a raised region reads as a well, and nothing else moves.
734    ///
735    /// [`Depth::Overlay`] is untouched along with the rest: an overlay is a
736    /// surface, not a control, so there is nothing there to press.
737    #[must_use]
738    pub const fn pressed(self) -> Self {
739        match self {
740            Self::Raised => Self::Well,
741            other => other,
742        }
743    }
744}
745
746/// An interaction state a region can be in, beside whatever [`Depth`] it is.
747///
748/// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
749/// and a disabled field is still a [`Depth::Well`], so folding either member
750/// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
751/// something that is not a depth, and would leave disabled-button and
752/// disabled-field sharing one variant that cannot tell them apart.
753///
754/// # Why hover and pressed are not members
755///
756/// The line is whether every renderer has the state to express, not whether CSS
757/// does. Hover is renderer policy and `makeover-webview` says so in its own
758/// header: a terminal and an immediate-mode painter have no pointer hovering
759/// over anything, and pressed already arrives through [`Bevel::pressed`] and
760/// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
761/// rather than a separate condition.
762///
763/// Focus and disabled are different in kind. A TUI has a focused widget and a
764/// greyed-out one; so does egui. Both were unsayable here, so all three webview
765/// consumers supplied them from outside the primitive by out-specifying rules
766/// they did not own: goingson alone carries 19 of them, and the MNW server
767/// another 21. That is the divergence this crate exists to end, arriving one
768/// layer down.
769///
770/// # The principle this encodes
771///
772/// A primitive owns every state it implies. A renderer that emits a hover rule
773/// for a thing owes disabled and the capability answer for that same thing,
774/// because anything less exports the completion work to N consumers who will
775/// each do it differently.
776///
777/// Focus is not on that list and was removed from this axis in 0.19.0. It is
778/// the renderer's, decided after the description; see the crate header, "Reach,
779/// focus and the focus ring", for the three terms and who owns each.
780///
781/// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
782/// must not be a lockstep event across the three renderers.
783#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
784#[non_exhaustive]
785pub enum State {
786    /// Present, visible, and not answering.
787    ///
788    /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
789    /// control keeps the surface it always had and stops responding, so what
790    /// changes is its content and its interactivity rather than what it is.
791    Disabled,
792}
793
794impl State {
795    /// Whether a region in this state stops answering the pointer.
796    ///
797    /// Stated in the description rather than left to each renderer, on the same
798    /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
799    /// immediate-mode renderer resolves it per call site, so leaving it unsaid
800    /// means resolving it once per consumer and disagreeing.
801    #[must_use]
802    pub const fn suppresses_interaction(self) -> bool {
803        // A match rather than a bare `true`, so a member added to this
804        // `#[non_exhaustive]` axis has to answer the question rather than
805        // inheriting an answer.
806        match self {
807            Self::Disabled => true,
808        }
809    }
810}
811
812impl Intent for State {
813    fn token(self) -> &'static str {
814        match self {
815            // Reusing the muted content intent rather than minting a
816            // `disabled` colour. Disabled is a reduction and not a status, and
817            // `makeover-webview`'s progress rules already record the reading
818            // that `content-muted` is what disabled looks like.
819            Self::Disabled => "content-muted",
820        }
821    }
822}
823
824/// What a region is saying, when it is saying something.
825///
826/// The one intent family shared by badges, notices and nothing else. Kept
827/// separate from [`Fill`] because a surface is where a thing sits and a tone is
828/// what it means, and the three apps agree on the four statuses:
829/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
830/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
831/// `.toast.error` in Balanced Breakfast.
832///
833/// The per-tag palette (`category-one` through `category-six`) is deliberately
834/// not here. Which colour a *particular* tag takes is app domain, and both
835/// webview apps already carry it as a `data-color` attribute.
836#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
837pub enum Tone {
838    /// No status. Reads as ordinary de-emphasised content.
839    Neutral,
840    /// Something worth knowing and nothing to do about it.
841    Info,
842    /// Something finished and it worked.
843    Success,
844    /// Something the user should look at before continuing.
845    Warning,
846    /// Something broken, or something about to be destroyed.
847    Danger,
848}
849
850impl Intent for Tone {
851    fn token(self) -> &'static str {
852        match self {
853            // Neutral has no status token of its own. It takes the muted
854            // content intent, which is what both webview apps already spell as
855            // `data-color="muted"`.
856            Self::Neutral => "content-muted",
857            Self::Info => "info",
858            Self::Success => "success",
859            Self::Warning => "warning",
860            Self::Danger => "danger",
861        }
862    }
863}
864
865/// A small labelled thing that sits inside something else.
866///
867/// Two members, because the three apps drew three taxonomies and only one line
868/// runs through all of them: does it answer a click. audiofiles has
869/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
870/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
871/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
872/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
873/// to decide which of the two it always was.
874///
875/// The evidence that a chip is a real concept rather than a badge with a
876/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
877/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
878/// holds itself down", which is exactly what [`Depth::pressed`] already says.
879#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
880pub enum Token {
881    /// Non-interactive status or count. Answers no click.
882    Badge,
883    /// An interactive or removable token. Answers a click, and latches if it
884    /// stands for a filter that is either on or off.
885    Chip {
886        /// Whether it carries its own remove affordance.
887        removable: bool,
888    },
889}
890
891impl Token {
892    /// Whether this answers a click.
893    ///
894    /// The whole difference between the two members, and the reason a renderer
895    /// with no hover (a touch surface, a terminal) can still tell them apart.
896    #[must_use]
897    pub const fn interactive(self) -> bool {
898        matches!(self, Self::Chip { .. })
899    }
900
901    /// How it sits, given whether it is currently latched down.
902    ///
903    /// A badge is flat: it is a label, and giving it an edge would say it can
904    /// be pressed. A chip is raised, and inset while latched.
905    #[must_use]
906    pub const fn depth(self, latched: bool) -> Depth {
907        match self {
908            Self::Badge => Depth::Flat,
909            Self::Chip { .. } if latched => Depth::Well,
910            Self::Chip { .. } => Depth::Raised,
911        }
912    }
913}
914
915/// Something the app is telling the user, unprompted.
916///
917/// Two concepts, not one with a placement. They differ in more than where they
918/// sit: a toast is transient, stacked and self-dismissing, and a banner is
919/// persistent, in flow, one per region, and dismissed by fixing the condition
920/// it reports. Folding them into one member with a placement parameter would
921/// make lifetime, stacking and dismissal all placement-dependent, which is the
922/// description leaking renderer policy.
923///
924/// All three apps have banners: `info_banner` and `warning_banner` in
925/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
926/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
927/// webview apps also have toasts. So neither member is speculative, and no app
928/// gains a concept it lacks except audiofiles, whose renderer may legitimately
929/// decline to draw a toast at all.
930#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
931pub enum Notice {
932    /// Transient, stacked, dismisses itself.
933    Toast,
934    /// Persistent, in flow, one per region, dismissed by fixing the cause.
935    Banner,
936}
937
938impl Notice {
939    /// Whether it goes away on its own.
940    #[must_use]
941    pub const fn transient(self) -> bool {
942        matches!(self, Self::Toast)
943    }
944
945    /// How it sits.
946    ///
947    /// A toast floats above the page rather than resting on it, which is
948    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
949    /// flow. Both are raised, and they are raised off different things.
950    #[must_use]
951    pub const fn fill(self) -> Fill {
952        match self {
953            Self::Toast => Fill::Overlay,
954            Self::Banner => Fill::Raised,
955        }
956    }
957}
958
959/// The parts of a list row.
960///
961/// Four to begin with, taken from Balanced Breakfast, which was the only
962/// consumer that had all of them (`row-primary`, `row-secondary`, `row-meta`,
963/// `row-actions`). audiofiles has two and no slot structure at all, so it gains
964/// meta and actions as real work rather than a rename; goingson moves off
965/// `task-row` / `task-cell`.
966///
967/// [`Tokens`](Self::Tokens) joined at 0.9.0, and `#[non_exhaustive]` with it.
968/// See the crate header for why the two arrived together.
969///
970/// # Meta against Tokens
971///
972/// The line is whether the thing has its own standing. `Meta` is one short
973/// trailing fact about the row, written as text: a count, a size, a date.
974/// `Tokens` is a set of small labelled things, each of which can be toned and
975/// can answer a click. "3 files" is meta. A status badge that is amber, and a
976/// tag you can click to filter by, are tokens.
977///
978/// Keeping them apart is what a single widened slot would have foreclosed. A
979/// renderer can right-align one string and cannot usefully do the same to a
980/// strip of chips, and a fact that is not clickable should not be drawn as
981/// though it were.
982#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
983#[non_exhaustive]
984pub enum RowPart {
985    /// The thing itself. What the row is called.
986    Primary,
987    /// Supporting text under the primary.
988    Secondary,
989    /// A short trailing fact: a count, a size, a date.
990    Meta,
991    /// Controls that act on this row.
992    Actions,
993    /// Small labelled things belonging to the row: badges, chips, tags.
994    ///
995    /// Each carries its own [`Token`] kind and [`Tone`], so a renderer with no
996    /// colour still has the kind to work with, and one with no chips still has
997    /// the label. That is the constrained-consumer test this vocabulary exists
998    /// to pass, and it is why the tone lives on the token rather than on the
999    /// part.
1000    Tokens,
1001    /// How much of a set the row's thing has done: a [`Meter`] in the row.
1002    ///
1003    /// Added 0.11.0, `da5666ae`, and it is [`Tokens`](Self::Tokens)'s problem
1004    /// again with a different payload. [`Meter`] arrived at 0.10.0 and closed
1005    /// two of the seven sites that asked for it; the other five sit in rows, and
1006    /// a row holds no nodes by the ruling that a row part may not carry an
1007    /// arbitrary node — the door through which a description becomes a
1008    /// templating language. So the part carries the *description of a bar*
1009    /// rather than a node, exactly as `Tokens` carries tags rather than nodes.
1010    ///
1011    /// Without it a row flattens the proportion into [`Meta`](Self::Meta) as
1012    /// "3/7 subtasks", which keeps both numbers and loses the reading, the same
1013    /// way a toned status badge read as prose before `Tokens`.
1014    Proportion,
1015}
1016
1017impl RowPart {
1018    /// The content intent the part takes.
1019    #[must_use]
1020    pub const fn intent(self) -> &'static str {
1021        match self {
1022            Self::Primary => "content",
1023            Self::Secondary => "content-secondary",
1024            Self::Meta => "content-muted",
1025            // Actions carry controls rather than text, so they inherit.
1026            Self::Actions => "content",
1027            // So do tokens: each one carries its own tone, and a part-level
1028            // intent underneath it would fight the token that sits on it.
1029            Self::Tokens => "content",
1030            // And so does a proportion, for the same reason: the meter carries
1031            // the tone, and it is about the ratio rather than about the row.
1032            Self::Proportion => "content",
1033        }
1034    }
1035}
1036
1037/// How far down the heading tree a title sits.
1038///
1039/// Three, and only the three that are actually headings. The bands those used
1040/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
1041/// and `.detail-header`) are arrangement, not type, and live at
1042/// [`Region::Band`]. One of them contains no text at all.
1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1044pub enum Heading {
1045    /// Names the whole screen. One per screen.
1046    Page,
1047    /// Names a block within the screen.
1048    Section,
1049    /// Names a sub-block inside an already-named section.
1050    Subsection,
1051}
1052
1053impl Heading {
1054    /// Whether a rule follows the heading.
1055    ///
1056    /// audiofiles' `section_header` draws a separator and its
1057    /// `subsection_label` deliberately does not, which is the only thing
1058    /// distinguishing the two once weight and colour are deferred.
1059    #[must_use]
1060    pub const fn separated(self) -> bool {
1061        matches!(self, Self::Section)
1062    }
1063}
1064
1065/// A control that picks between things.
1066///
1067/// Three, because three distinct behaviours are in play and collapsing any two
1068/// loses something. A segmented control picks a value; a tab picks a pane; a
1069/// toggle picks nothing and simply holds itself on or off.
1070#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1071pub enum Selector {
1072    /// Exactly one of N, and the options abut.
1073    Segmented,
1074    /// Independent on or off, on its own.
1075    Toggle,
1076    /// Navigation between panes. The folder semantic.
1077    Tabs,
1078}
1079
1080impl Selector {
1081    /// How the chosen option sits.
1082    ///
1083    /// Held in for a segmented control and a toggle, which is the same shape
1084    /// pressing produces and the whole economy of the idiom: one appearance,
1085    /// two reasons to wear it. A tab is the exception, because the selected
1086    /// folder tab comes *forward* to join the pane it opens.
1087    #[must_use]
1088    pub const fn chosen(self) -> Depth {
1089        match self {
1090            Self::Segmented | Self::Toggle => Depth::Well,
1091            Self::Tabs => Depth::Raised,
1092        }
1093    }
1094
1095    /// How the options that were *not* picked sit.
1096    ///
1097    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
1098    /// option falling through to [`Depth::Flat`], which says it is level with
1099    /// the strip it sits in, and no renderer emitted anything for it. That is
1100    /// wrong in both directions and goingson proved it: its unchosen tabs are
1101    /// recessed by hand, and being recessed is *why* the chosen one reads as
1102    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
1103    /// drawn on the strip's own colour, which is a much weaker folder effect
1104    /// than the contrast the idiom is named after.
1105    ///
1106    /// Each member is the inverse of its chosen state, which is the whole
1107    /// content of "picked" once colour is deferred:
1108    ///
1109    /// - Tabs recede, so the chosen one comes forward.
1110    /// - A segment and a toggle stand up, so the chosen one is held in.
1111    #[must_use]
1112    pub const fn unchosen(self) -> Depth {
1113        match self {
1114            Self::Tabs => Depth::Sunken,
1115            Self::Segmented | Self::Toggle => Depth::Raised,
1116        }
1117    }
1118
1119    /// Whether the options touch.
1120    ///
1121    /// The gap is the entire difference between a segmented control and a row
1122    /// of buttons that happen to sit near each other, which is what audiofiles'
1123    /// `segmented_control` says in its own comment and why it zeroes the
1124    /// spacing by hand.
1125    #[must_use]
1126    pub const fn abutting(self) -> bool {
1127        matches!(self, Self::Segmented | Self::Tabs)
1128    }
1129}
1130
1131/// What is in a region right now.
1132///
1133/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
1134/// nothing at all is renderer policy, the same class of decision that got
1135/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
1136/// each grew a skeleton with differently-named parts; both keep them, as the
1137/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
1138/// and needs none, because an immediate-mode renderer simply repaints.
1139///
1140/// # Four states and not two, as of 0.12.0
1141///
1142/// `703f4cd2`. It named `Ready` and `Pending` and stopped, so a described screen
1143/// whose list came back empty had to render an empty region or invent its own
1144/// placeholder text, and neither says what it is. goingson draws one at 27 sites
1145/// across 12 files and Balanced Breakfast at 9, with a class family that had
1146/// already drifted into `empty-state`, `empty-state--error`, `error-state` and
1147/// six more.
1148///
1149/// The four are one axis because they are mutually exclusive: a region shows its
1150/// content, or a sign that it is coming, or a sign that there is none, or a sign
1151/// that it broke. Never two. That is the test for one enum against several
1152/// fields, and it is why this grew rather than a new member arriving beside it.
1153///
1154/// # What is not here
1155///
1156/// **The message.** "No projects yet" is content, and this names a state. It
1157/// lives with whatever holds the region — in quasi's case a `Slot` — alongside
1158/// the action that leads out of the emptiness, since an address is the one thing
1159/// this crate never names.
1160///
1161/// **How much room it gets.** goingson's `--compact`, `--dashboard` and
1162/// `--padded` are the same state at three sizes, and a size is
1163/// `makeover-geometry`'s question. Naming them here would be this crate stating
1164/// values again.
1165///
1166/// **The icon.** Presentation, and each host has its own answer or none.
1167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1168#[non_exhaustive]
1169pub enum Readiness {
1170    /// The content is here.
1171    Ready,
1172    /// The content is on its way.
1173    ///
1174    /// For a region that changes *after* the first paint, and never for the
1175    /// first paint itself: see "First paint is final paint" in the crate header.
1176    /// A host that renders once, with its data already in hand, has nothing to
1177    /// say this about, and a screen arriving in this state is describing a
1178    /// moment its host should not have been in.
1179    ///
1180    /// What stands in occupies the geometry the content will occupy. A stand-in
1181    /// sized to itself rather than to what replaces it is the reflow the rule
1182    /// forbids, arriving one repaint later.
1183    Pending,
1184    /// The content arrived and there is none of it.
1185    ///
1186    /// Not a failure. An empty list is the normal state of a new install, and a
1187    /// renderer that drew it in a danger tone would be reporting a fault where
1188    /// there is none.
1189    Empty,
1190    /// The content did not arrive.
1191    Failed,
1192}
1193
1194impl Readiness {
1195    /// Whether the region draws its own content, or something standing in for
1196    /// it.
1197    ///
1198    /// The question every renderer asks first, so it is answered once here
1199    /// rather than by a `matches!` in each. A state added later is a stand-in
1200    /// until proven otherwise: falling back to drawing content that may not be
1201    /// there is the worse of the two mistakes.
1202    #[must_use]
1203    pub const fn shows_content(self) -> bool {
1204        matches!(self, Self::Ready)
1205    }
1206
1207    /// What the state means, for a renderer choosing a colour.
1208    ///
1209    /// Derived rather than carried, which is the opposite of [`Meter`] and
1210    /// [`Figure`], and the difference is worth stating: a proportion's meaning
1211    /// depends on what is being counted and only the app knows it, while
1212    /// "nothing here yet" and "this broke" mean the same thing in every app that
1213    /// will ever have them.
1214    #[must_use]
1215    pub const fn tone(self) -> Tone {
1216        match self {
1217            Self::Failed => Tone::Danger,
1218            _ => Tone::Neutral,
1219        }
1220    }
1221}
1222
1223/// How much of a set is done.
1224///
1225/// Added 0.10.0. Nine sites across the two webview apps drew a bar and nothing
1226/// here named one, so every described screen concatenated the two numbers into
1227/// its heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m
1228/// est, over". Every fact survives that and the reading does not, which is the
1229/// same loss `RowPart::Tokens` closed when a toned status badge became prose.
1230///
1231/// # Why a pair and not a percentage
1232///
1233/// Both numbers, not the percentage the apps compute from them. The percentage
1234/// was the obvious shape and it had already been tried: goingson's
1235/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
1236/// away the one case the bar exists to show — 45 minutes tracked against a
1237/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
1238/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
1239/// companion flag, and [`percent`](Meter::percent) is still one call away for a
1240/// renderer that wants it.
1241///
1242/// The pair is also what the apps already have at every site. All seven
1243/// determinate bars write the ratio into the accessible layer and never the
1244/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
1245/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
1246/// percentage member would have made [`label`](Meter::label) mandatory at every
1247/// call site, which is the concatenated text this member removes, moved one
1248/// layer down.
1249///
1250/// # What this is not
1251///
1252/// The progress of an *operation*. Two of the nine sites are that — goingson's
1253/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
1254/// purpose. Both are imperative controllers over a live handle, driven by a tick
1255/// or an event stream, and a description is built once and dropped. Holding one
1256/// would mean growing a way to update a description between renders, which is a
1257/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
1258/// honest part.
1259///
1260/// The two cases are distinguishable in the markup rather than by taste: every
1261/// determinate bar in both apps carries a tone, and neither operation bar
1262/// carries one. Two codebases drew that line the same way without coordinating.
1263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1264pub struct Meter<'a> {
1265    /// How much is done. May exceed [`total`](Self::total), and that is the
1266    /// case worth drawing.
1267    pub done: u32,
1268    /// How much there is to do. Zero means there is no set, not that the set is
1269    /// complete.
1270    pub total: u32,
1271    /// What the proportion means right now.
1272    ///
1273    /// Carried rather than derived, because no renderer can work it out. The
1274    /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
1275    /// a time estimate, and goingson picks between them from `is_over_estimate`,
1276    /// a fact about the data and not about the number.
1277    pub tone: Tone,
1278    /// What is being counted, if the bar says so: "subtasks", "tasks".
1279    ///
1280    /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
1281    /// and the two numbers; handing it the assembled string would put the
1282    /// sentence order in the description, where a terminal at one line and a
1283    /// tooltip want different ones.
1284    pub label: Option<&'a str>,
1285}
1286
1287impl<'a> Meter<'a> {
1288    /// A proportion with no tone and no label.
1289    #[must_use]
1290    pub const fn new(done: u32, total: u32) -> Self {
1291        Self {
1292            done,
1293            total,
1294            tone: Tone::Neutral,
1295            label: None,
1296        }
1297    }
1298
1299    /// What the proportion means.
1300    #[must_use]
1301    pub const fn tone(mut self, tone: Tone) -> Self {
1302        self.tone = tone;
1303        self
1304    }
1305
1306    /// What is being counted.
1307    #[must_use]
1308    pub const fn label(mut self, label: &'a str) -> Self {
1309        self.label = Some(label);
1310        self
1311    }
1312
1313    /// How full the bar is, 0 to 100, clamped.
1314    ///
1315    /// For drawing, which is the only thing a clamped number is good for. Ask
1316    /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
1317    /// is `time_progress`'s bug again with the clamp moved.
1318    ///
1319    /// An empty set reads as 0. Nothing is done, because there is nothing to do
1320    /// and no bar to fill; the apps guard on the count before drawing at all.
1321    #[must_use]
1322    pub const fn percent(&self) -> u8 {
1323        if self.total == 0 {
1324            return 0;
1325        }
1326        let scaled = (self.done as u64 * 100) / self.total as u64;
1327        if scaled > 100 { 100 } else { scaled as u8 }
1328    }
1329
1330    /// Whether more is done than there was to do.
1331    ///
1332    /// The fact [`percent`](Self::percent) destroys, kept reachable so a
1333    /// renderer can mark the over-run rather than drawing a full bar and
1334    /// implying it landed exactly.
1335    #[must_use]
1336    pub const fn overflowing(&self) -> bool {
1337        self.done > self.total
1338    }
1339
1340    /// Whether there is a set at all.
1341    ///
1342    /// A meter over nothing is sayable on purpose, for the same reason a field
1343    /// with no options is: it is what an app with an unloaded count actually
1344    /// has, and a renderer that shows an empty bar says so on screen rather than
1345    /// dividing by zero.
1346    #[must_use]
1347    pub const fn is_empty(&self) -> bool {
1348        self.total == 0
1349    }
1350}
1351
1352/// One figure with a caption: a number and what it counts.
1353///
1354/// The dashboard shape. A large value over a small caption, several of them in a
1355/// strip: a current streak, a completion rate, a total. Added 0.11.0,
1356/// `93c6a174`, after goingson turned out to have five of them across five
1357/// screens with five class vocabularies for the one shape — `task-overview-stat`,
1358/// `stat-box`, `month-stat-item`, `contact-summary-stat`, `sync-stat`. Four put
1359/// the value above the caption and one inverts it, which is drift inside the
1360/// shape rather than a second shape.
1361///
1362/// # Why the value is text
1363///
1364/// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
1365/// formatted, and the formatting is the app's because only it knows whether the
1366/// number is a percentage, a duration or a ratio. This carries none of the
1367/// arithmetic [`Meter`] carries, and that is the difference between them: a
1368/// meter is a proportion a renderer draws, and a figure is a fact a renderer
1369/// sets in type.
1370///
1371/// # Tone is carried, for [`Meter`]'s reason
1372///
1373/// Three of the five sites tone the figure by their own means — `red`/`blue` on
1374/// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
1375/// sync. So tone is carried at every site that needs it and derived at none, and
1376/// no renderer can work out that a streak of zero is worth colouring.
1377///
1378/// # What is not here
1379///
1380/// Whether the figure answers a click. One of the five is a control — sync's
1381/// "Not Applied: 3" opens the list — and an action is not something this crate
1382/// can name: nothing here knows what a route is. That belongs beside the figure
1383/// in whatever layer holds the actions, the same way a row's activation sits
1384/// beside its parts rather than inside them.
1385///
1386/// The arrangement is not here either. Several figures in a strip is a set, and
1387/// a renderer given them one at a time cannot tell it is looking at one; the
1388/// layer that holds the tree is where the set gets said.
1389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1390pub struct Figure<'a> {
1391    /// The number, formatted the way the app means it to read.
1392    pub value: &'a str,
1393    /// What it counts. The caption under the value.
1394    pub caption: &'a str,
1395    /// How the value has moved, if the app is tracking that.
1396    ///
1397    /// Added 0.13.0. Text, for [`value`](Self::value)'s reason: only the app
1398    /// knows whether a move reads as `+12.5%`, `+3` or `2x`, and a renderer
1399    /// handed a number would have to guess.
1400    ///
1401    /// This is what [`tone`](Self::tone) was for and had no consumer of. The MNW
1402    /// server has four screens whose stat card is a label, a value and a delta,
1403    /// and the delta is the toned part: the figure itself is an ordinary fact
1404    /// and it is the movement that reads as good or bad. Without this the delta
1405    /// has to be folded into the caption, which loses the tone and reads as a
1406    /// longer caption rather than as a second, smaller line.
1407    pub change: Option<&'a str>,
1408    /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
1409    ///
1410    /// Applies to [`change`](Self::change) where there is one, since that is the
1411    /// part that carries the judgement, and to the value where there is not.
1412    pub tone: Tone,
1413}
1414
1415impl<'a> Figure<'a> {
1416    /// A figure that is an ordinary fact.
1417    #[must_use]
1418    pub const fn new(value: &'a str, caption: &'a str) -> Self {
1419        Self {
1420            value,
1421            caption,
1422            change: None,
1423            tone: Tone::Neutral,
1424        }
1425    }
1426
1427    /// How the value has moved.
1428    #[must_use]
1429    pub const fn change(mut self, change: &'a str) -> Self {
1430        self.change = Some(change);
1431        self
1432    }
1433
1434    /// What the figure means.
1435    #[must_use]
1436    pub const fn tone(mut self, tone: Tone) -> Self {
1437        self.tone = tone;
1438        self
1439    }
1440}
1441
1442/// Something the user can do, and what it costs to say so.
1443///
1444/// Added 0.17.0, out of `quasi-tui`: the terminal renderer had drawn one of
1445/// these for months and every other consumer that wanted a button had written
1446/// its own, because this layer named [`RowPart::Actions`] as a *slot* and never
1447/// named the thing that goes in it. Beside [`Meter`] and [`Figure`] for the
1448/// reason those are here: a renderer that is handed the parts has to decide how
1449/// to say them, and a renderer that is handed a finished string has already had
1450/// the decision made for it.
1451///
1452/// No address. Where a control goes is the app's business and every host
1453/// follows it differently — an `hx-get`, a protocol URL, a function call — so
1454/// the description says what the control *is* and the caller keeps what it
1455/// does. That is the same split [`Choice`] makes.
1456///
1457/// No confirmation flag either, and that one is a finding rather than an
1458/// omission: a question asked *after* a control is pressed belongs to whatever
1459/// is holding the interaction, and a renderer that drew it would be asking
1460/// before there was anything to answer.
1461/// How a picture sits in the box it is given.
1462///
1463/// An intent rather than a value, so a renderer picks the expression it has:
1464/// `object-fit` in a webview, a texture's UV rect in egui, and in a terminal a
1465/// choice about how many cells the blit gets. Named because MNW already makes
1466/// the distinction deliberately at 17 sites and makes it three different ways,
1467/// which is a policy the app decided rather than one a shared crate would be
1468/// picking by accident.
1469#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1470#[non_exhaustive]
1471pub enum Fit {
1472    /// The picture's own proportions, and the box takes the height they imply.
1473    ///
1474    /// The default because it is the only one that shows the whole picture at
1475    /// its own shape, so a renderer that ignores this enum entirely is still
1476    /// right about the common case. A screenshot wants this; the shipped MNW
1477    /// carousel sets no `object-fit` at all, which is this.
1478    #[default]
1479    Natural,
1480    /// Fill the box and crop whatever does not fit.
1481    ///
1482    /// For a picture in a slot whose shape the layout fixed: a thumbnail, an
1483    /// avatar, cover art. 15 of MNW's 17 sites.
1484    Cover,
1485    /// Fit inside the box whole, leaving space on two sides.
1486    ///
1487    /// The letterbox. For when the whole picture matters more than filling the
1488    /// space, and the space is not the picture's shape.
1489    Contain,
1490}
1491
1492/// A picture, and what it says to someone who is not looking at it.
1493///
1494/// # No source
1495///
1496/// [`Act`]'s split, for [`Act`]'s reason. A source is an address, and this
1497/// crate has no notion of an address: it says what a thing *is* and the caller
1498/// keeps what it points at. The three findings dropped from 0.11.0 were all
1499/// this same shape.
1500///
1501/// It matters more here than it does for a control, because a picture is the
1502/// one member where the address is most of what a webview needs and *none* of
1503/// what the description knows. `quasi_router::Node::Image` carries the URL, the
1504/// way it carries an `Action` for a control.
1505///
1506/// # Why [`alt`](Self::alt) is not optional
1507///
1508/// Every other host has to draw something, and for two of the three the alt
1509/// text is not a fallback but the whole rendering: a terminal without a
1510/// graphics protocol has the words and nothing else. Making it optional would
1511/// make "this picture is invisible on a terminal" the default, and the
1512/// description would be carrying a webview assumption in its shape.
1513///
1514/// An image that genuinely says nothing — a rule, a spacer, a decoration
1515/// repeating what the text beside it already said — is an empty `alt`, which is
1516/// the same thing HTML means by it and is a claim rather than an oversight.
1517#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1518pub struct Image<'a> {
1519    /// What the picture says, for anything not showing it.
1520    ///
1521    /// Empty means the picture is decorative and adds nothing to the text
1522    /// around it. See the type's own docs on why this is not an `Option`.
1523    pub alt: &'a str,
1524    /// A visible line under the picture, where the app wants one.
1525    ///
1526    /// Distinct from [`alt`](Self::alt) and the difference is who it is for: a
1527    /// caption is content everybody reads, alt text is what stands in for the
1528    /// picture. A screenshot captioned "The library view" still needs alt text
1529    /// describing what is in the shot.
1530    pub caption: Option<&'a str>,
1531    /// How it sits in the box it is given.
1532    pub fit: Fit,
1533    /// The picture's own dimensions, where the app knows them.
1534    ///
1535    /// **Not a display size**, and that distinction is what makes this belong
1536    /// here rather than fall foul of the deferral rule. Saying a picture should
1537    /// be 320 points wide is a layout value and is not the description's to
1538    /// give. Saying the file is 5120x3412 is a fact *about the picture*, the
1539    /// same kind of fact [`alt`](Self::alt) is, and no renderer can find it out
1540    /// without fetching the bytes.
1541    ///
1542    /// # What it is for, and it is not decoration
1543    ///
1544    /// Without it a renderer cannot reserve room, so the picture occupies
1545    /// nothing until it arrives and then takes its full height at once,
1546    /// shoving everything below it down the screen. Measured on MNW's landing
1547    /// page 2026-08-14: a 478px jump per frame, and a cumulative layout shift
1548    /// of 0.087 for the page, which is most of the way to the 0.1 that counts
1549    /// as bad.
1550    ///
1551    /// Every host wants it and none can derive it. A webview writes `width` and
1552    /// `height` so the browser holds the space; egui sizes a texture; a
1553    /// terminal with a graphics protocol scales a blit into cells. This was
1554    /// missing from 0.21.0, which is the release that added [`Image`], and its
1555    /// absence is the defect rather than an omission.
1556    ///
1557    /// `None` is honest and common: a creator-uploaded image whose dimensions
1558    /// the app never recorded genuinely does not know. It means the renderer
1559    /// cannot reserve, not that the picture has no size.
1560    pub intrinsic: Option<Extent>,
1561    /// Whether the picture is needed with the screen, or can arrive later.
1562    pub loading: Loading,
1563}
1564
1565/// A picture's own pixel dimensions.
1566///
1567/// Deliberately not [`makeover_geometry`]'s business. Geometry answers *how
1568/// much space a thing should get*, which is a scale question with the same
1569/// answer on every screen. This is the intrinsic size of one asset, which is a
1570/// fact about that asset and varies per picture.
1571///
1572/// [`makeover_geometry`]: https://docs.rs/makeover-geometry
1573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1574pub struct Extent {
1575    /// Width in the picture's own pixels.
1576    pub width: u32,
1577    /// Height in the picture's own pixels.
1578    pub height: u32,
1579}
1580
1581impl Extent {
1582    /// A picture's dimensions.
1583    #[must_use]
1584    pub const fn new(width: u32, height: u32) -> Self {
1585        Self { width, height }
1586    }
1587
1588    /// Width over height, or `None` if either side is zero.
1589    ///
1590    /// The form a renderer actually reserves space with: a box that knows its
1591    /// proportion holds the right height at any width, which is what a
1592    /// responsive picture needs and what a fixed pixel height cannot give.
1593    #[must_use]
1594    pub fn ratio(self) -> Option<f32> {
1595        (self.width > 0 && self.height > 0).then(|| self.width as f32 / self.height as f32)
1596    }
1597}
1598
1599/// When a picture is needed.
1600///
1601/// A claim about *importance and position* rather than a fetch mechanism, which
1602/// is why it is the description's to make: only the app knows whether a picture
1603/// is the first thing on the screen or the fortieth thing down a list.
1604///
1605/// # Eager is the default, and that is a correctness choice
1606///
1607/// 0.21.0 emitted the webview's `loading="lazy"` for every picture, on the
1608/// evidence that the one consumer measured wrote it. That was reading a habit
1609/// as a rule. Deferring a picture that is on screen at first paint does not
1610/// save anything -- it is needed immediately either way -- and it delays the
1611/// arrival, so the space it eventually takes is claimed later and the shift is
1612/// more visible, not less.
1613///
1614/// So the safe answer is the default and the optimisation is opted into. A
1615/// carousel is the case that proves the two cannot be one setting for the
1616/// renderer to choose: its first frame is on screen and its other frames are
1617/// not, in the same widget, at the same moment.
1618#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1619#[non_exhaustive]
1620pub enum Loading {
1621    /// Needed with the screen. Fetch it now.
1622    #[default]
1623    Eager,
1624    /// Not on screen yet. It can wait until it is near.
1625    Lazy,
1626}
1627
1628impl<'a> Image<'a> {
1629    /// A picture that carries its own proportions.
1630    #[must_use]
1631    pub const fn new(alt: &'a str) -> Self {
1632        Self {
1633            alt,
1634            caption: None,
1635            fit: Fit::Natural,
1636            intrinsic: None,
1637            loading: Loading::Eager,
1638        }
1639    }
1640
1641    /// The picture's own dimensions, so a renderer can hold its place.
1642    #[must_use]
1643    pub const fn intrinsic(mut self, width: u32, height: u32) -> Self {
1644        self.intrinsic = Some(Extent::new(width, height));
1645        self
1646    }
1647
1648    /// This picture is not on screen yet; it can arrive when it is near.
1649    #[must_use]
1650    pub const fn lazy(mut self) -> Self {
1651        self.loading = Loading::Lazy;
1652        self
1653    }
1654
1655    /// A visible line under it.
1656    #[must_use]
1657    pub const fn caption(mut self, caption: &'a str) -> Self {
1658        self.caption = Some(caption);
1659        self
1660    }
1661
1662    /// How it sits in its box.
1663    #[must_use]
1664    pub const fn fit(mut self, fit: Fit) -> Self {
1665        self.fit = fit;
1666        self
1667    }
1668
1669    /// Whether the picture adds anything for someone not looking at it.
1670    ///
1671    /// A renderer with no way to show a picture uses this to decide between
1672    /// drawing the alt text and drawing nothing at all. Both are correct and
1673    /// the difference is this flag: standing in for a decorative rule with the
1674    /// word "decoration" is worse than leaving the space empty.
1675    #[must_use]
1676    pub const fn speaks(self) -> bool {
1677        !self.alt.is_empty()
1678    }
1679}
1680
1681/// What a [`Track`]'s integers count.
1682///
1683/// `Track::fraction` never needed this -- the arithmetic is the same whatever
1684/// the numbers mean -- which is exactly how the ruler came to assume minutes
1685/// and print `00:00` over a month. A renderer drawing an axis has to write a
1686/// label, and it cannot derive the unit from the numbers.
1687///
1688/// Added 2026-08-15, after a probe put a fifteen-day span on a
1689/// thirty-one-slot track and got correct geometry under a wall clock.
1690#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1691#[non_exhaustive]
1692pub enum Unit {
1693    /// Minutes from the start of a day. A day view.
1694    #[default]
1695    Minutes,
1696    /// Whole days. A month strip, a sprint, a stretch of leave.
1697    ///
1698    /// A day-granularity axis is a *strip*, not a calendar: one line with
1699    /// spans laid along it. What it deliberately does not do is wrap into
1700    /// weeks, which is the shape that makes weekday periodicity visible and
1701    /// the one job of a month grid that a strip cannot take over. See the
1702    /// crate header.
1703    Days,
1704}
1705
1706/// A window on an axis, in whatever [`Unit`] its [`Track`] counts.
1707///
1708/// The axis a [`Track`] draws. Offsets rather than instants, because a
1709/// description carrying a `DateTime` would carry a timezone with it and the
1710/// vocabulary has no business holding one. The app knows which day or month
1711/// this is; the description says how far along it a thing sits.
1712///
1713/// `to` is exclusive and may exceed the natural period, which is how a span
1714/// running past the end is said without a second date: under
1715/// [`Unit::Minutes`], `Span::new(1320, 1560)` is 22:00 to 02:00.
1716#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1717pub struct Span {
1718    from: u16,
1719    to: u16,
1720}
1721
1722impl Span {
1723    /// Midnight to midnight, the ordinary day.
1724    pub const DAY: Self = Self { from: 0, to: 1440 };
1725
1726    /// A span, clamped to a sane one.
1727    ///
1728    /// An empty or backwards span is a caller bug that should not cost a
1729    /// renderer a division by zero, so `to` is forced at least one minute past
1730    /// `from` rather than returning an error nobody can act on. Same reasoning
1731    /// as [`Share::percent`], which clamps rather than refuses.
1732    #[must_use]
1733    pub const fn new(from: u16, to: u16) -> Self {
1734        Self {
1735            from,
1736            to: if to > from { to } else { from + 1 },
1737        }
1738    }
1739
1740    /// The first minute on the axis.
1741    #[must_use]
1742    pub const fn from(self) -> u16 {
1743        self.from
1744    }
1745
1746    /// One past the last minute on the axis.
1747    #[must_use]
1748    pub const fn to(self) -> u16 {
1749        self.to
1750    }
1751
1752    /// How much the axis covers, in its track's unit. Never zero.
1753    #[must_use]
1754    pub const fn length(self) -> u16 {
1755        self.to - self.from
1756    }
1757
1758    /// Whether an offset falls on this axis.
1759    #[must_use]
1760    pub const fn holds(self, minute: u16) -> bool {
1761        minute >= self.from && minute < self.to
1762    }
1763}
1764
1765impl Default for Span {
1766    fn default() -> Self {
1767        Self::DAY
1768    }
1769}
1770
1771/// Where a thing sits on a [`Track`], and for how long.
1772///
1773/// The one fact a list cannot carry and the whole reason this primitive exists.
1774/// A list says what order things come in; a track says a thing starts 135
1775/// minutes along and lasts 45, which is a different claim and not derivable
1776/// from the first.
1777#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1778pub struct Placement {
1779    at: u16,
1780    length: u16,
1781}
1782
1783impl Placement {
1784    /// A placement, clamped to a drawable one.
1785    ///
1786    /// Zero length becomes one for the same reason [`Span::new`] clamps: a
1787    /// zero-height thing is invisible rather than expressive, and every
1788    /// renderer would need its own guard.
1789    #[must_use]
1790    pub const fn new(at: u16, length: u16) -> Self {
1791        Self {
1792            at,
1793            length: if length == 0 { 1 } else { length },
1794        }
1795    }
1796
1797    /// Offset from the axis origin, matching [`Span`]'s.
1798    #[must_use]
1799    pub const fn at(self) -> u16 {
1800        self.at
1801    }
1802
1803    /// How long it lasts, in its track's unit. Never zero.
1804    #[must_use]
1805    pub const fn length(self) -> u16 {
1806        self.length
1807    }
1808
1809    /// One past its last minute.
1810    #[must_use]
1811    pub const fn end(self) -> u16 {
1812        self.at + self.length
1813    }
1814
1815    /// Whether two placements cover any of the same time.
1816    ///
1817    /// Geometry, and deliberately not a described field. Whether an overlap is
1818    /// a *conflict* is the app's judgment -- a meeting inside a block of free
1819    /// time overlaps and is fine -- and that judgment travels the way every
1820    /// other judgment does, as a [`Tone`] on the thing itself. What a renderer
1821    /// needs in order to lay two things side by side instead of on top of each
1822    /// other is this, and it can compute it.
1823    ///
1824    /// The alternative was a `conflicts: bool` on each entry, which is state
1825    /// that can disagree with the times beside it. Two sources for one fact is
1826    /// how a screen starts rendering a conflict badge on a thing that no longer
1827    /// conflicts.
1828    #[must_use]
1829    pub const fn overlaps(self, other: Self) -> bool {
1830        self.at < other.end() && other.at < self.end()
1831    }
1832}
1833
1834/// A time axis: things placed by when they happen, rather than flowed.
1835///
1836/// # Why this is a primitive
1837///
1838/// This crate refused to name it until 2026-08-15, on the argument that a
1839/// description expressive enough to draw a timeline is a component library
1840/// wearing a description's name. The refusal is withdrawn, and it is worth
1841/// being precise about what was wrong with it, because the reasoning it used
1842/// applies to real cases and should not be discarded with it.
1843///
1844/// What a timeline needs that a [`List`](Region::Pane) does not is **one**
1845/// thing: placement. Where a thing sits is a fact about the thing, the way a
1846/// row's primary text is, and it is not derivable from order. Everything else a
1847/// day view draws -- the labels, the gridlines, the item bodies, the tones --
1848/// is furniture this vocabulary already names. Measured against goingson's
1849/// `day-planning-render.js`, the only members it needed and could not get were
1850/// `at` and `minutes`.
1851///
1852/// So the timeline was never a component library's worth of vocabulary. It was
1853/// two integers, and the refusal was priced as though it were the whole widget.
1854/// The test that matters is not "does this shape look complicated" but "how
1855/// many members does it actually add, and are they facts or presentation".
1856/// Slot heights, gridline colour, how overlaps stack and which hour scrolls
1857/// into view on open are all presentation and all stay the renderer's, which is
1858/// why they are absent here.
1859///
1860/// # What it does not carry
1861///
1862/// No pixel measure, no scroll offset, no drag affordance. A renderer draws the
1863/// span at whatever density its host uses; `makeover-geometry` owns that the
1864/// way it owns everything else measured in pixels.
1865#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1866pub struct Track {
1867    /// The window the axis covers.
1868    pub span: Span,
1869    /// The granularity a thing can be placed on, in minutes.
1870    ///
1871    /// goingson's day view is 15, giving 96 slots across a day. A renderer uses
1872    /// it to decide where gridlines fall and what a drop lands on; it does not
1873    /// constrain [`Placement`], because data arriving from a calendar does not
1874    /// respect anyone's grid.
1875    pub slot: u16,
1876    /// How often the axis labels itself, in its own unit.
1877    ///
1878    /// 60 gives an hourly ruler over a 15-minute grid, which is the common
1879    /// shape and the reason this is separate from `slot`. Zero means an
1880    /// unlabelled axis.
1881    pub tick: u16,
1882    /// What `span`, `slot`, `tick` and every [`Placement`] on it count.
1883    ///
1884    /// The one field here a renderer cannot derive, and the reason it exists:
1885    /// [`fraction`](Self::fraction) is unit-agnostic, so a day-granularity
1886    /// track produced correct geometry under an hours-and-minutes ruler until
1887    /// this was added. Geometry never needed it; a label always did.
1888    pub unit: Unit,
1889}
1890
1891impl Track {
1892    /// An ordinary day: midnight to midnight, quarter-hour slots, hourly ticks.
1893    pub const DAY: Self = Self {
1894        span: Span::DAY,
1895        slot: 15,
1896        tick: 60,
1897        unit: Unit::Minutes,
1898    };
1899
1900    /// A track over `span`, with the day's usual granularity.
1901    #[must_use]
1902    pub const fn over(span: Span) -> Self {
1903        Self {
1904            span,
1905            slot: 15,
1906            tick: 60,
1907            unit: Unit::Minutes,
1908        }
1909    }
1910
1911    /// A strip of whole days: one slot a day, a label a week.
1912    ///
1913    /// The shape a stretch of leave or a sprint is drawn on. Not a calendar --
1914    /// it does not wrap into weeks, and the crate header says why that
1915    /// distinction is the whole of what a month grid still has over this.
1916    #[must_use]
1917    pub const fn days(span: Span) -> Self {
1918        Self {
1919            span,
1920            slot: 1,
1921            tick: 7,
1922            unit: Unit::Days,
1923        }
1924    }
1925
1926    /// How many slots the axis holds.
1927    ///
1928    /// Rounded up, so a span that does not divide evenly by `slot` still has a
1929    /// slot covering its tail rather than dropping it. Never zero: `slot` of 0
1930    /// reads as one slot spanning the whole axis rather than a division by
1931    /// zero, since a renderer asking this question has already committed to
1932    /// drawing something.
1933    #[must_use]
1934    pub const fn slots(self) -> u16 {
1935        if self.slot == 0 {
1936            1
1937        } else {
1938            self.span.length().div_ceil(self.slot)
1939        }
1940    }
1941
1942    /// Where a placement sits on the axis, as a fraction from 0.0 to 1.0.
1943    ///
1944    /// The one calculation every renderer would otherwise write itself, and the
1945    /// place the three would drift apart. Clamped, so a placement outside the
1946    /// span draws at the edge rather than off it -- an event running past
1947    /// midnight is a real thing and truncating it is better than either
1948    /// panicking or drawing it somewhere impossible.
1949    #[must_use]
1950    pub fn fraction(self, minute: u16) -> f32 {
1951        let span = f32::from(self.span.length());
1952        let offset = f32::from(minute.saturating_sub(self.span.from()));
1953        (offset / span).clamp(0.0, 1.0)
1954    }
1955}
1956
1957impl Default for Track {
1958    fn default() -> Self {
1959        Self::DAY
1960    }
1961}
1962
1963#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1964pub struct Act<'a> {
1965    /// What the control says.
1966    pub label: &'a str,
1967    /// The key that reaches it where a host has keys.
1968    ///
1969    /// The one member written for a terminal before there was one. A webview
1970    /// hangs it off `accesskey` or ignores it; a terminal has nothing else to
1971    /// offer, so this is the whole of how a control is reached there.
1972    pub key: Option<&'a str>,
1973    /// What pressing it means. [`Tone::Danger`] is the destructive one.
1974    pub tone: Tone,
1975    /// Disabled, or nothing said.
1976    ///
1977    /// [`State::Disabled`] is what changes what a renderer may do: see
1978    /// [`State::suppresses_interaction`], which is what says a disabled control
1979    /// is drawn and not reachable. It has been the only member since 0.19.0,
1980    /// and a control's focus is not sayable here at all — see the crate header,
1981    /// "Reach, focus and the focus ring".
1982    pub state: Option<State>,
1983}
1984
1985impl<'a> Act<'a> {
1986    /// An ordinary control, reachable, with no key.
1987    #[must_use]
1988    pub const fn new(label: &'a str) -> Self {
1989        Self {
1990            label,
1991            key: None,
1992            tone: Tone::Neutral,
1993            state: None,
1994        }
1995    }
1996
1997    /// The key that reaches it.
1998    #[must_use]
1999    pub const fn key(mut self, key: &'a str) -> Self {
2000        self.key = Some(key);
2001        self
2002    }
2003
2004    /// What pressing it means.
2005    #[must_use]
2006    pub const fn tone(mut self, tone: Tone) -> Self {
2007        self.tone = tone;
2008        self
2009    }
2010
2011    /// Focus, or disabled.
2012    #[must_use]
2013    pub const fn state(mut self, state: State) -> Self {
2014        self.state = Some(state);
2015        self
2016    }
2017
2018    /// Whether the control is drawn and does not answer.
2019    #[must_use]
2020    pub fn disabled(&self) -> bool {
2021        self.state.is_some_and(State::suppresses_interaction)
2022    }
2023}
2024
2025/// A named part of a screen.
2026///
2027/// The thing `makeover-geometry` deliberately does not name: it names the space
2028/// *between* things by relationship, and nothing named the things. Six named
2029/// members, taken from what the two webview apps actually use, plus
2030/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
2031/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
2032/// this layer is absent rather than divergent, which makes it the cheapest of
2033/// the schemas to add and the easiest to over-build.
2034///
2035/// `#[non_exhaustive]` arrives with [`Region::Widget`], the pairing [`RowPart`]
2036/// made at 0.9.0 and [`Readiness`] at 0.12.0, and for the same reason: the
2037/// member after this one should not be a lockstep event across three renderers.
2038#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2039#[non_exhaustive]
2040pub enum Region<'a> {
2041    /// A full-width strip with a title slot and an actions cluster, either of
2042    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
2043    /// `.header` and `.detail-header` are all this, differing only in which
2044    /// slots they fill.
2045    Band,
2046    /// A persistent column beside the content, holding navigation.
2047    Sidebar,
2048    /// A region of content with its own scroll.
2049    Pane,
2050    /// Things that belong together, and nothing else.
2051    ///
2052    /// The block [`Heading::Section`] has been naming since 0.2.0 without the
2053    /// vocabulary being able to contain it. A section heading is a leaf sitting
2054    /// *beside* the things it names, so nothing said where a section started or
2055    /// ended and a renderer learned one had ended only because the next heading
2056    /// arrived.
2057    ///
2058    /// # The measurement
2059    ///
2060    /// 41 [`Heading::Section`] sites across the ten screens described through
2061    /// the router, not one of them contained. audiofiles' settings screen is the
2062    /// clearest: one pane holding a heading, a field, a heading, two toggles, a
2063    /// heading, a toggle and a heading, which is four sections and no
2064    /// containers. Under the hand-written CSS the ports are replacing the same
2065    /// block is spelled `.settings-section` in goingson, `.form-section` and
2066    /// `.content-section` in the MNW server, `.help-section` in Balanced
2067    /// Breakfast: three apps, four names, one shape.
2068    ///
2069    /// # Why the existing members were the wrong answer
2070    ///
2071    /// [`Pane`](Self::Pane) is what apps reached for, and it is 28 of the 45
2072    /// regions in the described screens. It claims a scroll of its own and
2073    /// [`Depth::Well`], so four settings groups inside a pane are four wells
2074    /// inside a well and four scroll contexts. Neither claim is true of a group.
2075    ///
2076    /// [`Widget`](Self::Widget) is wrong from the other side. Its own docs say a
2077    /// widget is never how a primitive gets added by the back door, and a run of
2078    /// related controls under a heading is furniture any app would have, which
2079    /// is the generic-against-bespoke bar a primitive has to clear.
2080    ///
2081    /// # What it does not carry
2082    ///
2083    /// **A heading.** A group usually has one and it is an ordinary node in the
2084    /// body, the way it already was. A group of related toggles with no heading
2085    /// is a real thing and a mandatory slot would forbid it.
2086    ///
2087    /// **A depth.** [`Depth::Flat`], on [`Bespoke`](Self::Bespoke)'s reasoning:
2088    /// it inherits, and an app that wants its group in a well puts it in a
2089    /// [`Pane`](Self::Pane), which composes rather than adding a knob here.
2090    ///
2091    /// **A colour.** Distinguishing sibling groups by colour is the thing this
2092    /// member was asked for and it is deliberately not stated here. The
2093    /// description says these things belong together; which of the theme's
2094    /// categorical colours a renderer reaches for, and whether it reaches for
2095    /// one at all, is derived from sibling order at the renderer. A terminal
2096    /// that tints nothing and separates with a rule is honouring this.
2097    Group,
2098    /// Two panes side by side, where the left chooses what the right shows.
2099    Split,
2100    /// Peer regions across, all of them equals.
2101    ///
2102    /// A kanban board's columns, and the shape [`Split`](Self::Split) is not:
2103    /// a split's two panes stand in a master-detail relationship, where the
2104    /// left chooses what the right shows. These choose nothing about each
2105    /// other. Each is a whole region and the set is the arrangement.
2106    ///
2107    /// # What it does not carry
2108    ///
2109    /// **How many.** The children say, and a count here would be a second
2110    /// source for something the description already states by containing them.
2111    ///
2112    /// **How wide.** Peers are equal by definition, so there is no [`Share`] to
2113    /// state. A board whose columns wanted different widths would be a
2114    /// different member, and no app has one.
2115    ///
2116    /// **What happens when there is no room.** Scroll across, wrap, or collapse
2117    /// to one column at a time: all three are right on some host, none is
2118    /// derivable from the description, and every one of them is presentation.
2119    /// A terminal that stacks them vertically is honouring this, not degrading
2120    /// it.
2121    ///
2122    /// # Why it is not an `Arrangement`
2123    ///
2124    /// [`Arrangement`] is the page's shape, and a board is usually a region
2125    /// *inside* a page that also has a band over it. Naming it here composes;
2126    /// naming it there would make a screen either a board or a list-detail and
2127    /// never a band above a board. It also keeps [`Arrangement::share`]
2128    /// meaningful, which a peer arrangement has no answer for.
2129    Columns,
2130    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
2131    TabGroup,
2132    /// Content over a scrim, taking input until dismissed.
2133    Modal,
2134    /// A region this crate names the *place* of and nothing else. The app owns
2135    /// what goes in it.
2136    ///
2137    /// The escape hatch, and the thing that keeps the description honest about
2138    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
2139    /// paint interaction over the timeline are not describable here and are not
2140    /// going to become describable: a description expressive enough to produce
2141    /// a timeline is a widget library wearing a description's name.
2142    ///
2143    /// But a screen containing one still has to be a screen. Without this
2144    /// member the description covers only the boring screens, and the four that
2145    /// make goingson worth using would need a second, undescribed path beside
2146    /// the router. Two paths is how the vocabulary starts drifting from the app
2147    /// again, which is the exact failure this crate exists to end.
2148    ///
2149    /// So the description says "a thing called `day-plan` goes here" and stops.
2150    /// The name is opaque: this crate never interprets it, and no renderer is
2151    /// expected to know what it means beyond handing the space over.
2152    Bespoke {
2153        /// What the app calls it. Never interpreted here.
2154        name: &'a str,
2155    },
2156    /// A named assembly of things the vocabulary already says.
2157    ///
2158    /// The third tier, between a primitive and [`Bespoke`](Self::Bespoke).
2159    /// Stated by Max 2026-08-12 answering the carousel: "something in between a
2160    /// primitive and a bespoke interface, like a widget, which is just an
2161    /// assembly of primitives." Full note: wiki `widget-tier`.
2162    ///
2163    /// # What separates it from the two members either side
2164    ///
2165    /// A primitive is a thing every renderer draws from scratch, and the test
2166    /// it has to pass is that every host has an honest answer. A carousel fails
2167    /// that test — a terminal has no carousel — which is the same refusal
2168    /// `Node::Html` got and is why the carousel sat unsayable for months.
2169    ///
2170    /// [`Bespoke`](Self::Bespoke) fails it from the other side. Bespoke is for
2171    /// what one app owns and nobody will build twice, and it carries *no*
2172    /// contents: the description names the place and stops. A carousel is
2173    /// furniture any app would have, and every part of it — an ordered set of
2174    /// frames, a position, prev and next, a strip of position indicators — is
2175    /// already sayable. Only the assembly had no name.
2176    ///
2177    /// So this member is the pair the other two are not: a name **and**
2178    /// contents. The contents are the assembly, in the region's own body, said
2179    /// in members that already exist.
2180    ///
2181    /// # Why the name does not have to be understood
2182    ///
2183    /// A renderer that recognises the name draws it the way its host does it: a
2184    /// carousel in a webview, a pager with a count in a terminal, a selector in
2185    /// egui. A renderer that does not recognise it walks the body, which is
2186    /// primitives all the way down and which it can already draw.
2187    ///
2188    /// That is what lets the widget set be **open** without every renderer
2189    /// knowing every widget. An unrecognised widget degrades to its assembly
2190    /// instead of failing, so a second or third party can name one without
2191    /// three renderers releasing in lockstep to accept it. Contrast
2192    /// [`Bespoke`](Self::Bespoke), which no renderer can degrade: there is
2193    /// nothing under it to fall back to.
2194    ///
2195    /// # What it does not do
2196    ///
2197    /// A widget is an assembly of things the vocabulary *already* says, so it
2198    /// buys no expressive power. Anything needing a member the vocabulary does
2199    /// not have is a finding about the vocabulary, and the answer to a finding
2200    /// is to add the member. A widget is never the way a primitive gets added
2201    /// by the back door.
2202    ///
2203    /// This used to say "it does not make a timeline describable, and the
2204    /// refusal in the crate header stands unchanged". The timeline is
2205    /// describable as of 2026-08-15 -- see [`Track`] -- and it got there the
2206    /// way the paragraph above says it should have: by adding the two members
2207    /// that were missing, not by dressing the screen up as an assembly.
2208    Widget {
2209        /// What the assembly is called. This crate never interprets it, and a
2210        /// renderer is free not to know it.
2211        name: &'a str,
2212    },
2213}
2214
2215impl<'a> Region<'a> {
2216    /// How the region sits on what is behind it.
2217    #[must_use]
2218    pub const fn depth(self) -> Depth {
2219        match self {
2220            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
2221            // Flat, and it inherits. A group says its contents belong together
2222            // and says nothing about the surface they sit on, so a group in a
2223            // pane is in a well and a group on the page is on the page. An app
2224            // wanting one lifted puts it in a `Pane`.
2225            Self::Group => Depth::Flat,
2226            // Flat, and it is the container rather than the columns. Each
2227            // column is its own region and brings its own depth; a well here
2228            // would put a second edge around a row of wells.
2229            Self::Columns => Depth::Flat,
2230            // A pane is looked into, the same as a table body or a tag tree.
2231            Self::Pane => Depth::Well,
2232            Self::Modal => Depth::Raised,
2233            // Flat because it inherits: a bespoke region takes the depth of
2234            // whatever frames it. An app that wants its timeline in a well puts
2235            // it in a `Pane`, which composes rather than adding a knob here.
2236            //
2237            // A widget inherits for the same reason and it matters more here,
2238            // because a widget is drawn by whichever renderer recognises it. A
2239            // depth set here would be this crate deciding that a carousel is
2240            // raised on every host, which is the kind of value the deferral
2241            // rule exists to refuse.
2242            Self::Bespoke { .. } | Self::Widget { .. } => Depth::Flat,
2243        }
2244    }
2245
2246    /// Whether this crate can say anything about the region's contents.
2247    ///
2248    /// A renderer walks the description and hands every region it understands
2249    /// to the right drawing code. This is how it tells the two apart, and the
2250    /// reason it is a method rather than a `matches!` at each renderer: there
2251    /// is exactly one opaque member and there should stay exactly one.
2252    ///
2253    /// [`Widget`](Self::Widget) is described, and that is the whole of what
2254    /// separates it from [`Bespoke`](Self::Bespoke) here. Both carry a name
2255    /// this crate never interprets; only one of them carries contents under it.
2256    /// A renderer that does not recognise a widget's name still walks its body,
2257    /// so there is nothing for it to hand over and nothing it cannot draw.
2258    #[must_use]
2259    pub const fn described(self) -> bool {
2260        !matches!(self, Self::Bespoke { .. })
2261    }
2262
2263    /// The name an app gave this region, if it gave one.
2264    ///
2265    /// [`Bespoke`](Self::Bespoke) and [`Widget`](Self::Widget) are the two
2266    /// members that carry a name, for two different purposes: one says what the
2267    /// app will fill the space with, the other says what the assembly under it
2268    /// is called. A renderer dispatching on either wants the string without
2269    /// caring which member it came from, and writing that `matches!` at each
2270    /// renderer is how the two drift apart.
2271    #[must_use]
2272    pub const fn name(self) -> Option<&'a str> {
2273        match self {
2274            Self::Bespoke { name } | Self::Widget { name } => Some(name),
2275            // Spelled out rather than a wildcard, so a member added later has
2276            // to answer whether it carries a name instead of inheriting `None`
2277            // by sitting under a `_`.
2278            Self::Band
2279            | Self::Sidebar
2280            | Self::Pane
2281            | Self::Group
2282            | Self::Split
2283            | Self::Columns
2284            | Self::TabGroup
2285            | Self::Modal => None,
2286        }
2287    }
2288}
2289
2290/// How many of a region's children are visible at once.
2291///
2292/// `4dcd241b`. Three findings turned out to be one sentence the vocabulary
2293/// could not say: *this region holds several children and shows some of them,
2294/// and the reader can change which.* [`Region::TabGroup`] existed with nothing
2295/// saying which tab was open, a carousel had nothing saying which frame was up,
2296/// and a disclosure had nothing saying whether its one child was showing at all.
2297///
2298/// Because the fact lived nowhere, a renderer had two moves: hardcode a widget
2299/// name, or draw every child. That is what put per-widget code in renderers, and
2300/// it was the missing member rather than the widget tier that put it there.
2301///
2302/// # What is here and what is not
2303///
2304/// The *kind*, and only the kind. Which child is currently up is the current
2305/// answer, and a layer that defers every address does not hold the current
2306/// answer either — the split [`Selector`] already makes, where this crate says
2307/// what kind of chooser a thing is and the router says which option is picked.
2308/// So a holder of regions carries the index and the per-child label beside this.
2309///
2310/// # What a renderer does with it
2311///
2312/// Derives its chrome, once, for every widget rather than per name:
2313///
2314/// - Children carrying labels get a strip of the labels, the current one marked.
2315/// - Children carrying none get previous, position, next.
2316/// - [`AtMostOne`](Self::AtMostOne) over one child gets a summary line that
2317///   opens.
2318///
2319/// The name on [`Region::Widget`] survives as app vocabulary, for a renderer
2320/// that wants to do something *special* with one, which is what it should have
2321/// been from the start.
2322///
2323/// Degradation runs the way it already did: a renderer ignoring this draws every
2324/// child, which is more content rather than less.
2325#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2326#[non_exhaustive]
2327pub enum Showing {
2328    /// Every child, in order. What every region did before this existed.
2329    #[default]
2330    All,
2331    /// Exactly one. A carousel, a tab group.
2332    One,
2333    /// One, or none. A disclosure, which is closed until it is opened.
2334    AtMostOne,
2335}
2336
2337impl Showing {
2338    /// Whether the reader can change which child is up.
2339    ///
2340    /// The question every renderer's region arm asks before deriving any
2341    /// chrome, and a method rather than a `matches!` at each renderer for
2342    /// [`Region::name`]'s reason: three renderers writing the same comparison is
2343    /// how they come to disagree about a member added later.
2344    #[must_use]
2345    pub const fn selective(self) -> bool {
2346        !matches!(self, Self::All)
2347    }
2348
2349    /// Whether showing nothing is a legal state.
2350    ///
2351    /// True only for [`AtMostOne`](Self::AtMostOne). A renderer needs this to
2352    /// know whether its control closes as well as moves: a carousel's row moves
2353    /// between frames and never reaches empty, and a disclosure's summary line
2354    /// is the same control wearing its closed state.
2355    #[must_use]
2356    pub const fn dismissible(self) -> bool {
2357        matches!(self, Self::AtMostOne)
2358    }
2359}
2360
2361/// A window onto a sequence: where it starts, how much it covers, and how long
2362/// the sequence is when that is known.
2363///
2364/// The mechanism under two things the vocabulary deliberately keeps apart. A
2365/// carousel is a window of one frame over children that are all present; a
2366/// paged list is a window of a page over rows most of which were never fetched.
2367/// Those are different facts and they stay different types — [`Showing`] says
2368/// which child is up, [`Paging`] says where a reader is in a query — but the
2369/// arithmetic underneath is one piece of code, so a terminal and a browser
2370/// cannot come to disagree about which frame is last.
2371///
2372/// # Why `of` is optional and `count` is not
2373///
2374/// `count` is what is on screen and is therefore always known. `of` is the
2375/// length of the thing being windowed, and a host that cannot count says so by
2376/// leaving it empty **for the life of the screen**. It is never "not counted
2377/// yet": see "First paint is final paint" in the crate header. A total that
2378/// turns up on a later pass widens the text that prints it.
2379///
2380/// # Clamping
2381///
2382/// Every derivation clamps rather than refusing, and a zero `count` answers
2383/// `None` rather than dividing. A window past the end is a bug in the host, and
2384/// a renderer that answered it by drawing nothing would report a region that
2385/// vanished, which is the hardest kind of bug to find from what is on screen.
2386/// [`Share::percent`] clamps for the same reason.
2387#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2388pub struct Window {
2389    /// The index into the sequence where the window starts.
2390    pub from: usize,
2391    /// How many the window covers. One, for a carousel.
2392    pub count: usize,
2393    /// How long the sequence is, when the host can say.
2394    pub of: Option<usize>,
2395}
2396
2397impl Window {
2398    /// A window of `count`, starting at `from`, over a sequence of unknown
2399    /// length.
2400    #[must_use]
2401    pub const fn new(from: usize, count: usize) -> Self {
2402        Self {
2403            from,
2404            count,
2405            of: None,
2406        }
2407    }
2408
2409    /// How long the sequence is.
2410    #[must_use]
2411    pub const fn of(mut self, of: usize) -> Self {
2412        self.of = Some(of);
2413        self
2414    }
2415
2416    /// One item of a sequence whose length is known. A carousel frame.
2417    #[must_use]
2418    pub const fn frame(at: usize, of: usize) -> Self {
2419        Self {
2420            from: at,
2421            count: 1,
2422            of: Some(of),
2423        }
2424    }
2425
2426    /// Which window this is, counting from zero.
2427    ///
2428    /// `None` when `count` is zero, which is the only input with no answer
2429    /// rather than a clamped one.
2430    #[must_use]
2431    pub const fn index(self) -> Option<usize> {
2432        if self.count == 0 {
2433            return None;
2434        }
2435        Some(self.from / self.count)
2436    }
2437
2438    /// How many windows the sequence holds.
2439    ///
2440    /// `None` unless both the length and a non-zero `count` are known. A
2441    /// partial answer here would be a renderer drawing "of 0".
2442    #[must_use]
2443    pub const fn windows(self) -> Option<usize> {
2444        match self.of {
2445            Some(of) if self.count > 0 => Some(of.div_ceil(self.count)),
2446            _ => None,
2447        }
2448    }
2449
2450    /// Whether anything sits before this window.
2451    #[must_use]
2452    pub const fn has_before(self) -> bool {
2453        self.from > 0
2454    }
2455
2456    /// How many sit after this window, when the length is known.
2457    ///
2458    /// Here rather than in each renderer for [`Showing::selective`]'s reason:
2459    /// three of them writing the same subtraction is how they come to disagree,
2460    /// and this one has an underflow in it for whoever writes it fourth.
2461    #[must_use]
2462    pub const fn after(self) -> Option<usize> {
2463        match self.of {
2464            Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
2465            None => None,
2466        }
2467    }
2468
2469    /// Whether anything sits after it.
2470    ///
2471    /// `true` when the length is unknown: a host that cannot count cannot rule
2472    /// out more, and offering a way forward that turns out to be empty is the
2473    /// cheaper of the two mistakes.
2474    #[must_use]
2475    pub const fn has_after(self) -> bool {
2476        match self.of {
2477            Some(of) => self.from.saturating_add(self.count) < of,
2478            None => true,
2479        }
2480    }
2481
2482    /// The window with `from` brought inside the sequence.
2483    ///
2484    /// A no-op when the length is unknown, since there is nothing to clamp
2485    /// against.
2486    #[must_use]
2487    pub const fn clamped(mut self) -> Self {
2488        if let Some(of) = self.of
2489            && self.from >= of
2490        {
2491            // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
2492            // window would otherwise clamp onto the end rather than inside it.
2493            let step = if self.count == 0 { 1 } else { self.count };
2494            self.from = of.saturating_sub(step);
2495        }
2496        self
2497    }
2498}
2499
2500/// Where a reader is in a set that arrived in parts.
2501///
2502/// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
2503/// window at the top level on purpose, because the intent differs and a call
2504/// site should say which one it means, while the arithmetic below is shared so
2505/// the two cannot drift apart.
2506///
2507/// # The two idioms, and which one a renderer may draw
2508///
2509/// Load-more and numbered pages are both this type. Which is honest is
2510/// [`paged`](Self::paged): a set whose page size is known can be drawn as
2511/// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
2512/// forward. Saying it here rather than letting each renderer guess is the point
2513/// — three renderers inferring it from the numbers is how they come to disagree.
2514///
2515/// # What it does not carry
2516///
2517/// No addresses. `makeover-layout` cannot name an action, and the way to ask for
2518/// the next part is the host's: `quasi_router` pairs this with the addresses the
2519/// same way `Row` pairs its parts with `Row::activate`. That split is the reason
2520/// this type is reusable by a carousel, which has nothing to ask.
2521#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2522pub struct Paging {
2523    /// The window onto the set.
2524    pub window: Window,
2525    /// Whether the parts are a fixed size, and so whether pages are countable.
2526    ///
2527    /// `false` for load-more, where the window simply grew and "page 2" would
2528    /// name nothing.
2529    pub paged: bool,
2530}
2531
2532impl Paging {
2533    /// A page of `per`, starting at `from`.
2534    #[must_use]
2535    pub const fn pages(from: usize, per: usize) -> Self {
2536        Self {
2537            window: Window::new(from, per),
2538            paged: true,
2539        }
2540    }
2541
2542    /// The first `shown`, with more behind them.
2543    ///
2544    /// The load-more shape: the window starts at the beginning and grows, so
2545    /// there is no page to number.
2546    #[must_use]
2547    pub const fn more(shown: usize) -> Self {
2548        Self {
2549            window: Window::new(0, shown),
2550            paged: false,
2551        }
2552    }
2553
2554    /// How many there are altogether.
2555    ///
2556    /// Left unsaid by a host that cannot count, and left unsaid **for good**:
2557    /// a total arriving later widens whatever prints it. See "First paint is
2558    /// final paint" in the crate header.
2559    #[must_use]
2560    pub const fn of(mut self, of: usize) -> Self {
2561        self.window = self.window.of(of);
2562        self
2563    }
2564
2565    /// Which page this is, counting from one, when pages are countable.
2566    ///
2567    /// One-based because it is read aloud. [`Window::index`] is the zero-based
2568    /// form for anyone indexing with it.
2569    #[must_use]
2570    pub const fn page(self) -> Option<usize> {
2571        if !self.paged {
2572            return None;
2573        }
2574        match self.window.index() {
2575            Some(index) => Some(index + 1),
2576            None => None,
2577        }
2578    }
2579
2580    /// How many pages there are, when that is countable.
2581    #[must_use]
2582    pub const fn pages_total(self) -> Option<usize> {
2583        if !self.paged {
2584            return None;
2585        }
2586        self.window.windows()
2587    }
2588
2589    /// How many are on screen.
2590    #[must_use]
2591    pub const fn shown(self) -> usize {
2592        self.window.count
2593    }
2594
2595    /// How many there are, when the host counted.
2596    #[must_use]
2597    pub const fn total(self) -> Option<usize> {
2598        self.window.of
2599    }
2600
2601    /// How many are not shown yet, when the host counted.
2602    ///
2603    /// The figure a load-more control puts in its label. `None` is the honest
2604    /// and common case: a set that cannot say how many more there are still has
2605    /// a way to ask for them.
2606    #[must_use]
2607    pub const fn remaining(self) -> Option<usize> {
2608        self.window.after()
2609    }
2610
2611    /// Whether there is anything further on.
2612    #[must_use]
2613    pub const fn has_more(self) -> bool {
2614        self.window.has_after()
2615    }
2616
2617    /// Whether there is anything back the other way.
2618    #[must_use]
2619    pub const fn has_previous(self) -> bool {
2620        self.window.has_before()
2621    }
2622}
2623
2624/// How much of the width an arrangement's first region takes.
2625///
2626/// `e0fd485e`. Nothing said how much room a region got, so every renderer
2627/// invented its own number and two hosts showing one screen disagreed about
2628/// its proportions. A webview never noticed, because the stylesheet answered
2629/// once for every consumer; a terminal has no stylesheet to inherit from, so
2630/// `quasi-tui` picked 24 columns for a sidebar and 40% for a list pane and
2631/// neither had anything behind it.
2632///
2633/// # A proportion, never a unit
2634///
2635/// Held as a percentage, and that is the only form it comes in. A description
2636/// carrying columns would be describing a terminal and one carrying pixels a
2637/// webview, and the whole point is that both honour the same fact: a terminal
2638/// resolves it against a column count, a webview writes it into a grid, and
2639/// neither has to know what the other did.
2640///
2641/// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
2642/// guess. Geometry is scales that answer the same for every screen and takes
2643/// no input that would let a sidebar screen differ from a list-detail one.
2644///
2645/// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
2646#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
2647pub struct Share(u8);
2648
2649impl Share {
2650    /// What a sidebar takes, when nobody says otherwise.
2651    ///
2652    /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
2653    /// 96-column terminal and about a fifth of a wide one; a quarter is that
2654    /// number said in the form a webview can honour too.
2655    pub const SIDEBAR: Self = Self(25);
2656
2657    /// What the list side of a list-detail takes, when nobody says otherwise.
2658    ///
2659    /// `quasi-tui`'s 40%, which was already a proportion and is the one number
2660    /// this member did not have to invent.
2661    pub const LIST: Self = Self(40);
2662
2663    /// A share of the width, as a percentage.
2664    ///
2665    /// Clamped to 5..=95 rather than refused. A description that asked for a
2666    /// region of nothing is a bug in the app, and a renderer drawing a region
2667    /// zero cells wide reports it as a region that vanished, which is the
2668    /// hardest kind of bug to find from what is on the screen.
2669    #[must_use]
2670    pub const fn percent(percent: u8) -> Self {
2671        Self(if percent < 5 {
2672            5
2673        } else if percent > 95 {
2674            95
2675        } else {
2676            percent
2677        })
2678    }
2679
2680    /// The share as a percentage.
2681    #[must_use]
2682    pub const fn as_percent(self) -> u8 {
2683        self.0
2684    }
2685
2686    /// This share of a width, rounded to the nearest whole unit.
2687    ///
2688    /// What a terminal calls to turn the proportion into columns. At least one,
2689    /// because a region the description named should be visible: a screen
2690    /// 3 columns wide is unusable either way, and a sidebar that is there is a
2691    /// truer picture of the description than a sidebar that is not.
2692    #[must_use]
2693    pub const fn of(self, whole: u16) -> u16 {
2694        let taken = (whole as u32 * self.0 as u32).div_ceil(100);
2695        if taken == 0 { 1 } else { taken as u16 }
2696    }
2697}
2698
2699/// How a screen is laid out.
2700///
2701/// Two, and the second is not a variant of the first. goingson is list-detail,
2702/// Balanced Breakfast is sidebar plus content, and neither app has a third.
2703/// The tab group is a modifier rather than a member, because goingson uses it
2704/// *inside* the same content region rather than instead of one.
2705///
2706/// This exists at all because the router has to be able to express a screen
2707/// rather than only a control. Discovering the arrangement layer missing after
2708/// the renderers exist is a redesign; naming two now is a morning.
2709///
2710/// # Why the share rides here
2711///
2712/// `e0fd485e`. A share is per-arrangement: how much a sidebar takes and how
2713/// much a list side takes are different questions, and this enum is the only
2714/// thing that knows which one is being asked. Geometry would have had to invent
2715/// a channel to be told.
2716///
2717/// [`list_detail`](Self::list_detail) and
2718/// [`sidebar_content`](Self::sidebar_content) build these with the default
2719/// shares, so a screen that has no opinion does not have to have one.
2720#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2721pub enum Arrangement {
2722    /// A list that chooses what the detail beside it shows.
2723    ListDetail {
2724        /// Whether the detail side is a [`Region::TabGroup`].
2725        tabbed: bool,
2726        /// How much of the width the list side takes.
2727        share: Share,
2728    },
2729    /// Navigation down the side, content filling the rest.
2730    SidebarContent {
2731        /// How much of the width the sidebar takes.
2732        share: Share,
2733    },
2734}
2735
2736impl Arrangement {
2737    /// A list and a detail beside it, at the default share.
2738    #[must_use]
2739    pub const fn list_detail(tabbed: bool) -> Self {
2740        Self::ListDetail {
2741            tabbed,
2742            share: Share::LIST,
2743        }
2744    }
2745
2746    /// A sidebar and content beside it, at the default share.
2747    #[must_use]
2748    pub const fn sidebar_content() -> Self {
2749        Self::SidebarContent {
2750            share: Share::SIDEBAR,
2751        }
2752    }
2753
2754    /// How much of the width the first region takes.
2755    #[must_use]
2756    pub const fn share(self) -> Share {
2757        match self {
2758            Self::ListDetail { share, .. } | Self::SidebarContent { share } => share,
2759        }
2760    }
2761
2762    /// The same arrangement, at this share.
2763    #[must_use]
2764    pub const fn with_share(self, share: Share) -> Self {
2765        match self {
2766            Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
2767            Self::SidebarContent { .. } => Self::SidebarContent { share },
2768        }
2769    }
2770}
2771
2772/// How wide the content of a whole screen runs.
2773///
2774/// `0eccff0d`, and [`Share`]'s sibling one level up: that one says how a
2775/// screen's width is divided between regions, this says how much of the window
2776/// the screen uses in the first place. Both are the description's, which is
2777/// what answering the two together settled.
2778///
2779/// Measured in the MNW server, where 69 of 72 templates carry exactly one of
2780/// three mutually exclusive classes and the choice is per screen. GoingsOn
2781/// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
2782/// token for it, so three apps were solving one thing by hand.
2783///
2784/// # Named for the measure, not for MNW's classes
2785///
2786/// A renderer that is not a browser has to answer this too, and `padded-page`
2787/// tells a terminal nothing. The three say how wide the text runs, which is a
2788/// question every renderer can answer: a webview with a `max-width`, a terminal
2789/// with gutters, an immediate-mode frame with its own width.
2790///
2791/// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
2792/// the measurement found three, and a fourth arriving should not be a lockstep
2793/// release across nine repos.
2794#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2795#[non_exhaustive]
2796pub enum Measure {
2797    /// The whole width, with gutters. The default, and 53 of the 69.
2798    ///
2799    /// What a dashboard, a table and a settings screen want: the content is
2800    /// wide because the content *is* wide, and constraining it would waste the
2801    /// window.
2802    #[default]
2803    Wide,
2804    /// Capped at a comfortable page width, centred. 13 of the 69.
2805    ///
2806    /// A form, a sign-in, a purchase. Content that does not get better by
2807    /// getting wider, but is not prose either.
2808    Contained,
2809    /// Capped at a line length that reads well. 3 of the 69.
2810    ///
2811    /// Prose. The narrowest of the three, and the one with a reason outside
2812    /// taste: a line of text past roughly 75 characters costs the reader the
2813    /// return sweep.
2814    Reading,
2815}
2816
2817impl Measure {
2818    /// A stable name, for a renderer that needs to spell it.
2819    ///
2820    /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
2821    /// renderers spelling one enum is three chances to spell it differently.
2822    #[must_use]
2823    pub const fn as_str(self) -> &'static str {
2824        match self {
2825            Self::Wide => "wide",
2826            Self::Contained => "contained",
2827            Self::Reading => "reading",
2828        }
2829    }
2830}
2831
2832/// What kind of value a form field takes.
2833///
2834/// The union of the two vocabularies that diverged, which is what triggered
2835/// this crate. They have since converged on their own: both apps now have a
2836/// `renderFormField` emitting the same anatomy, and what is left differing is
2837/// the kind set, the error shape, and whether the return is a string or a node.
2838///
2839/// Validation is deliberately absent. Neither app has a shared story (goingson
2840/// validates after collecting the form data, with per-field transform hooks;
2841/// Balanced Breakfast has `required` and nothing else), and a schema that
2842/// describes fields but not constraints acquires a constraint layer per app,
2843/// which is exactly how the current divergence started. Naming it absent is a
2844/// decision; leaving it unmentioned would not be.
2845/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
2846/// the set keeps growing, so growth must not be a lockstep event. Email, Url
2847/// and Tel arriving in 0.5.0 is the second growth in two releases.
2848#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2849#[non_exhaustive]
2850pub enum FieldKind {
2851    /// A single line of text.
2852    Text,
2853    /// A single line of text that must never be echoed, logged or round-tripped
2854    /// through anything that might persist it.
2855    Secret,
2856    /// A number.
2857    Number,
2858    /// An email address.
2859    ///
2860    /// Distinct from [`Text`](Self::Text) because the distinction is not
2861    /// decoration: a webview renderer emits `type="email"`, which on a touch
2862    /// device changes the keyboard that appears and turns on the platform's own
2863    /// validation. goingson ships to iOS, so collapsing this into text costs a
2864    /// keyboard with no `@` on it.
2865    ///
2866    /// Added 0.5.0, from goingson's contact form.
2867    Email,
2868    /// A URL. Same reasoning as [`Email`](Self::Email).
2869    ///
2870    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
2871    Url,
2872    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
2873    /// clearest case of it: the keyboard is a numeric pad rather than letters.
2874    ///
2875    /// Added 0.5.0, from goingson's contact-phone form.
2876    Tel,
2877    /// A calendar day, with no time of day in it.
2878    ///
2879    /// [`Email`](Self::Email)'s argument, and it carries further: a webview
2880    /// emits `type="date"`, which is a native picker, the platform's own
2881    /// validation, and on a touch device the date keyboard. Described as
2882    /// [`Text`](Self::Text) with a hint reading "YYYY-MM-DD", all three are
2883    /// lost and the hint is doing the platform's job in prose.
2884    ///
2885    /// The membership test passes on every host without stretching: a webview
2886    /// and a Tauri app emit the input, egui has a date picker, a terminal
2887    /// prompts for a day and can validate it, a CLI takes an argument.
2888    ///
2889    /// # The value is ISO 8601, `YYYY-MM-DD`
2890    ///
2891    /// Named here rather than left to each host, because a host that picks
2892    /// differently sends a server something it parses differently, and the
2893    /// failure is silent and per-host. It is `<input type="date">`'s own wire
2894    /// format, so the webview renderer owes nothing to honour it and the other
2895    /// hosts have one spelling to meet. [`DATE_FORMAT`] is the constant, and a
2896    /// test asserts this doc and that constant agree.
2897    ///
2898    /// Added 0.15.0, from the MNW server's git access-token expiry
2899    /// (`user_ssh_keys_tab.html`) and six further sites across the server and
2900    /// goingson.
2901    Date,
2902    /// A calendar day and a time of day together.
2903    ///
2904    /// Apart from [`Date`](Self::Date) because the question is different rather
2905    /// than more precise: "which day does this expire" and "at what moment does
2906    /// this publish" are asked by different screens and answered by different
2907    /// controls. A webview emits `type="datetime-local"` for one and
2908    /// `type="date"` for the other, and a host that collapsed them would ask
2909    /// half the tree for a precision it does not want.
2910    ///
2911    /// Both arrived together on measurement rather than on symmetry: 13 sites
2912    /// of each across the MNW server and goingson, and **zero** of `time`,
2913    /// `month` or `week`, which is why those are not here. A member added for a
2914    /// case nobody has is a member designed against nothing, which is
2915    /// [`File`](Self::File)'s reasoning about `accept` applied to a whole
2916    /// member.
2917    ///
2918    /// # The value is `YYYY-MM-DDTHH:MM`, local, with no zone
2919    ///
2920    /// `<input type="datetime-local">`'s own format, and the "local" is the
2921    /// load-bearing half: the value carries no offset and no `Z`, so the moment
2922    /// it names is only fixed once something supplies a zone. That is the app's
2923    /// business and not the description's. Seconds are absent, which is the
2924    /// browser's own default and is left as the rule rather than restated as a
2925    /// constraint. [`DATETIME_FORMAT`] is the constant.
2926    ///
2927    /// [`Field::min`] and [`Field::max`] already take "the host's own spelling
2928    /// of a bound", so a floor of *not in the past* needs nothing new here: it
2929    /// is a string in this same format.
2930    ///
2931    /// Added 0.15.0, from goingson's snooze picker and day planner and the MNW
2932    /// server's publish-at fields.
2933    DateTime,
2934    /// Several lines of text.
2935    Textarea,
2936    /// One of a fixed set, offered behind a control that shows one at a time.
2937    Select,
2938    /// One of a fixed set, with every option on screen at once.
2939    ///
2940    /// Not a presentation of [`Select`](Self::Select), which is the reading to
2941    /// resist: what differs is a property of the *question*. A choice that is
2942    /// consequential or irreversible has to be readable without opening
2943    /// anything, because a closed control shows one option and hides the rest,
2944    /// and the one it shows is whichever was current before the user had read
2945    /// the alternatives. audiofiles asks whether a library copies samples into
2946    /// its store or references them where they lie — which cannot be changed
2947    /// afterwards — and had already promoted that out of a checkbox by hand,
2948    /// with a comment giving this reason, before the description could say it.
2949    ///
2950    /// It was described here at 0.8.1 as "the one HTML input type this enum was
2951    /// missing", which was not true then and is not true now: `file` arrived at
2952    /// 0.11.0 and `date` and `datetime-local` at 0.15.0. Everything here is
2953    /// still an `<input type=...>`, a `<select>` or a `<textarea>`, and the way
2954    /// this enum grows is by a site being measured rather than by a list being
2955    /// completed, so "the last one" is not a claim it should make again.
2956    ///
2957    /// Added 0.8.1, from audiofiles' Add Library form.
2958    Radio,
2959    /// On or off.
2960    Checkbox,
2961    /// A file the user picks from wherever the host keeps files.
2962    ///
2963    /// Added 0.11.0, `844b5ae0`, from goingson's project-dashboard attachments
2964    /// column. It was filed as a router finding — a control whose destination is
2965    /// a host capability rather than an address — and splitting it is what made
2966    /// it two answers instead of one member satisfying neither. *Opening* a file
2967    /// is a one-way handoff and needs no new API. *Picking* one returns a value
2968    /// into a write, which is a form concern, which is this.
2969    ///
2970    /// The membership test passes on every host and not by a stretch: a Tauri
2971    /// app opens a native picker, a server renders `<input type="file">`, a
2972    /// terminal prompts for a path, a CLI takes an argument. That is closer to
2973    /// [`Email`](Self::Email), which exists because it changes the keyboard,
2974    /// than to anything bespoke.
2975    ///
2976    /// It carries no accepted-types list and no multiple flag, and that is
2977    /// measured rather than deferred: `accept` appears at zero sites in either
2978    /// app. A member added for a case nobody has is a member designed against
2979    /// nothing.
2980    File,
2981    /// Carried through the form and never shown.
2982    Hidden,
2983}
2984
2985/// The wire format a [`FieldKind::Date`] value takes: ISO 8601, `YYYY-MM-DD`.
2986///
2987/// A constant rather than a sentence in a doc comment, because the reason to
2988/// name the format at all is that a host picking its own would fail silently
2989/// against a server parsing another. A host that cannot emit the native control
2990/// still has one spelling to meet, and can say which one it meant.
2991pub const DATE_FORMAT: &str = "%Y-%m-%d";
2992
2993/// The wire format a [`FieldKind::DateTime`] value takes: `YYYY-MM-DDTHH:MM`,
2994/// local, carrying no zone and no seconds.
2995///
2996/// [`DATE_FORMAT`]'s sibling and there for its reason. The absent zone is a
2997/// property of the value rather than an omission: the moment is not fixed until
2998/// something outside the description supplies one.
2999pub const DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M";
3000
3001impl FieldKind {
3002    /// Whether the value the kind takes is a moment rather than a string.
3003    ///
3004    /// Named once here for the reason [`offers_options`](Self::offers_options)
3005    /// is: two kinds answer yes, and a host that has to parse or format a value
3006    /// needs to ask without spelling the pair out at each renderer. A third
3007    /// temporal kind should land here and nowhere else.
3008    ///
3009    /// The format each one takes is [`DATE_FORMAT`] and [`DATETIME_FORMAT`].
3010    #[must_use]
3011    pub const fn temporal(self) -> bool {
3012        matches!(self, Self::Date | Self::DateTime)
3013    }
3014
3015    /// Whether the field is drawn at all.
3016    #[must_use]
3017    pub const fn visible(self) -> bool {
3018        !matches!(self, Self::Hidden)
3019    }
3020
3021    /// Whether the value must be kept out of logs and diagnostics.
3022    #[must_use]
3023    pub const fn confidential(self) -> bool {
3024        matches!(self, Self::Secret)
3025    }
3026
3027    /// Where the field's own label sits.
3028    ///
3029    /// A checkbox labels itself on the right of the box; everything else takes
3030    /// a label above. Both webview apps already do this and both special-case
3031    /// it inline, which is the tell that it belongs in the description.
3032    ///
3033    /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
3034    /// naming: its *options* each label themselves, but the field still asks a
3035    /// question above them, so the group takes a label like everything else.
3036    #[must_use]
3037    pub const fn labels_itself(self) -> bool {
3038        matches!(self, Self::Checkbox)
3039    }
3040
3041    /// Whether the kind reads [`Field::options`].
3042    ///
3043    /// Two kinds do, so the pair is named once here rather than spelled out at
3044    /// each renderer and again in [`Field::options`]' own doc, where "every
3045    /// kind but `Select`" was true for exactly one release. A third
3046    /// option-taking kind should land here and nowhere else.
3047    #[must_use]
3048    pub const fn offers_options(self) -> bool {
3049        matches!(self, Self::Select | Self::Radio)
3050    }
3051}
3052
3053/// One option offered by a field [`FieldKind::offers_options`] accepts.
3054///
3055/// Two strings, because the submitted value and the read label are different
3056/// facts and every renderer that has tried to collapse them has had to
3057/// un-collapse them later. `makeover-webview` invented this shape writing its
3058/// form emitter and it is taken here unchanged; moving it down rather than
3059/// re-deriving it is the point, since the second and third renderers were each
3060/// going to arrive at a near-miss of it.
3061#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3062pub struct Choice<'a> {
3063    /// What is submitted.
3064    pub value: &'a str,
3065    /// What is read.
3066    pub label: &'a str,
3067}
3068
3069impl<'a> Choice<'a> {
3070    /// An option whose submitted value is also its label.
3071    #[must_use]
3072    pub const fn plain(value: &'a str) -> Self {
3073        Self {
3074            value,
3075            label: value,
3076        }
3077    }
3078}
3079
3080/// One field of a form.
3081///
3082/// Borrowed rather than owned: a description is built, read once by a renderer,
3083/// and dropped. Nothing here outlives the screen it describes.
3084///
3085/// # What it carries, and what it does not
3086///
3087/// Stated here so the next renderer does not re-ask, which is what the first
3088/// two both did. It carries everything a renderer needs to *draw* the field:
3089/// its kind, what it is called, what it is asked for, its standing help, what
3090/// is wrong with it now, whether it is compulsory, whether it hides behind a
3091/// disclosure, its ghost text, and the options it offers.
3092///
3093/// It does not carry the **current value**, and it is not going to. That is the
3094/// one thing here that is genuinely renderer state: a webview reads it back out
3095/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
3096/// and writes through it, and a terminal keeps an edit buffer. A description
3097/// that carried the value would have to carry a way to write it back, at which
3098/// point it is a form model and no longer a description.
3099///
3100/// **Constraints** are here and enforcement is not, which is one line rather
3101/// than two. [`required`], [`max_length`], [`min`] and [`max`] are facts about
3102/// the *question*, so a renderer can emit its host's idiom for each — an HTML
3103/// attribute, a marked label, a clamped spinner — and the platform helps the
3104/// user before anything is submitted. Deciding that a value is wrong stays with
3105/// whoever validated, and [`error`] is that decision arriving back.
3106///
3107/// The set stops before `pattern`, and stops there on both tests at once. A
3108/// regex has an honest answer in a webview and none anywhere else: egui would
3109/// have to run it per keystroke and decide what a half-typed value means, which
3110/// is enforcement wearing description's clothes. And it is one site in goingson
3111/// and none in Balanced Breakfast, against 8 and 1 for `maxlength`. Measured
3112/// 2026-08-09, `2cbad3e2`.
3113///
3114/// [`error`]: Field::error
3115/// [`required`]: Field::required
3116/// [`max_length`]: Field::max_length
3117/// [`min`]: Field::min
3118/// [`max`]: Field::max
3119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3120pub struct Field<'a> {
3121    /// What kind of value it takes.
3122    pub kind: FieldKind,
3123    /// The name the value is submitted under.
3124    pub name: &'a str,
3125    /// What the user is asked for.
3126    pub label: &'a str,
3127    /// Standing help, shown whether or not anything is wrong.
3128    pub hint: Option<&'a str>,
3129    /// What is currently wrong with the value.
3130    pub error: Option<&'a str>,
3131    /// Ghost text shown while the field is empty.
3132    ///
3133    /// User-facing text, and it sits with `label` and `hint` rather than with
3134    /// the value because it is a property of the *question* and not of the
3135    /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
3136    /// reason and it was not a reading on where it belonged: adding a field to
3137    /// a published struct is a breaking change.
3138    ///
3139    /// Not a substitute for a label. A field labelled only by its placeholder
3140    /// loses its label the moment anything is typed, and no renderer here can
3141    /// make that not happen, so the description keeps both.
3142    pub placeholder: Option<&'a str>,
3143    /// The options offered, in the order they are offered.
3144    ///
3145    /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
3146    /// described with no options is sayable on purpose: it is what an app with
3147    /// an unfinished-loading option list actually has, and a renderer showing
3148    /// an empty control says so on screen rather than in a log.
3149    ///
3150    /// Which option is *current* is not here. That is the value, and the value
3151    /// is renderer state.
3152    pub options: &'a [Choice<'a>],
3153    /// Whether the form refuses to submit without it.
3154    pub required: bool,
3155    /// The longest the value may be, in characters.
3156    ///
3157    /// Added 0.11.0 with [`min`](Self::min) and [`max`](Self::max), joining
3158    /// [`required`](Self::required), which had been the only constraint here
3159    /// since before the crate wrote down that it carried none.
3160    pub max_length: Option<u32>,
3161    /// The lowest value accepted, as the host would write it.
3162    ///
3163    /// Text rather than a number, because the bound is only a number for some
3164    /// of the kinds that take one. goingson's own sites are `min="1"` on a
3165    /// duration and `min="2026-08-09T14:30"` on a datetime, and a numeric member
3166    /// could say the first and not the second. The [`kind`](Self::kind) already
3167    /// says how to read it, the same way it does for the value.
3168    pub min: Option<&'a str>,
3169    /// The highest value accepted, as the host would write it. See
3170    /// [`min`](Self::min).
3171    pub max: Option<&'a str>,
3172    /// Whether the field lives behind a "more options" disclosure.
3173    pub extended: bool,
3174}
3175
3176impl<'a> Field<'a> {
3177    /// A plain required-nothing field of the given kind.
3178    #[must_use]
3179    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
3180        Self {
3181            kind,
3182            name,
3183            label,
3184            hint: None,
3185            error: None,
3186            placeholder: None,
3187            options: &[],
3188            required: false,
3189            max_length: None,
3190            min: None,
3191            max: None,
3192            extended: false,
3193        }
3194    }
3195
3196    /// A select offering the given options.
3197    ///
3198    /// One of the two kinds under-described by [`Field::new`], so it gets a
3199    /// constructor rather than leaving every call site to remember that a
3200    /// select with an empty `options` renders as an empty select.
3201    #[must_use]
3202    pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
3203        Self::offering(FieldKind::Select, name, label, options)
3204    }
3205
3206    /// A radio group offering the given options.
3207    ///
3208    /// The other. Same hazard as [`select`](Self::select) and a worse one: a
3209    /// radio group with no options draws nothing at all, so a call site that
3210    /// forgot them has an empty rectangle rather than a visibly empty control.
3211    #[must_use]
3212    pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
3213        Self::offering(FieldKind::Radio, name, label, options)
3214    }
3215
3216    /// The shared body of the two constructors that take options.
3217    ///
3218    /// Private, and keyed on the kind rather than exposed, because the two
3219    /// public names are the point: a call site says which question it is
3220    /// asking, not which flag it is setting.
3221    const fn offering(
3222        kind: FieldKind,
3223        name: &'a str,
3224        label: &'a str,
3225        options: &'a [Choice<'a>],
3226    ) -> Self {
3227        Self {
3228            options,
3229            ..Self::new(kind, name, label)
3230        }
3231    }
3232
3233    /// Whether the field is currently reporting a problem.
3234    ///
3235    /// Read this rather than testing `error.is_some()` at each renderer: the
3236    /// error state has to mark the field's whole group and not only the
3237    /// message, because a renderer with no descendant selectors (egui, a
3238    /// terminal) cannot find the group from the message. goingson already marks
3239    /// the group and Balanced Breakfast does not, so goingson's shape is the
3240    /// one taken here.
3241    #[must_use]
3242    pub const fn invalid(&self) -> bool {
3243        self.error.is_some()
3244    }
3245}
3246
3247/// How much room a placement asks for.
3248///
3249/// A column says it, and so does a [`Field`]. An intent, so the actual floor
3250/// stays with `makeover-geometry`. goingson's task table spells these as
3251/// `minmax(200px, 1fr)`, `140px` and content-sized; only the first three words
3252/// of that survive deferral.
3253/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
3254/// renderer matches on this and a vocabulary that grows must not break every
3255/// renderer when it does.
3256#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3257#[non_exhaustive]
3258pub enum Width {
3259    /// Takes what it needs and no more.
3260    Content,
3261    /// A fixed share, the same at every width.
3262    Fixed,
3263    /// Absorbs whatever is left over.
3264    ///
3265    /// **Several fills divide what is left equally.** Stated because it would
3266    /// otherwise be undefined and each renderer would invent something, and
3267    /// stated this way because equal division is the only sharing rule that
3268    /// answers to "Any width, one answer" without a tiebreak: allocating in
3269    /// declaration order makes the result depend on the order the description
3270    /// was written in, which is a fact about the source file and not about the
3271    /// screen. It documents what both renderers already do — CSS grid gives
3272    /// `1fr 1fr`, ratatui gives each a `Constraint::Fill(1)` — rather than
3273    /// changing anything.
3274    ///
3275    /// So a row of fills is a legal thing to describe, and there is no rule
3276    /// against it. Measured 2026-08-16, every table in the tree uses exactly
3277    /// one, which is the discipline this would otherwise have had to forbid.
3278    Fill,
3279}
3280
3281/// What a column is worth when there is not room for all of them.
3282///
3283/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
3284/// drops. This replaces addressing columns by position, which is what both
3285/// webview apps do today and is a live bug rather than only verbosity. goingson
3286/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
3287/// inserting a column silently hides the wrong one.
3288/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
3289/// whole point of the type, so a new tier has to be declared in its place in
3290/// the sequence rather than appended.
3291#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
3292#[non_exhaustive]
3293pub enum Priority {
3294    /// Dropped first.
3295    Optional,
3296    /// Dropped once the optional columns are gone.
3297    Secondary,
3298    /// Never dropped. Without it the row does not identify itself.
3299    Essential,
3300}
3301
3302/// One column of a table.
3303///
3304/// Described once. The grid track, the cell order and the drop behaviour are
3305/// all derived from this, rather than being three hand-written encodings that
3306/// must agree and are never checked against each other.
3307#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3308pub struct Column<'a> {
3309    /// The heading, and the name the cell is addressed by.
3310    pub name: &'a str,
3311    /// How much room it asks for.
3312    pub width: Width,
3313    /// What it is worth when room runs out.
3314    pub priority: Priority,
3315    /// Whether the user can reorder the table by this column.
3316    ///
3317    /// `ce620871`. What reordering *calls* is not here — that is an address, and
3318    /// this crate names none — so a host pairs this with the route the way it
3319    /// pairs a row's parts with the row's activation. This says the affordance
3320    /// exists, which is what a renderer needs to draw a header a user can press
3321    /// rather than a heading they cannot.
3322    pub sortable: bool,
3323    /// Which way the table is ordered by this column, if it is.
3324    ///
3325    /// `None` on every column but the one in force. A renderer draws the caret
3326    /// from this and a webview sets `aria-sort`, which is why it is per column
3327    /// rather than a single fact on the table: the host idiom is a property of
3328    /// the header cell.
3329    ///
3330    /// Independent of [`sortable`](Self::sortable) rather than implied by it,
3331    /// because both combinations mean something. A column sorted and not
3332    /// sortable is a list ordered by a key the user cannot change, which is a
3333    /// real thing to describe and a caret worth drawing.
3334    pub sorted: Option<Sort>,
3335}
3336
3337/// Which way a column is ordered.
3338///
3339/// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
3340/// `None`, and folding it in here would be the same absence said twice.
3341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3342pub enum Sort {
3343    /// Smallest, earliest or first alphabetically at the top.
3344    Ascending,
3345    /// The other way.
3346    Descending,
3347}
3348
3349impl Sort {
3350    /// The other direction, for a header that flips when pressed.
3351    #[must_use]
3352    pub const fn reversed(self) -> Self {
3353        match self {
3354            Self::Ascending => Self::Descending,
3355            Self::Descending => Self::Ascending,
3356        }
3357    }
3358
3359    /// What a webview writes into `aria-sort`.
3360    ///
3361    /// Named here rather than in the webview renderer because a terminal and an
3362    /// immediate-mode painter both want the same two words for a caret's label,
3363    /// and three renderers picking their own is the drift this crate ends.
3364    #[must_use]
3365    pub const fn as_str(self) -> &'static str {
3366        match self {
3367            Self::Ascending => "ascending",
3368            Self::Descending => "descending",
3369        }
3370    }
3371
3372    /// The caret a renderer draws for this direction.
3373    ///
3374    /// Here for [`as_str`](Self::as_str)'s reason, said about a glyph rather
3375    /// than a word: three renderers picking their own is the drift this crate
3376    /// ends. They had picked their own — two on the solid triangles and
3377    /// `makeover-webview` on the arrows U+2191/U+2193 — and agreeing by
3378    /// coincidence in three files is not agreement.
3379    ///
3380    /// Settled 2026-08-16 (Max): the solid triangles, U+25B2 and U+25BC. The
3381    /// reason generalizes past this pair and is the house rule now — prefer the
3382    /// bolder, simpler glyph over the thinner or more complicated one. A third
3383    /// spelling is not open for re-argument.
3384    ///
3385    /// **Bare, with no spacing.** Where the gap goes is each renderer's
3386    /// business: `makeover-tui` and `makeover-immediate` carry a leading space
3387    /// inside their `TableStyle` string and a webview emits its own in
3388    /// `content`, so folding a space in here would make one of the two wrong.
3389    ///
3390    /// Neither face the web apps self-host carries these — IBM Plex Mono has one
3391    /// glyph in the whole geometric-shapes block and Lato has none — so a
3392    /// browser falls back per glyph until the in-house face ships with them
3393    /// drawn in (makeover `6d6d9146`, wiki `typography-standard`). Cosmetic
3394    /// drift in one renderer, not a reason to spell it three ways.
3395    #[must_use]
3396    pub const fn glyph(self) -> &'static str {
3397        match self {
3398            Self::Ascending => "\u{25B2}",
3399            Self::Descending => "\u{25BC}",
3400        }
3401    }
3402}
3403
3404impl<'a> Column<'a> {
3405    /// A column that absorbs slack and drops after the optional ones.
3406    #[must_use]
3407    pub const fn new(name: &'a str) -> Self {
3408        Self {
3409            name,
3410            width: Width::Fill,
3411            priority: Priority::Secondary,
3412            sortable: false,
3413            sorted: None,
3414        }
3415    }
3416
3417    /// Whether this column survives at the given cutoff.
3418    ///
3419    /// A renderer narrows by raising the cutoff, and never by counting
3420    /// positions.
3421    #[must_use]
3422    pub const fn kept_at(&self, cutoff: Priority) -> bool {
3423        (self.priority as u8) >= (cutoff as u8)
3424    }
3425}
3426
3427/// What a table cell holds.
3428///
3429/// [`RowPart`] for tables, and it exists for the same reason: a part that
3430/// carries a control is not text, and a renderer with one class for the whole
3431/// cell paints it as though it were. `makeover-webview` emitted a single
3432/// `.cell` until 0.25.0, so a button in a cell inherited the cell's content
3433/// colour, which is the exact drift [`RowPart::intent`] prevents for rows and
3434/// prevented for nothing here.
3435///
3436/// Four members, and the count is what quasi's `Cell` was measured to carry:
3437/// a value, tokens (33 cells across 22 server templates), actions (30 rows
3438/// carrying a control, 5 beside a value) and a link (35 cells across 18
3439/// templates). Nothing was added past what something holds.
3440///
3441/// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
3442/// lockstep event across three renderers.
3443///
3444/// # No hover-reveal
3445///
3446/// [`RowPart`] carried a `revealed_on_hover` until 0.13.0 retired it, and this
3447/// enum never gets one. A cell's actions are shown at rest in every consumer
3448/// measured, and a member nothing uses is one three renderers owe an answer
3449/// for.
3450#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3451#[non_exhaustive]
3452pub enum CellPart {
3453    /// The cell's own text.
3454    Value,
3455    /// Small labelled things in the cell: a status badge, a chip.
3456    Tokens,
3457    /// Controls that act on what the row is about.
3458    Actions,
3459    /// The cell's value, where the value is itself a link.
3460    Link,
3461}
3462
3463impl CellPart {
3464    /// The content intent the part takes.
3465    ///
3466    /// One part is text and three are not, so three answer with the intent
3467    /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
3468    /// text side narrower: a cell's secondary and muted readings are the
3469    /// column's business, not the cell's.
3470    #[must_use]
3471    pub const fn intent(self) -> &'static str {
3472        match self {
3473            Self::Value => "content",
3474            // A token carries its own tone, and a part-level intent underneath
3475            // it would fight the token sitting on it.
3476            Self::Tokens => "content",
3477            // Actions carry controls rather than text.
3478            Self::Actions => "content",
3479            // A link takes the action colour from the control it is, rather
3480            // than the cell's text colour from the cell it sits in.
3481            Self::Link => "content",
3482        }
3483    }
3484}
3485
3486#[cfg(test)]
3487mod tests {
3488    use super::*;
3489
3490    #[test]
3491    fn the_four_readiness_states_are_one_axis_and_only_one_shows_content() {
3492        // Mutually exclusive is the test for one enum against several fields: a
3493        // region shows its content, or that it is coming, or that there is none,
3494        // or that it broke. Never two.
3495        assert!(Readiness::Ready.shows_content());
3496        for state in [Readiness::Pending, Readiness::Empty, Readiness::Failed] {
3497            assert!(!state.shows_content());
3498        }
3499    }
3500
3501    #[test]
3502    fn a_region_shows_all_of_its_children_unless_it_says_otherwise() {
3503        // The default is the behaviour every region had before this member
3504        // existed, which is what keeps it additive: a description written
3505        // against 0.22.0 says the same thing under 0.23.0.
3506        assert_eq!(Showing::default(), Showing::All);
3507        assert!(!Showing::All.selective());
3508    }
3509
3510    #[test]
3511    fn only_a_disclosure_can_show_nothing() {
3512        // The two derived idioms differ in one respect and this is it. A
3513        // carousel's row moves between frames and never reaches empty; a
3514        // disclosure's summary line is the same control wearing its closed
3515        // state, so a renderer has to know which it is drawing.
3516        assert!(Showing::AtMostOne.dismissible());
3517        assert!(!Showing::One.dismissible());
3518        assert!(!Showing::All.dismissible());
3519
3520        // Both are selective, though. Deriving chrome is one question and
3521        // whether that chrome closes is another.
3522        assert!(Showing::One.selective());
3523        assert!(Showing::AtMostOne.selective());
3524    }
3525
3526    #[test]
3527    fn an_empty_region_is_not_a_broken_one() {
3528        // An empty list is the normal state of a new install. Drawing it in a
3529        // danger tone reports a fault where there is none, and this is the one
3530        // place the distinction is carried.
3531        assert_eq!(Readiness::Empty.tone(), Tone::Neutral);
3532        assert_eq!(Readiness::Failed.tone(), Tone::Danger);
3533        assert_eq!(Readiness::Pending.tone(), Tone::Neutral);
3534    }
3535
3536    #[test]
3537    fn a_column_can_be_sorted_without_being_sortable() {
3538        // Both combinations mean something, which is why the two fields are
3539        // independent rather than one implying the other. A list ordered by a
3540        // key the user cannot change is a real thing with a caret worth drawing.
3541        let fixed = Column {
3542            sorted: Some(Sort::Descending),
3543            ..Column::new("Created")
3544        };
3545
3546        assert!(!fixed.sortable);
3547        assert_eq!(fixed.sorted.map(Sort::as_str), Some("descending"));
3548
3549        let offered = Column {
3550            sortable: true,
3551            ..Column::new("Name")
3552        };
3553        assert_eq!(offered.sorted, None);
3554    }
3555
3556    #[test]
3557    fn a_direction_flips_and_says_what_it_is() {
3558        assert_eq!(Sort::Ascending.reversed(), Sort::Descending);
3559        assert_eq!(Sort::Descending.reversed().reversed(), Sort::Descending);
3560        assert_eq!(Sort::Ascending.as_str(), "ascending");
3561    }
3562
3563    #[test]
3564    fn a_direction_carries_its_caret_and_the_two_are_not_the_same_glyph() {
3565        // The spelling every renderer reads, so that agreeing is composition
3566        // rather than three files happening to hold the same literal.
3567        assert_eq!(Sort::Ascending.glyph(), "\u{25B2}");
3568        assert_eq!(Sort::Descending.glyph(), "\u{25BC}");
3569        assert_ne!(Sort::Ascending.glyph(), Sort::Descending.glyph());
3570        // Bare. The gap is the renderer's, and a space here would be a second
3571        // one wherever a renderer already carries its own.
3572        for d in [Sort::Ascending, Sort::Descending] {
3573            assert_eq!(d.glyph().trim(), d.glyph());
3574        }
3575    }
3576
3577    #[test]
3578    fn a_figure_carries_its_tone_because_no_renderer_can_derive_it() {
3579        // Three of goingson's five sites tone the figure by their own means, so
3580        // tone is carried at every site that needs it and derived at none. The
3581        // same reasoning `Meter` reached, from a different direction.
3582        let streak = Figure::new("0", "Current Streak").tone(Tone::Warning);
3583        assert_eq!(streak.tone, Tone::Warning);
3584        assert_eq!(Figure::new("17", "Total").tone, Tone::Neutral);
3585    }
3586
3587    #[test]
3588    fn a_figures_change_is_the_toned_part_and_is_absent_by_default() {
3589        // 0.13.0. The MNW server's stat card is a label, a value and a delta,
3590        // across four screens, and the delta is what reads as good or bad. Tone
3591        // had no consumer before this: the figure itself is an ordinary fact.
3592        let views = Figure::new("1,204", "Views")
3593            .change("+12.5%")
3594            .tone(Tone::Success);
3595        assert_eq!(views.change, Some("+12.5%"));
3596        assert_eq!(views.tone, Tone::Success);
3597
3598        // A figure with nothing to compare against says so by having no change,
3599        // rather than by carrying an empty string a renderer has to test for.
3600        assert_eq!(Figure::new("3.1%", "Conversion").change, None);
3601    }
3602
3603    #[test]
3604    fn a_figures_value_is_text_because_only_the_app_knows_what_it_is() {
3605        // "84%", "12/30", "3d". A figure is whatever the app computed, already
3606        // formatted, and that is the line between this and `Meter`: a meter is
3607        // a proportion a renderer draws, a figure is a fact it sets in type.
3608        for value in ["84%", "12/30", "3d"] {
3609            assert_eq!(Figure::new(value, "Rate").value, value);
3610        }
3611    }
3612
3613    #[test]
3614    fn a_proportion_is_a_row_part_and_takes_no_intent_of_its_own() {
3615        // The meter carries the tone, so a part-level intent underneath would
3616        // fight it. Same answer `Tokens` needed, for the same reason.
3617        assert_eq!(RowPart::Proportion.intent(), RowPart::Tokens.intent());
3618    }
3619
3620    #[test]
3621    fn a_file_field_is_drawn_and_offers_no_options() {
3622        // It is a control the user operates, unlike `Hidden`, and it does not
3623        // pick from a list the description carries, unlike `Select`.
3624        assert!(FieldKind::File.visible());
3625        assert!(!FieldKind::File.offers_options());
3626        assert!(!FieldKind::File.confidential());
3627    }
3628
3629    #[test]
3630    fn a_constraint_is_a_fact_about_the_question_and_not_a_verdict() {
3631        // The whole model: the description carries the rule, the renderer emits
3632        // its host's idiom, and `error` is what arrives back when someone
3633        // validated. Nothing here decides a value is wrong.
3634        let field = Field {
3635            max_length: Some(100),
3636            min: Some("1"),
3637            max: Some("240"),
3638            required: true,
3639            ..Field::new(FieldKind::Number, "minutes", "Minutes")
3640        };
3641        assert!(!field.invalid());
3642
3643        // A bound is text because it is only a number for some of the kinds
3644        // that take one. goingson has both shapes live.
3645        let when = Field {
3646            min: Some("2026-08-09T14:30"),
3647            ..Field::new(FieldKind::Text, "starts", "Starts")
3648        };
3649        assert_eq!(when.min, Some("2026-08-09T14:30"));
3650    }
3651
3652    #[test]
3653    fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
3654        // The whole reason this is a pair. goingson's `Task::time_progress`
3655        // clamps to 100 and then carries `is_over_estimate` beside it to say
3656        // what the clamp dropped; a meter says both from one fact.
3657        let over = Meter::new(45, 30);
3658        assert_eq!(over.percent(), 100);
3659        assert!(over.overflowing());
3660
3661        let exact = Meter::new(30, 30);
3662        assert_eq!(exact.percent(), over.percent());
3663        assert!(!exact.overflowing());
3664    }
3665
3666    #[test]
3667    fn an_empty_set_does_not_divide_by_zero() {
3668        // Sayable on purpose, so it has to be answerable. A meter over an
3669        // unloaded count is what an app actually has for a frame.
3670        let none = Meter::new(0, 0);
3671        assert_eq!(none.percent(), 0);
3672        assert!(none.is_empty());
3673        assert!(!none.overflowing());
3674    }
3675
3676    #[test]
3677    fn the_ratio_survives_where_a_percentage_would_not() {
3678        // Given 43 nothing can recover "3 of 7", which is why the numbers are
3679        // carried and the label names only the noun.
3680        let m = Meter::new(3, 7).label("subtasks");
3681        assert_eq!(m.percent(), 42);
3682        assert_eq!((m.done, m.total), (3, 7));
3683        assert_eq!(m.label, Some("subtasks"));
3684    }
3685
3686    #[test]
3687    fn tone_is_carried_because_no_renderer_can_derive_it() {
3688        // The same fullness means opposite things on two of goingson's bars,
3689        // and only the app knows which.
3690        let subtasks = Meter::new(9, 10).tone(Tone::Success);
3691        let estimate = Meter::new(9, 10).tone(Tone::Danger);
3692        assert_eq!(subtasks.percent(), estimate.percent());
3693        assert_ne!(subtasks.tone, estimate.tone);
3694        // Untoned by default: a bar says nothing about status until something
3695        // says so, the same way a row is not selectable until told.
3696        assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
3697    }
3698
3699    #[test]
3700    fn an_act_is_reachable_until_it_is_disabled() {
3701        // The one member a renderer must branch on, and since 0.19.0 the only
3702        // member there is. A stated state is not by itself a reason to stop
3703        // answering, which is the distinction `State` makes and every
3704        // hand-rolled button in the tree had to remember.
3705        assert!(!Act::new("Save").disabled());
3706        assert!(Act::new("Save").state(State::Disabled).disabled());
3707    }
3708
3709    #[test]
3710    fn an_act_carries_its_key_because_a_terminal_has_nothing_else() {
3711        // No key is the ordinary case, and the webview hosts that ignore it
3712        // are why it stayed optional.
3713        assert_eq!(Act::new("Delete").key, None);
3714        let quit = Act::new("Quit").key("q").tone(Tone::Danger);
3715        assert_eq!(quit.key, Some("q"));
3716        assert_eq!(quit.tone, Tone::Danger);
3717    }
3718
3719    #[test]
3720    fn a_meter_does_not_overflow_on_large_counts() {
3721        // done * 100 in u32 would wrap somewhere past 42 million. Counts that
3722        // size are not tasks, but a description layer that silently reports 3%
3723        // for a full bar is worse than one that is slow.
3724        let big = Meter::new(u32::MAX, u32::MAX);
3725        assert_eq!(big.percent(), 100);
3726        assert!(!big.overflowing());
3727    }
3728
3729    #[test]
3730    fn inset_is_raised_with_the_light_moved() {
3731        let (rl, rd) = Bevel::Raised.edges();
3732        let (il, id) = Bevel::Inset.edges();
3733        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
3734        assert_eq!((il, id), (rd, rl));
3735    }
3736
3737    #[test]
3738    fn pressing_twice_is_a_no_op() {
3739        for b in [Bevel::Raised, Bevel::Inset] {
3740            assert_eq!(b.pressed().pressed(), b);
3741        }
3742    }
3743
3744    #[test]
3745    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
3746        // The bug this vocabulary exists to make unrepresentable.
3747        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
3748        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
3749        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
3750        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
3751    }
3752
3753    #[test]
3754    fn state_is_orthogonal_to_depth() {
3755        // The reason State is its own axis and not a Depth member: a disabled
3756        // button and a disabled field are both disabled and are not the same
3757        // shape, which one shared variant could not have said.
3758        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
3759        assert_eq!(Depth::Well.fill(), Some(Fill::Well));
3760        assert!(State::Disabled.suppresses_interaction());
3761    }
3762
3763    #[test]
3764    fn only_disabled_stops_answering() {
3765        // Kept in spirit from the version where `Focus` was the counter-example:
3766        // suppressing interaction is `Disabled`'s alone, so a member added here
3767        // later does not get to inherit it by being a state.
3768        assert!(State::Disabled.suppresses_interaction());
3769    }
3770
3771    #[test]
3772    fn disabled_resolves_against_an_intent_makeover_already_derives() {
3773        // No new token, so this costs no `makeover` release.
3774        assert_eq!(State::Disabled.token(), "content-muted");
3775    }
3776
3777    #[test]
3778    fn flat_has_neither_edge_nor_fill() {
3779        assert_eq!(Depth::Flat.bevel(), None);
3780        assert_eq!(Depth::Flat.fill(), None);
3781    }
3782
3783    #[test]
3784    fn sunken_is_recessed_by_colour_with_no_edge() {
3785        // The one member carrying a fill without a bevel. A renderer that
3786        // assumes the two arrive together drops the fill silently, which is
3787        // exactly what makeover-webview did before 0.3.0.
3788        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
3789        assert_eq!(Depth::Sunken.bevel(), None);
3790    }
3791
3792    #[test]
3793    fn sunken_and_flat_are_different_claims() {
3794        // Both edgeless, and only one of them needs a colour. Collapsing them
3795        // is what left an unchosen tab unsayable.
3796        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
3797        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
3798    }
3799
3800    #[test]
3801    fn a_sunken_surface_is_not_a_well() {
3802        // Authored in opposite directions: makeover derives surface-well by
3803        // inverting against the theme's content colour, while surface-sunken is
3804        // authored and may sit darker than raised.
3805        assert_ne!(Fill::Sunken, Fill::Well);
3806        assert_eq!(Fill::Sunken.token(), "surface-sunken");
3807        assert_eq!(Fill::Well.token(), "surface-well");
3808    }
3809
3810    #[test]
3811    fn every_selector_describes_both_of_its_states() {
3812        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
3813        // unchosen option fell through to Flat at every renderer.
3814        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
3815            assert_ne!(
3816                s.chosen(),
3817                s.unchosen(),
3818                "{s:?} cannot tell picked from unpicked"
3819            );
3820        }
3821    }
3822
3823    #[test]
3824    fn only_a_tab_inverts_the_other_way() {
3825        // Tabs recede so the chosen one comes forward; a segment and a toggle
3826        // stand up so the chosen one is held in. That inversion is the whole
3827        // content of "picked" once colour is deferred, and it is why the three
3828        // are not one member with a flag.
3829        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
3830        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
3831
3832        for s in [Selector::Segmented, Selector::Toggle] {
3833            assert_eq!(s.unchosen(), Depth::Raised);
3834            assert_eq!(s.chosen(), Depth::Well);
3835            // Held in is what pressing produces: one appearance, two reasons.
3836            assert_eq!(s.unchosen().pressed(), s.chosen());
3837        }
3838    }
3839
3840    #[test]
3841    fn pressing_a_card_makes_a_well() {
3842        assert_eq!(Depth::Raised.pressed(), Depth::Well);
3843        assert_eq!(
3844            Depth::Raised.pressed().bevel(),
3845            Depth::Raised.bevel().map(Bevel::pressed)
3846        );
3847        // Only raised regions respond to being pressed.
3848        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
3849        assert_eq!(Depth::Well.pressed(), Depth::Well);
3850        // An overlay is a surface, not a control.
3851        assert_eq!(Depth::Overlay.pressed(), Depth::Overlay);
3852    }
3853
3854    #[test]
3855    fn an_overlay_is_lifted_rather_than_edged() {
3856        // The wave-2 rule: a surface over the page takes elevation, a surface
3857        // in the page takes a bevel. Both halves come off the one Depth, so
3858        // they cannot disagree.
3859        assert_eq!(Depth::Overlay.fill(), Some(Fill::Overlay));
3860        assert_eq!(Depth::Overlay.bevel(), None);
3861
3862        // Three depths have no bevel and they are not the same claim. Flat has
3863        // nothing to separate from, Sunken's colour is doing the separating,
3864        // and an overlay is separated by the lift.
3865        assert_ne!(Depth::Overlay.fill(), Depth::Sunken.fill());
3866        assert_ne!(Depth::Overlay.fill(), Depth::Flat.fill());
3867    }
3868
3869    #[test]
3870    fn intents_name_makeover_tokens_and_nothing_else() {
3871        assert_eq!(Edge::Light.token(), "bevel-light");
3872        assert_eq!(Edge::Dark.token(), "bevel-dark");
3873        assert_eq!(Fill::Raised.token(), "surface-raised");
3874        assert_eq!(Fill::Well.token(), "surface-well");
3875        // No value ever leaves this crate.
3876        for t in [
3877            Edge::Light.token(),
3878            Edge::Dark.token(),
3879            Tone::Danger.token(),
3880            Tone::Neutral.token(),
3881            State::Disabled.token(),
3882        ] {
3883            assert!(!t.starts_with('#'), "{t} looks like a value");
3884            assert!(
3885                !t.chars().next().unwrap().is_ascii_digit(),
3886                "{t} is a value"
3887            );
3888        }
3889    }
3890
3891    #[test]
3892    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
3893        // The one line that runs through all three apps' taxonomies.
3894        assert!(!Token::Badge.interactive());
3895        assert!(Token::Chip { removable: false }.interactive());
3896        assert!(Token::Chip { removable: true }.interactive());
3897
3898        // A badge is a label, so giving it an edge would lie about it.
3899        assert_eq!(Token::Badge.depth(false), Depth::Flat);
3900        assert_eq!(Token::Badge.depth(true), Depth::Flat);
3901
3902        // A latched chip wears the same shape a pressed one does.
3903        let chip = Token::Chip { removable: false };
3904        assert_eq!(chip.depth(false), Depth::Raised);
3905        assert_eq!(chip.depth(true), Depth::Raised.pressed());
3906    }
3907
3908    #[test]
3909    fn a_toast_and_a_banner_differ_in_more_than_placement() {
3910        assert!(Notice::Toast.transient());
3911        assert!(!Notice::Banner.transient());
3912        // A toast floats above the page; a banner rests in the flow.
3913        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
3914        assert_eq!(Notice::Banner.fill(), Fill::Raised);
3915    }
3916
3917    #[test]
3918    fn emphasis_falls_off_down_the_row() {
3919        // `revealed_on_hover` was asserted here until 0.13.0 retired it. It said
3920        // a row's actions stay hidden until hover, which stopped being true when
3921        // makeover-webview 0.23.0 showed them at rest, and nothing had consumed
3922        // it for a release either way.
3923        assert_eq!(RowPart::Primary.intent(), "content");
3924        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
3925        assert_eq!(RowPart::Meta.intent(), "content-muted");
3926    }
3927
3928    #[test]
3929    fn a_token_part_carries_no_intent_of_its_own() {
3930        // Each token carries its own tone, so a part-level intent underneath
3931        // would fight the thing sitting on it. Same reasoning as actions, which
3932        // is why they answer alike.
3933        assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
3934        assert_eq!(RowPart::Tokens.intent(), "content");
3935    }
3936
3937    #[test]
3938    fn the_two_temporal_kinds_are_the_two_that_name_a_moment() {
3939        // The pair is named once so a host with parsing to do asks here rather
3940        // than spelling it out, which is `offers_options`' reason.
3941        assert!(FieldKind::Date.temporal());
3942        assert!(FieldKind::DateTime.temporal());
3943
3944        for kind in [
3945            FieldKind::Text,
3946            FieldKind::Secret,
3947            FieldKind::Number,
3948            FieldKind::Email,
3949            FieldKind::Url,
3950            FieldKind::Tel,
3951            FieldKind::Textarea,
3952            FieldKind::Select,
3953            FieldKind::Radio,
3954            FieldKind::Checkbox,
3955            FieldKind::File,
3956            FieldKind::Hidden,
3957        ] {
3958            assert!(!kind.temporal(), "{kind:?}");
3959        }
3960    }
3961
3962    #[test]
3963    fn a_date_carries_no_time_and_a_datetime_carries_no_zone() {
3964        // The formats are the whole reason the members are worth naming apart
3965        // from text, so the doc comments and the constants have to agree. A
3966        // host reading one and meeting the other is the silent failure.
3967        assert_eq!(DATE_FORMAT, "%Y-%m-%d");
3968        assert!(!DATE_FORMAT.contains("%H"), "a day carries no hour");
3969
3970        assert_eq!(DATETIME_FORMAT, "%Y-%m-%dT%H:%M");
3971        assert!(
3972            DATETIME_FORMAT.starts_with(DATE_FORMAT),
3973            "a moment starts with the day it is on"
3974        );
3975        // Local, and that is a property of the value rather than an omission.
3976        assert!(!DATETIME_FORMAT.contains("%Z"), "no zone name");
3977        assert!(!DATETIME_FORMAT.ends_with('Z'), "not UTC-stamped");
3978        assert!(!DATETIME_FORMAT.contains("%S"), "no seconds by default");
3979    }
3980
3981    #[test]
3982    fn a_temporal_kind_takes_a_label_above_it_and_offers_no_options() {
3983        // Neither is a checkbox and neither is a fixed set, so both fall where
3984        // text does. Asserted because a new kind lands in three predicates and
3985        // only one of them is the interesting one.
3986        for kind in [FieldKind::Date, FieldKind::DateTime] {
3987            assert!(kind.visible(), "{kind:?}");
3988            assert!(!kind.confidential(), "{kind:?}");
3989            assert!(!kind.labels_itself(), "{kind:?}");
3990            assert!(!kind.offers_options(), "{kind:?}");
3991        }
3992    }
3993
3994    #[test]
3995    fn a_cell_part_names_an_intent_and_only_the_value_is_text() {
3996        // The table half of what RowPart::intent does for rows. A cell holding
3997        // a control and a cell holding text answered alike until 0.14.0, and a
3998        // control in a cell took the cell's text colour.
3999        assert_eq!(CellPart::Value.intent(), "content");
4000
4001        for part in [CellPart::Tokens, CellPart::Actions, CellPart::Link] {
4002            // Each for its own reason -- a token carries its tone, an action is
4003            // a control, a link takes the action colour -- and all three reach
4004            // the intent inheriting already gives.
4005            assert_eq!(part.intent(), CellPart::Value.intent(), "{part:?}");
4006        }
4007    }
4008
4009    #[test]
4010    fn every_cell_part_answers_with_a_token_and_never_a_value() {
4011        for part in [
4012            CellPart::Value,
4013            CellPart::Tokens,
4014            CellPart::Actions,
4015            CellPart::Link,
4016        ] {
4017            let intent = part.intent();
4018            assert!(!intent.is_empty(), "{part:?} names nothing");
4019            assert!(!intent.starts_with('#'), "{part:?} looks like a value");
4020        }
4021    }
4022
4023    #[test]
4024    fn a_separator_is_what_tells_a_section_from_a_subsection() {
4025        assert!(Heading::Section.separated());
4026        assert!(!Heading::Subsection.separated());
4027        assert!(!Heading::Page.separated());
4028    }
4029
4030    #[test]
4031    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
4032        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
4033        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
4034        // The exception, and the whole folder semantic: the open tab joins its
4035        // pane rather than sinking away from it.
4036        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
4037
4038        // A held-in segment is indistinguishable from a pressed raised one,
4039        // which is the economy the light model buys over a colour swap.
4040        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
4041
4042        // A toggle stands alone; the other two are built out of parts that
4043        // touch.
4044        assert!(Selector::Segmented.abutting());
4045        assert!(Selector::Tabs.abutting());
4046        assert!(!Selector::Toggle.abutting());
4047    }
4048
4049    #[test]
4050    fn columns_are_peers_and_a_split_is_not() {
4051        // The distinction the member exists for. A split's two panes stand in a
4052        // master-detail relationship; columns choose nothing about each other.
4053        // Both are flat, so depth cannot tell them apart and the doc has to.
4054        assert_eq!(Region::Columns.depth(), Depth::Flat);
4055        assert_eq!(Region::Split.depth(), Depth::Flat);
4056        assert_ne!(Region::Columns, Region::Split);
4057    }
4058
4059    #[test]
4060    fn columns_carry_no_count_and_no_share() {
4061        // The two things a board is always asked to carry and must not. How
4062        // many is what the children say; how wide is settled by "peers are
4063        // equal".
4064        //
4065        // The guard is the binding itself and it is a compile-time one: adding
4066        // a field to `Columns` stops this line compiling, which is a better
4067        // failure than any assertion about it. Written out rather than inlined
4068        // for exactly that reason.
4069        let columns: Region<'_> = Region::Columns;
4070        assert_eq!(columns.name(), None);
4071    }
4072
4073    #[test]
4074    fn columns_are_described_and_the_escape_hatch_is_still_one_member() {
4075        // A board's contents are ordinary description all the way down, so a
4076        // renderer that does not lay them across still draws every column.
4077        // Stacking them vertically is honouring this member, not degrading it.
4078        assert!(Region::Columns.described());
4079        assert!(!Region::Bespoke { name: "timeline" }.described());
4080    }
4081
4082    #[test]
4083    fn a_span_never_has_zero_minutes_however_it_is_asked_for() {
4084        // Every renderer divides by this. A caller passing a backwards or empty
4085        // span is a bug, but it is not a bug worth a panic three renderers deep.
4086        assert_eq!(Span::new(600, 600).length(), 1);
4087        assert_eq!(Span::new(600, 300).length(), 1);
4088        assert_eq!(Span::DAY.length(), 1440);
4089    }
4090
4091    #[test]
4092    fn a_span_can_run_past_midnight_without_a_second_date() {
4093        // 22:00 to 02:00. The alternative was carrying a date, which drags a
4094        // timezone into the vocabulary for the sake of one night shift.
4095        let overnight = Span::new(1320, 1560);
4096        assert_eq!(overnight.length(), 240);
4097        assert!(overnight.holds(1500));
4098        assert!(!overnight.holds(1200));
4099    }
4100
4101    #[test]
4102    fn overlap_is_computed_rather_than_declared() {
4103        // The reason Placement carries no `conflicts` flag: the times already
4104        // say it, and a second source for one fact is how a stale conflict
4105        // badge outlives the conflict.
4106        let morning = Placement::new(540, 60); // 09:00-10:00
4107        let overlapping = Placement::new(570, 60); // 09:30-10:30
4108        let after = Placement::new(600, 60); // 10:00-11:00
4109
4110        assert!(morning.overlaps(overlapping));
4111        assert!(overlapping.overlaps(morning), "overlap is symmetric");
4112        // Touching end to end is not overlapping: `to` is exclusive, so a
4113        // 10:00 start does not collide with a 10:00 end.
4114        assert!(!morning.overlaps(after));
4115        assert!(!after.overlaps(morning));
4116    }
4117
4118    #[test]
4119    fn a_placement_is_always_drawable() {
4120        assert_eq!(Placement::new(540, 0).length(), 1);
4121        assert_eq!(Placement::new(540, 30).end(), 570);
4122    }
4123
4124    #[test]
4125    fn a_track_places_the_fraction_every_renderer_would_otherwise_compute() {
4126        let day = Track::DAY;
4127        assert!((day.fraction(0) - 0.0).abs() < f32::EPSILON);
4128        assert!((day.fraction(720) - 0.5).abs() < f32::EPSILON);
4129        // Clamped rather than off the end: an event running past the span's
4130        // close draws at the edge, which beats panicking or drawing nowhere.
4131        assert!((day.fraction(2000) - 1.0).abs() < f32::EPSILON);
4132    }
4133
4134    #[test]
4135    fn a_track_counts_its_slots_and_never_divides_by_zero() {
4136        assert_eq!(Track::DAY.slots(), 96);
4137        assert_eq!(Track::over(Span::new(540, 1020)).slots(), 32);
4138        // A span that does not divide evenly keeps a slot for its tail.
4139        assert_eq!(Track::over(Span::new(0, 50)).slots(), 4);
4140        // slot: 0 is a caller bug that reads as one slot, not a panic.
4141        let degenerate = Track {
4142            span: Span::DAY,
4143            slot: 0,
4144            tick: 60,
4145            unit: Unit::Minutes,
4146        };
4147        assert_eq!(degenerate.slots(), 1);
4148    }
4149
4150    #[test]
4151    fn a_track_carries_facts_and_no_presentation() {
4152        // The guard on the thing the withdrawn refusal was right about. If a
4153        // pixel measure, a scroll offset or a colour ever lands on Track, the
4154        // member has stopped being a fact about the data and the timeline
4155        // really has become a component library wearing a description's name.
4156        let day = Track::DAY;
4157        assert_eq!(day.span, Span::DAY);
4158        assert_eq!(day.slot, 15);
4159        assert_eq!(day.tick, 60);
4160        assert_eq!(day.unit, Unit::Minutes);
4161
4162        // Three fields when this was written, and the fourth came here to say
4163        // why, which is the whole point of the assertion. `unit` is what the
4164        // integers COUNT -- a fact about the data, unavailable from the numbers
4165        // themselves, and the absence of it is what let a month strip render
4166        // under a wall clock. A fifth field still has to argue, and "the
4167        // renderer would find it handy" is still not the argument.
4168        // Destructured rather than rebuilt: this is the form that names every
4169        // field and stops compiling when a fifth arrives, without binding
4170        // anything a lint has to forgive.
4171        let Track {
4172            span: _,
4173            slot: _,
4174            tick: _,
4175            unit: _,
4176        } = day;
4177    }
4178
4179    #[test]
4180    fn a_day_strip_is_the_same_arithmetic_under_a_different_unit() {
4181        // The probe that found the defect, kept as a test. Fifteen days from
4182        // day three, on a thirty-one day month: the geometry was always right
4183        // and only the label was wrong, which is why `unit` is a fact and not
4184        // presentation.
4185        let march = Track::days(Span::new(0, 31));
4186        assert_eq!(march.slots(), 31);
4187        assert_eq!(march.unit, Unit::Days);
4188
4189        let leave = Placement::new(2, 15);
4190        assert!((march.fraction(leave.at()) - 2.0 / 31.0).abs() < 0.0001);
4191        assert!((march.fraction(leave.end()) - 17.0 / 31.0).abs() < 0.0001);
4192    }
4193
4194    #[test]
4195    fn a_pane_is_looked_into_and_a_band_is_not() {
4196        assert_eq!(Region::Pane.depth(), Depth::Well);
4197        assert_eq!(Region::Modal.depth(), Depth::Raised);
4198        for r in [
4199            Region::Band,
4200            Region::Sidebar,
4201            Region::Group,
4202            Region::Split,
4203            Region::TabGroup,
4204        ] {
4205            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
4206        }
4207    }
4208
4209    #[test]
4210    fn exactly_one_region_is_opaque() {
4211        // The escape hatch is one member and stays one member. If a second
4212        // undescribed region ever appears, the description has started
4213        // conceding rather than deferring.
4214        for r in [
4215            Region::Band,
4216            Region::Sidebar,
4217            Region::Pane,
4218            Region::Group,
4219            Region::Split,
4220            Region::TabGroup,
4221            Region::Modal,
4222            // A widget is described, and that is the whole of what separates it
4223            // from a bespoke here. Both carry a name this crate never reads;
4224            // only one of them has contents under it that a renderer which does
4225            // not know the name can still walk.
4226            Region::Widget { name: "carousel" },
4227        ] {
4228            assert!(r.described(), "{r:?} should be describable");
4229        }
4230        assert!(!Region::Bespoke { name: "day-plan" }.described());
4231    }
4232
4233    #[test]
4234    fn a_picture_that_says_nothing_is_a_claim_and_not_an_oversight() {
4235        // The distinction a renderer with no graphics protocol runs on: draw
4236        // the words, or draw nothing. Standing in for a decorative rule with
4237        // the word "decoration" is worse than leaving the space empty.
4238        assert!(Image::new("The library view, mid-import").speaks());
4239        assert!(!Image::new("").speaks());
4240    }
4241
4242    #[test]
4243    fn a_caption_and_alt_text_are_not_the_same_line() {
4244        // A caption is content everybody reads; alt text stands in for the
4245        // picture. A screenshot with a caption still needs alt text.
4246        let shot = Image::new("A file list with three rows selected").caption("The library view");
4247        assert_eq!(shot.caption, Some("The library view"));
4248        assert!(shot.speaks());
4249        assert_ne!(shot.alt, shot.caption.unwrap());
4250    }
4251
4252    #[test]
4253    fn a_picture_can_say_how_much_room_to_hold() {
4254        // The whole point: a renderer reserves from the ratio, so the space is
4255        // right at any width. A fixed height would only be right at one.
4256        let shot = Image::new("a screenshot").intrinsic(5120, 3412);
4257        let e = shot.intrinsic.expect("carried");
4258        assert_eq!((e.width, e.height), (5120, 3412));
4259        assert!((e.ratio().unwrap() - 1.5006).abs() < 0.001);
4260    }
4261
4262    #[test]
4263    fn a_picture_with_no_dimensions_reserves_nothing_rather_than_guessing() {
4264        // `None` is honest: a creator upload whose size was never recorded does
4265        // not know it. A renderer must not invent one.
4266        assert_eq!(Image::new("unknown upload").intrinsic, None);
4267        assert_eq!(Extent::new(0, 10).ratio(), None);
4268        assert_eq!(Extent::new(10, 0).ratio(), None);
4269    }
4270
4271    #[test]
4272    fn a_picture_is_wanted_now_unless_the_app_says_otherwise() {
4273        // Eager is the safe default and lazy is the opt-in, because deferring
4274        // something already on screen saves nothing and moves its shift later.
4275        assert_eq!(Image::new("hero").loading, Loading::Eager);
4276        assert_eq!(Loading::default(), Loading::Eager);
4277        assert_eq!(Image::new("frame 2").lazy().loading, Loading::Lazy);
4278    }
4279
4280    #[test]
4281    fn a_picture_keeps_its_own_proportions_unless_told_otherwise() {
4282        // The default is the one that shows the whole picture at its own shape,
4283        // so a renderer ignoring Fit entirely is still right about the common
4284        // case. The shipped MNW carousel sets no object-fit at all, which is
4285        // this.
4286        assert_eq!(Image::new("a").fit, Fit::Natural);
4287        assert_eq!(Fit::default(), Fit::Natural);
4288        assert_eq!(Image::new("a").fit(Fit::Cover).fit, Fit::Cover);
4289    }
4290
4291    #[test]
4292    fn a_group_contains_a_section_without_claiming_to_be_a_pane() {
4293        // The whole of why this is a member rather than a `Pane`. A pane is
4294        // looked into and scrolls; a group is neither, and four groups inside a
4295        // settings pane described as panes are four wells inside a well.
4296        assert_eq!(Region::Pane.depth(), Depth::Well);
4297        assert_eq!(Region::Group.depth(), Depth::Flat);
4298        assert_ne!(Region::Group, Region::Pane);
4299
4300        // Described, and it carries no name: a group is a primitive every
4301        // renderer draws from scratch, which is what separates it from the two
4302        // members that do carry one.
4303        assert!(Region::Group.described());
4304        assert_eq!(Region::Group.name(), None);
4305    }
4306
4307    #[test]
4308    fn a_section_heading_names_a_block_that_now_exists() {
4309        // `Heading::Section` has said "names a block within the screen" since
4310        // 0.2.0 and there was no block. The pairing is the point, and it is the
4311        // reason a group carries no heading of its own: the heading is an
4312        // ordinary node in the body, and a group without one is legal.
4313        assert!(Heading::Section.separated());
4314        assert_eq!(Region::Group.depth(), Depth::Flat);
4315    }
4316
4317    #[test]
4318    fn a_widget_inherits_its_depth_the_way_a_bespoke_does() {
4319        // Stronger than the bespoke case: a widget is drawn by whichever
4320        // renderer recognises the name, so a depth chosen here would be this
4321        // crate deciding a carousel is raised on every host.
4322        assert_eq!(Region::Widget { name: "carousel" }.depth(), Depth::Flat);
4323        assert_eq!(Region::Widget { name: "pager" }.depth(), Depth::Flat);
4324    }
4325
4326    #[test]
4327    fn a_name_is_readable_without_asking_which_member_carried_it() {
4328        // A renderer dispatching on a name wants the string, not the member.
4329        // Writing that `matches!` at each renderer is how the two drift apart.
4330        assert_eq!(Region::Widget { name: "carousel" }.name(), Some("carousel"));
4331        assert_eq!(
4332            Region::Bespoke { name: "day-plan" }.name(),
4333            Some("day-plan")
4334        );
4335
4336        for r in [
4337            Region::Band,
4338            Region::Sidebar,
4339            Region::Pane,
4340            Region::Group,
4341            Region::Split,
4342            Region::TabGroup,
4343            Region::Modal,
4344        ] {
4345            assert_eq!(r.name(), None, "{r:?} names nothing an app chose");
4346        }
4347    }
4348
4349    #[test]
4350    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
4351        // The app owns the contents, not the placement. An app that wants its
4352        // timeline in a well frames it in a Pane.
4353        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
4354        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
4355    }
4356
4357    #[test]
4358    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
4359        // The argument the member exists for: goingson's day-plan has to be
4360        // routable, or the description covers only the boring screens and the
4361        // interesting four need a second path beside the router.
4362        let day_plan = [
4363            Region::Band,
4364            Region::Bespoke { name: "day-plan" },
4365            Region::Sidebar,
4366        ];
4367        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
4368        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
4369    }
4370
4371    #[test]
4372    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
4373        let secret = Field::new(FieldKind::Secret, "password", "Password");
4374        assert!(secret.kind.confidential());
4375        assert!(secret.kind.visible());
4376
4377        assert!(!FieldKind::Hidden.visible());
4378        // Nothing else is confidential, or the marker means nothing.
4379        for k in [
4380            FieldKind::Text,
4381            FieldKind::Number,
4382            FieldKind::Textarea,
4383            FieldKind::Select,
4384            FieldKind::Checkbox,
4385            FieldKind::Hidden,
4386        ] {
4387            assert!(!k.confidential(), "{k:?} should not be confidential");
4388        }
4389
4390        // Only a checkbox carries its own label.
4391        assert!(FieldKind::Checkbox.labels_itself());
4392        assert!(!FieldKind::Text.labels_itself());
4393    }
4394
4395    #[test]
4396    fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
4397        let text = Field::new(FieldKind::Text, "title", "Title");
4398        assert!(text.options.is_empty());
4399        assert_eq!(text.placeholder, None);
4400
4401        let sizes = [Choice::plain("small"), Choice::plain("large")];
4402        let select = Field::select("size", "Size", &sizes);
4403        assert_eq!(select.kind, FieldKind::Select);
4404        assert_eq!(select.options.len(), 2);
4405    }
4406
4407    #[test]
4408    fn a_choice_says_what_submits_and_what_is_read_apart() {
4409        // The whole reason it is two strings. `plain` is the case where they
4410        // coincide, and it is a shorthand rather than the general shape.
4411        let plain = Choice::plain("7");
4412        assert_eq!((plain.value, plain.label), ("7", "7"));
4413
4414        let spelled = Choice {
4415            value: "7",
4416            label: "One week",
4417        };
4418        assert_ne!(spelled.value, spelled.label);
4419    }
4420
4421    #[test]
4422    fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
4423        // Both offer a fixed set and both read `options`, so the two
4424        // constructors differ in exactly one thing. That one thing is the
4425        // point: a renderer decides whether the alternatives are readable
4426        // without opening anything, and it can only decide that if the
4427        // description said which question was asked.
4428        let styles = [
4429            Choice {
4430                value: "copy",
4431                label: "Copy samples in",
4432            },
4433            Choice {
4434                value: "reference",
4435                label: "Reference in place",
4436            },
4437        ];
4438        let radio = Field::radio("storage", "Storage style", &styles);
4439        let select = Field::select("storage", "Storage style", &styles);
4440
4441        assert_eq!(radio.kind, FieldKind::Radio);
4442        assert_ne!(radio.kind, select.kind);
4443        assert_eq!(radio.options, select.options);
4444        assert_eq!(
4445            Field {
4446                kind: select.kind,
4447                ..radio
4448            },
4449            select
4450        );
4451    }
4452
4453    #[test]
4454    fn exactly_the_option_taking_kinds_say_so() {
4455        // The renderers branch on this rather than on a list of their own, so
4456        // a kind added without a decision here renders its options nowhere.
4457        assert!(FieldKind::Select.offers_options());
4458        assert!(FieldKind::Radio.offers_options());
4459        for kind in [
4460            FieldKind::Text,
4461            FieldKind::Secret,
4462            FieldKind::Number,
4463            FieldKind::Email,
4464            FieldKind::Url,
4465            FieldKind::Tel,
4466            FieldKind::Textarea,
4467            FieldKind::Checkbox,
4468            FieldKind::Hidden,
4469        ] {
4470            assert!(!kind.offers_options(), "{kind:?} does not offer options");
4471        }
4472    }
4473
4474    #[test]
4475    fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
4476        // The near-miss: each option is labelled beside its own button, so a
4477        // renderer could plausibly read the group as self-labelling and drop
4478        // the question. Checkbox is the only kind that does that.
4479        assert!(!FieldKind::Radio.labels_itself());
4480        assert!(FieldKind::Checkbox.labels_itself());
4481    }
4482
4483    #[test]
4484    fn a_select_with_no_options_is_sayable() {
4485        // An app whose option list has not loaded has exactly this. Making it
4486        // unrepresentable would push the state somewhere less visible, and a
4487        // renderer drawing an empty select reports it on screen.
4488        let loading = Field::select("project", "Project", &[]);
4489        assert!(loading.options.is_empty());
4490    }
4491
4492    #[test]
4493    fn the_description_carries_the_question_and_never_the_answer() {
4494        // The line 0.8.0 drew. Placeholder and options are properties of what
4495        // is being asked; the current value is what came back, and no field
4496        // here holds one.
4497        let f = Field {
4498            placeholder: Some("yyyy-mm-dd"),
4499            ..Field::new(FieldKind::Text, "due", "Due")
4500        };
4501        assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
4502        // A placeholder is not a label, and having one does not excuse the
4503        // field from carrying the other.
4504        assert_eq!(f.label, "Due");
4505    }
4506
4507    #[test]
4508    fn a_field_reports_its_own_error_state() {
4509        let mut f = Field::new(FieldKind::Text, "title", "Title");
4510        assert!(!f.invalid());
4511        f.error = Some("Required");
4512        assert!(f.invalid());
4513    }
4514
4515    #[test]
4516    fn columns_drop_by_priority_and_never_by_position() {
4517        let cols = [
4518            Column {
4519                width: Width::Fill,
4520                priority: Priority::Essential,
4521                ..Column::new("Title")
4522            },
4523            Column {
4524                width: Width::Fixed,
4525                priority: Priority::Secondary,
4526                ..Column::new("Due")
4527            },
4528            Column {
4529                width: Width::Fixed,
4530                priority: Priority::Optional,
4531                ..Column::new("Estimate")
4532            },
4533        ];
4534
4535        // Widest: everything survives.
4536        assert_eq!(
4537            cols.iter()
4538                .filter(|c| c.kept_at(Priority::Optional))
4539                .count(),
4540            3
4541        );
4542        // Narrower: the optional column goes first.
4543        let kept: Vec<_> = cols
4544            .iter()
4545            .filter(|c| c.kept_at(Priority::Secondary))
4546            .map(|c| c.name)
4547            .collect();
4548        assert_eq!(kept, ["Title", "Due"]);
4549        // Narrowest: only what identifies the row.
4550        let kept: Vec<_> = cols
4551            .iter()
4552            .filter(|c| c.kept_at(Priority::Essential))
4553            .map(|c| c.name)
4554            .collect();
4555        assert_eq!(kept, ["Title"]);
4556    }
4557
4558    #[test]
4559    fn inserting_a_column_does_not_move_what_gets_dropped() {
4560        // The bug the ordinal form has and this form cannot: goingson hides
4561        // `nth-child(n+5)` against a seven-column table, so a column inserted
4562        // anywhere to the left silently hides a different one.
4563        let before = [
4564            Column::new("Title"),
4565            Column {
4566                width: Width::Fixed,
4567                priority: Priority::Optional,
4568                ..Column::new("Estimate")
4569            },
4570        ];
4571        let after = [
4572            Column::new("Title"),
4573            Column::new("Project"), // inserted
4574            Column {
4575                width: Width::Fixed,
4576                priority: Priority::Optional,
4577                ..Column::new("Estimate")
4578            },
4579        ];
4580
4581        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
4582            cols.iter()
4583                .filter(|c| !c.kept_at(Priority::Secondary))
4584                .map(|c| c.name)
4585                .collect()
4586        }
4587        assert_eq!(dropped(&before), ["Estimate"]);
4588        assert_eq!(dropped(&after), ["Estimate"]);
4589    }
4590
4591    #[test]
4592    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
4593        // goingson uses the tab group inside the content region rather than
4594        // instead of one, so it is not a third arrangement.
4595        let go = Arrangement::list_detail(true);
4596        let plain = Arrangement::list_detail(false);
4597        assert_ne!(go, plain);
4598        assert_ne!(go, Arrangement::sidebar_content());
4599    }
4600
4601    #[test]
4602    fn a_share_is_a_proportion_and_resolves_the_same_way_everywhere() {
4603        // The point of the member: a terminal reading columns and a webview
4604        // reading a grid honour one fact, so two hosts showing one screen agree
4605        // about its proportions.
4606        assert_eq!(Share::LIST.as_percent(), 40);
4607        assert_eq!(Share::LIST.of(100), 40);
4608        assert_eq!(
4609            Share::SIDEBAR.of(96),
4610            24,
4611            "quasi-tui's 24 columns, said as a quarter"
4612        );
4613    }
4614
4615    #[test]
4616    fn a_region_never_resolves_to_nothing() {
4617        // A region the description named should be visible. A zero-width one
4618        // reads on screen as a region that vanished, which is the hardest kind
4619        // of bug to find from what is drawn.
4620        assert_eq!(Share::percent(5).of(1), 1);
4621        assert_eq!(Share::percent(5).of(0), 1);
4622    }
4623
4624    #[test]
4625    fn a_share_outside_the_range_is_clamped_rather_than_refused() {
4626        assert_eq!(Share::percent(0), Share::percent(5));
4627        assert_eq!(Share::percent(200), Share::percent(95));
4628    }
4629
4630    #[test]
4631    fn the_share_rides_on_the_arrangement_that_knows_which_question_it_is() {
4632        // How much a sidebar takes and how much a list side takes are different
4633        // questions, and this enum is the only thing that knows which is being
4634        // asked.
4635        assert_eq!(Arrangement::sidebar_content().share(), Share::SIDEBAR);
4636        assert_eq!(Arrangement::list_detail(false).share(), Share::LIST);
4637
4638        let narrow = Arrangement::sidebar_content().with_share(Share::percent(20));
4639        assert_eq!(narrow.share(), Share::percent(20));
4640        assert!(matches!(narrow, Arrangement::SidebarContent { .. }));
4641    }
4642
4643    #[test]
4644    fn a_measure_defaults_to_the_one_53_of_69_templates_asked_for() {
4645        // The default is meaningful: a screen nobody said anything about uses
4646        // the window it was given.
4647        assert_eq!(Measure::default(), Measure::Wide);
4648        assert_eq!(Measure::Reading.as_str(), "reading");
4649    }
4650
4651    #[test]
4652    fn readiness_names_the_state_and_not_the_shimmer() {
4653        // Two members and no third. If a skeleton ever appears in this enum,
4654        // the deferral rule has been broken.
4655        assert_ne!(Readiness::Ready, Readiness::Pending);
4656    }
4657
4658    #[test]
4659    fn a_window_with_no_length_still_answers_what_it_can() {
4660        // The uncounted case is the common one, not the degenerate one: a query
4661        // that asked for 51 to learn there were more than 50 knows there are,
4662        // and not how many.
4663        let uncounted = Window::new(100, 50);
4664        assert_eq!(uncounted.index(), Some(2));
4665        assert_eq!(uncounted.windows(), None);
4666        assert!(uncounted.has_before());
4667        // Unknown length cannot rule out more, and offering a way forward that
4668        // turns out empty is the cheaper mistake.
4669        assert!(uncounted.has_after());
4670    }
4671
4672    #[test]
4673    fn a_counted_window_knows_where_it_ends() {
4674        let last = Window::new(350, 50).of(400);
4675        assert_eq!(last.index(), Some(7));
4676        assert_eq!(last.windows(), Some(8));
4677        assert!(last.has_before());
4678        assert!(!last.has_after());
4679
4680        let first = Window::new(0, 50).of(400);
4681        assert!(!first.has_before());
4682        assert!(first.has_after());
4683    }
4684
4685    #[test]
4686    fn a_window_that_does_not_divide_evenly_rounds_up() {
4687        // 401 rows in pages of 50 is eight pages and a straggler, which is nine
4688        // pages. Rounding down would make the last one unreachable.
4689        assert_eq!(Window::new(0, 50).of(401).windows(), Some(9));
4690    }
4691
4692    #[test]
4693    fn a_zero_count_answers_none_rather_than_dividing() {
4694        let empty = Window::new(0, 0).of(400);
4695        assert_eq!(empty.index(), None);
4696        assert_eq!(empty.windows(), None);
4697        // And it still clamps rather than panicking.
4698        assert_eq!(Window::new(900, 0).of(400).clamped().from, 399);
4699    }
4700
4701    #[test]
4702    fn a_window_past_the_end_clamps_inside_rather_than_vanishing() {
4703        // `Slot::current`'s reasoning, one layer down: a description pointing
4704        // past the end is a host bug, and answering it by drawing nothing
4705        // reports a region that vanished.
4706        assert_eq!(Window::new(900, 50).of(400).clamped().from, 350);
4707        // Nothing to clamp against when the length is unknown.
4708        assert_eq!(Window::new(900, 50).clamped().from, 900);
4709    }
4710
4711    #[test]
4712    fn a_carousel_frame_is_a_window_of_one() {
4713        // The shape a carousel instantiates. Same code as a paged list, which is
4714        // the whole reason `Window` exists rather than two copies of it.
4715        let third = Window::frame(2, 5);
4716        assert_eq!(third.index(), Some(2));
4717        assert_eq!(third.windows(), Some(5));
4718        assert!(third.has_before());
4719        assert!(third.has_after());
4720
4721        let last = Window::frame(4, 5);
4722        assert!(!last.has_after());
4723    }
4724
4725    #[test]
4726    fn numbered_pages_read_from_one_and_load_more_has_no_page() {
4727        // The page number is read aloud, so it is one-based; `Window::index` is
4728        // the zero-based form for indexing.
4729        let third = Paging::pages(100, 50).of(400);
4730        assert_eq!(third.page(), Some(3));
4731        assert_eq!(third.pages_total(), Some(8));
4732        assert_eq!(third.total(), Some(400));
4733        assert!(third.has_previous());
4734        assert!(third.has_more());
4735
4736        // Load-more grew a window from the start, so "page 2" would name
4737        // nothing and the type says so rather than inventing one.
4738        let grown = Paging::more(150).of(400);
4739        assert_eq!(grown.page(), None);
4740        assert_eq!(grown.pages_total(), None);
4741        assert_eq!(grown.shown(), 150);
4742        assert!(!grown.has_previous());
4743        assert!(grown.has_more());
4744    }
4745
4746    #[test]
4747    fn an_uncounted_paging_offers_forward_and_admits_no_total() {
4748        // What a host that will not pay for a COUNT describes. `None` here is
4749        // permanent: a total arriving later would widen the text that prints it,
4750        // which is the reflow "first paint is final paint" forbids.
4751        let feed = Paging::more(50);
4752        assert_eq!(feed.total(), None);
4753        assert_eq!(feed.pages_total(), None);
4754        assert_eq!(feed.remaining(), None);
4755        assert!(feed.has_more());
4756    }
4757
4758    #[test]
4759    fn what_is_left_is_derived_and_never_underflows() {
4760        assert_eq!(Paging::more(150).of(400).remaining(), Some(250));
4761        assert_eq!(Paging::pages(350, 50).of(400).remaining(), Some(0));
4762        // A host that overshot its own total gets zero rather than a wrapped
4763        // usize, which would print as "18446744073709551516 remaining".
4764        assert_eq!(Paging::more(500).of(400).remaining(), Some(0));
4765    }
4766}