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