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