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