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