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