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