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