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