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