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