Skip to main content

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** is absent on purpose rather than pending: neither app has a
44//! shared story, and a schema describing fields but not constraints acquires a
45//! constraint layer per app, which is how the divergence this crate exists to
46//! end got started.
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//! # Where the description stops
85//!
86//! The bespoke widgets, a day-plan timeline and a kanban board and a calendar,
87//! are not describable here and will not become describable. A description
88//! expressive enough to produce a timeline is a widget library wearing a
89//! description's name. Generate the boring 80% so the bespoke 20% gets the
90//! attention.
91//!
92//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
93//! description names the *place* and the app owns the contents, so a screen
94//! containing a timeline is still a whole screen and still routable. Without
95//! it, the four goingson screens that make the app worth using would need a
96//! second, undescribed path beside the router, and two paths is how a
97//! vocabulary starts drifting from its app again.
98
99#![forbid(unsafe_code)]
100
101/// A colour intent this crate refers to but never resolves.
102///
103/// The string is the token name `makeover` publishes, so a renderer can look
104/// it up without this crate knowing what colour came back.
105pub trait Intent {
106    /// The `makeover` intent token this resolves against.
107    fn token(self) -> &'static str;
108}
109
110/// Which way the light falls across a two-tone edge.
111///
112/// The whole content of a bevel, once colour and thickness are deferred. The
113/// light is always assumed to come from the top left: every consumer measured
114/// agreed on that and none of them ever varied it, so it is an invariant here
115/// rather than a parameter.
116///
117/// # The two corners that belong to both edges
118///
119/// Top-right and bottom-left are where the lit run meets the shaded one, and
120/// the description's claim is that they belong to *both*. How a renderer says
121/// that is its own business, because the answer is bounded by resolution and
122/// not by taste:
123///
124/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
125///   to one tone thickens that edge by a cell and reads as one run overrunning
126///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
127///   splits it and recovers real information. Its box-drawing fallback cannot:
128///   a single stroke has no half to give, so there both corners go to dark.
129/// - A pixel bevel is a one-point stroke by default, which makes the corner a
130///   one-point square. There is nothing to divide — a diagonal seam across one
131///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
132///   already produces. So `makeover-immediate` mitres and is *not* diverging;
133///   it is the same rule at a resolution where the split degenerates.
134///
135/// Stated here so the difference reads as a decision rather than as drift. A
136/// renderer with room to divide the corner should; one without should mitre or
137/// pick the shaded tone, and neither is a bug.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub enum Bevel {
140    /// Lit from the top left: light on top and left, dark on bottom and right.
141    Raised,
142    /// The same edge inverted, which is also the pressed state of anything
143    /// that draws itself [`Bevel::Raised`].
144    Inset,
145}
146
147impl Bevel {
148    /// The edge intents, as `(top_left, bottom_right)`.
149    ///
150    /// Split out from any painting because the inversion *is* the idea, and
151    /// it is the one part every renderer implements identically.
152    #[must_use]
153    pub const fn edges(self) -> (Edge, Edge) {
154        match self {
155            Self::Raised => (Edge::Light, Edge::Dark),
156            Self::Inset => (Edge::Dark, Edge::Light),
157        }
158    }
159
160    /// Pressing inverts. A raised control reads as inset while held.
161    ///
162    /// Stated here rather than left to each consumer because a cascade can
163    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
164    /// resolves this per call site, eighteen times.
165    #[must_use]
166    pub const fn pressed(self) -> Self {
167        match self {
168            Self::Raised => Self::Inset,
169            Self::Inset => Self::Raised,
170        }
171    }
172}
173
174/// One side of a bevel, named by the intent it takes.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub enum Edge {
177    /// The lit side.
178    Light,
179    /// The shadowed side.
180    Dark,
181}
182
183impl Intent for Edge {
184    fn token(self) -> &'static str {
185        match self {
186            Self::Light => "bevel-light",
187            Self::Dark => "bevel-dark",
188        }
189    }
190}
191
192/// A surface intent a region is filled with.
193///
194/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
195/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
196/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
197/// `makeover-immediate` at compile time and left neither able to move until
198/// both published. The vocabulary exists to grow and the renderers exist to
199/// disagree about how much of it they answer, so growth must not be a
200/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
201/// resolved through a fallible lookup, and a missing intent is answered with
202/// structure rather than with a substituted colour.
203///
204/// [`Sunken`]: Fill::Sunken
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[non_exhaustive]
207pub enum Fill {
208    /// The page behind everything.
209    Page,
210    /// A surface lifted off the page: cards, controls, menus, toasts.
211    Raised,
212    /// A surface floating above the page rather than resting on it.
213    Overlay,
214    /// The inside of a well.
215    Well,
216    /// A surface set back from the one it sits on, by colour and nothing else.
217    ///
218    /// Not a well. A well is a hole with an edge, and the two are authored in
219    /// opposite directions: `makeover` derives `surface-well` by inverting
220    /// against the theme's own content colour, while `surface-sunken` is
221    /// authored and free to sit darker than raised (goingson's does). Naming
222    /// only the well left the recessed-with-no-edge surface unsayable, which is
223    /// what an unchosen tab is: it recedes so the chosen one can come forward,
224    /// and it carries no bevel of its own.
225    ///
226    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
227    /// and could not delete the line because no member described it.
228    Sunken,
229}
230
231// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
232// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
233// had something to paint. makeover-tui found that wrong within a day: page is
234// the surface a well is usually cut into, so on a terminal that substitution
235// produces exactly the invisibility it was meant to prevent, and the right
236// answer there is a drawn edge rather than a different colour.
237//
238// Substituting one intent for another is renderer policy. The description says
239// what the region is and stops.
240
241impl Intent for Fill {
242    fn token(self) -> &'static str {
243        match self {
244            Self::Page => "surface-page",
245            Self::Raised => "surface-raised",
246            Self::Overlay => "surface-overlay",
247            Self::Well => "surface-well",
248            Self::Sunken => "surface-sunken",
249        }
250    }
251}
252
253/// How a region sits relative to the surface behind it.
254///
255/// Fill and bevel are named together because naming them apart is what let
256/// them disagree. Every consumer measured had at least one region carrying a
257/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
258/// and recorded the bug in its doc comment, and Balanced Breakfast still had
259/// twelve of them a year later. A single name for the pair makes that
260/// unrepresentable.
261/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
262/// release: a depth this renderer has no drawing for should cost it a
263/// wildcard arm, not a compile error and a wait on someone else's publish.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265#[non_exhaustive]
266pub enum Depth {
267    /// Level with its surroundings. No edge.
268    Flat,
269    /// A card laid on the panel it sits in.
270    Raised,
271    /// A hole in the panel, with content down inside it. For anything the
272    /// user looks *into*: a table body, a tag tree, a text field.
273    Well,
274    /// Set back from what it sits on, by colour alone. No edge.
275    ///
276    /// The one member carrying a fill without a bevel, so a renderer cannot
277    /// assume the two arrive together. That is deliberate and it is still the
278    /// pairing rule: both halves come off the same `Depth`, so they cannot
279    /// disagree, and here one half is legitimately absent.
280    ///
281    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
282    /// Recessed and level-with are different claims, and only one of them
283    /// needs a colour.
284    Sunken,
285}
286
287impl Depth {
288    /// The edge this depth is drawn with, if it has one.
289    #[must_use]
290    pub const fn bevel(self) -> Option<Bevel> {
291        match self {
292            // Sunken joins Flat here, for the opposite reason: Flat has no edge
293            // because nothing separates it from its surroundings, and Sunken has
294            // none because its colour is already doing the separating.
295            Self::Flat | Self::Sunken => None,
296            Self::Raised => Some(Bevel::Raised),
297            Self::Well => Some(Bevel::Inset),
298        }
299    }
300
301    /// The surface this depth is filled with.
302    ///
303    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
304    /// which is the difference between level-with and painted-the-same-colour.
305    #[must_use]
306    pub const fn fill(self) -> Option<Fill> {
307        match self {
308            Self::Flat => None,
309            Self::Raised => Some(Fill::Raised),
310            Self::Well => Some(Fill::Well),
311            Self::Sunken => Some(Fill::Sunken),
312        }
313    }
314
315    /// Pressing a raised region reads as a well, and nothing else moves.
316    #[must_use]
317    pub const fn pressed(self) -> Self {
318        match self {
319            Self::Raised => Self::Well,
320            other => other,
321        }
322    }
323}
324
325/// An interaction state a region can be in, beside whatever [`Depth`] it is.
326///
327/// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
328/// and a disabled field is still a [`Depth::Well`], so folding either member
329/// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
330/// something that is not a depth, and would leave disabled-button and
331/// disabled-field sharing one variant that cannot tell them apart.
332///
333/// # Why hover and pressed are not members
334///
335/// The line is whether every renderer has the state to express, not whether CSS
336/// does. Hover is renderer policy and `makeover-webview` says so in its own
337/// header: a terminal and an immediate-mode painter have no pointer hovering
338/// over anything, and pressed already arrives through [`Bevel::pressed`] and
339/// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
340/// rather than a separate condition.
341///
342/// Focus and disabled are different in kind. A TUI has a focused widget and a
343/// greyed-out one; so does egui. Both were unsayable here, so all three webview
344/// consumers supplied them from outside the primitive by out-specifying rules
345/// they did not own: goingson alone carries 19 of them, and the MNW server
346/// another 21. That is the divergence this crate exists to end, arriving one
347/// layer down.
348///
349/// # The principle this encodes
350///
351/// A primitive owns every state it implies. A renderer that emits a hover rule
352/// for a thing owes disabled, focus and the capability answer for that same
353/// thing, because anything less exports the completion work to N consumers who
354/// will each do it differently.
355///
356/// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
357/// must not be a lockstep event across the three renderers.
358#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
359#[non_exhaustive]
360pub enum State {
361    /// Keyboard focus, as distinct from the pointer having landed on something.
362    ///
363    /// One ring, not one per primitive. Where the ring sits is [`Depth`]'s
364    /// question and not a per-component choice: a well takes it inside its own
365    /// edge and a raised surface takes it outside. That is one decision with
366    /// two renderings rather than one decision per component, which is how the
367    /// three apps ended up with three rings.
368    Focus,
369    /// Present, visible, and not answering.
370    ///
371    /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
372    /// control keeps the surface it always had and stops responding, so what
373    /// changes is its content and its interactivity rather than what it is.
374    Disabled,
375}
376
377impl State {
378    /// Whether a region in this state stops answering the pointer.
379    ///
380    /// Stated in the description rather than left to each renderer, on the same
381    /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
382    /// immediate-mode renderer resolves it per call site, so leaving it unsaid
383    /// means resolving it once per consumer and disagreeing.
384    #[must_use]
385    pub const fn suppresses_interaction(self) -> bool {
386        match self {
387            Self::Disabled => true,
388            Self::Focus => false,
389        }
390    }
391}
392
393impl Intent for State {
394    fn token(self) -> &'static str {
395        match self {
396            // Already derived by `makeover` from `action.primary`, and unused
397            // until now for the same reason `hover-surface` was: nothing
398            // emitted the rule that would consume it.
399            Self::Focus => "focus-ring",
400            // Reusing the muted content intent rather than minting a
401            // `disabled` colour. Disabled is a reduction and not a status, and
402            // `makeover-webview`'s progress rules already record the reading
403            // that `content-muted` is what disabled looks like.
404            Self::Disabled => "content-muted",
405        }
406    }
407}
408
409/// What a region is saying, when it is saying something.
410///
411/// The one intent family shared by badges, notices and nothing else. Kept
412/// separate from [`Fill`] because a surface is where a thing sits and a tone is
413/// what it means, and the three apps agree on the four statuses:
414/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
415/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
416/// `.toast.error` in Balanced Breakfast.
417///
418/// The per-tag palette (`category-one` through `category-six`) is deliberately
419/// not here. Which colour a *particular* tag takes is app domain, and both
420/// webview apps already carry it as a `data-color` attribute.
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
422pub enum Tone {
423    /// No status. Reads as ordinary de-emphasised content.
424    Neutral,
425    /// Something worth knowing and nothing to do about it.
426    Info,
427    /// Something finished and it worked.
428    Success,
429    /// Something the user should look at before continuing.
430    Warning,
431    /// Something broken, or something about to be destroyed.
432    Danger,
433}
434
435impl Intent for Tone {
436    fn token(self) -> &'static str {
437        match self {
438            // Neutral has no status token of its own. It takes the muted
439            // content intent, which is what both webview apps already spell as
440            // `data-color="muted"`.
441            Self::Neutral => "content-muted",
442            Self::Info => "info",
443            Self::Success => "success",
444            Self::Warning => "warning",
445            Self::Danger => "danger",
446        }
447    }
448}
449
450/// A small labelled thing that sits inside something else.
451///
452/// Two members, because the three apps drew three taxonomies and only one line
453/// runs through all of them: does it answer a click. audiofiles has
454/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
455/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
456/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
457/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
458/// to decide which of the two it always was.
459///
460/// The evidence that a chip is a real concept rather than a badge with a
461/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
462/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
463/// holds itself down", which is exactly what [`Depth::pressed`] already says.
464#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
465pub enum Token {
466    /// Non-interactive status or count. Answers no click.
467    Badge,
468    /// An interactive or removable token. Answers a click, and latches if it
469    /// stands for a filter that is either on or off.
470    Chip {
471        /// Whether it carries its own remove affordance.
472        removable: bool,
473    },
474}
475
476impl Token {
477    /// Whether this answers a click.
478    ///
479    /// The whole difference between the two members, and the reason a renderer
480    /// with no hover (a touch surface, a terminal) can still tell them apart.
481    #[must_use]
482    pub const fn interactive(self) -> bool {
483        matches!(self, Self::Chip { .. })
484    }
485
486    /// How it sits, given whether it is currently latched down.
487    ///
488    /// A badge is flat: it is a label, and giving it an edge would say it can
489    /// be pressed. A chip is raised, and inset while latched.
490    #[must_use]
491    pub const fn depth(self, latched: bool) -> Depth {
492        match self {
493            Self::Badge => Depth::Flat,
494            Self::Chip { .. } if latched => Depth::Well,
495            Self::Chip { .. } => Depth::Raised,
496        }
497    }
498}
499
500/// Something the app is telling the user, unprompted.
501///
502/// Two concepts, not one with a placement. They differ in more than where they
503/// sit: a toast is transient, stacked and self-dismissing, and a banner is
504/// persistent, in flow, one per region, and dismissed by fixing the condition
505/// it reports. Folding them into one member with a placement parameter would
506/// make lifetime, stacking and dismissal all placement-dependent, which is the
507/// description leaking renderer policy.
508///
509/// All three apps have banners: `info_banner` and `warning_banner` in
510/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
511/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
512/// webview apps also have toasts. So neither member is speculative, and no app
513/// gains a concept it lacks except audiofiles, whose renderer may legitimately
514/// decline to draw a toast at all.
515#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
516pub enum Notice {
517    /// Transient, stacked, dismisses itself.
518    Toast,
519    /// Persistent, in flow, one per region, dismissed by fixing the cause.
520    Banner,
521}
522
523impl Notice {
524    /// Whether it goes away on its own.
525    #[must_use]
526    pub const fn transient(self) -> bool {
527        matches!(self, Self::Toast)
528    }
529
530    /// How it sits.
531    ///
532    /// A toast floats above the page rather than resting on it, which is
533    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
534    /// flow. Both are raised, and they are raised off different things.
535    #[must_use]
536    pub const fn fill(self) -> Fill {
537        match self {
538            Self::Toast => Fill::Overlay,
539            Self::Banner => Fill::Raised,
540        }
541    }
542}
543
544/// The parts of a list row.
545///
546/// Four, taken from Balanced Breakfast, which is the only consumer that had all
547/// of them (`row-primary`, `row-secondary`, `row-meta`, `row-actions`).
548/// audiofiles has two and no slot structure at all, so it gains meta and
549/// actions as real work rather than a rename; goingson moves off
550/// `task-row` / `task-cell`.
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
552pub enum RowPart {
553    /// The thing itself. What the row is called.
554    Primary,
555    /// Supporting text under the primary.
556    Secondary,
557    /// A short trailing fact: a count, a size, a date.
558    Meta,
559    /// Controls that act on this row.
560    Actions,
561}
562
563impl RowPart {
564    /// Whether the part stays hidden until the row is hovered or focused.
565    ///
566    /// Behaviour of the part, not app policy: Balanced Breakfast and goingson
567    /// grew the same hover-reveal on their actions independently and neither
568    /// applies it to anything else.
569    ///
570    /// A renderer with no hover shows it always. That is a renderer decision
571    /// and this returning `true` does not forbid it.
572    #[must_use]
573    pub const fn revealed_on_hover(self) -> bool {
574        matches!(self, Self::Actions)
575    }
576
577    /// The content intent the part takes.
578    #[must_use]
579    pub const fn intent(self) -> &'static str {
580        match self {
581            Self::Primary => "content",
582            Self::Secondary => "content-secondary",
583            Self::Meta => "content-muted",
584            // Actions carry controls rather than text, so they inherit.
585            Self::Actions => "content",
586        }
587    }
588}
589
590/// How far down the heading tree a title sits.
591///
592/// Three, and only the three that are actually headings. The bands those used
593/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
594/// and `.detail-header`) are arrangement, not type, and live at
595/// [`Region::Band`]. One of them contains no text at all.
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
597pub enum Heading {
598    /// Names the whole screen. One per screen.
599    Page,
600    /// Names a block within the screen.
601    Section,
602    /// Names a sub-block inside an already-named section.
603    Subsection,
604}
605
606impl Heading {
607    /// Whether a rule follows the heading.
608    ///
609    /// audiofiles' `section_header` draws a separator and its
610    /// `subsection_label` deliberately does not, which is the only thing
611    /// distinguishing the two once weight and colour are deferred.
612    #[must_use]
613    pub const fn separated(self) -> bool {
614        matches!(self, Self::Section)
615    }
616}
617
618/// A control that picks between things.
619///
620/// Three, because three distinct behaviours are in play and collapsing any two
621/// loses something. A segmented control picks a value; a tab picks a pane; a
622/// toggle picks nothing and simply holds itself on or off.
623#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
624pub enum Selector {
625    /// Exactly one of N, and the options abut.
626    Segmented,
627    /// Independent on or off, on its own.
628    Toggle,
629    /// Navigation between panes. The folder semantic.
630    Tabs,
631}
632
633impl Selector {
634    /// How the chosen option sits.
635    ///
636    /// Held in for a segmented control and a toggle, which is the same shape
637    /// pressing produces and the whole economy of the idiom: one appearance,
638    /// two reasons to wear it. A tab is the exception, because the selected
639    /// folder tab comes *forward* to join the pane it opens.
640    #[must_use]
641    pub const fn chosen(self) -> Depth {
642        match self {
643            Self::Segmented | Self::Toggle => Depth::Well,
644            Self::Tabs => Depth::Raised,
645        }
646    }
647
648    /// How the options that were *not* picked sit.
649    ///
650    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
651    /// option falling through to [`Depth::Flat`], which says it is level with
652    /// the strip it sits in, and no renderer emitted anything for it. That is
653    /// wrong in both directions and goingson proved it: its unchosen tabs are
654    /// recessed by hand, and being recessed is *why* the chosen one reads as
655    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
656    /// drawn on the strip's own colour, which is a much weaker folder effect
657    /// than the contrast the idiom is named after.
658    ///
659    /// Each member is the inverse of its chosen state, which is the whole
660    /// content of "picked" once colour is deferred:
661    ///
662    /// - Tabs recede, so the chosen one comes forward.
663    /// - A segment and a toggle stand up, so the chosen one is held in.
664    #[must_use]
665    pub const fn unchosen(self) -> Depth {
666        match self {
667            Self::Tabs => Depth::Sunken,
668            Self::Segmented | Self::Toggle => Depth::Raised,
669        }
670    }
671
672    /// Whether the options touch.
673    ///
674    /// The gap is the entire difference between a segmented control and a row
675    /// of buttons that happen to sit near each other, which is what audiofiles'
676    /// `segmented_control` says in its own comment and why it zeroes the
677    /// spacing by hand.
678    #[must_use]
679    pub const fn abutting(self) -> bool {
680        matches!(self, Self::Segmented | Self::Tabs)
681    }
682}
683
684/// Whether the content of a region has arrived.
685///
686/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
687/// nothing at all is renderer policy, the same class of decision that got
688/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
689/// each grew a skeleton with differently-named parts; both keep them, as the
690/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
691/// and needs none, because an immediate-mode renderer simply repaints.
692#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
693pub enum Readiness {
694    /// The content is here.
695    Ready,
696    /// The content is on its way.
697    Pending,
698}
699
700/// A named part of a screen.
701///
702/// The thing `makeover-geometry` deliberately does not name: it names the space
703/// *between* things by relationship, and nothing named the things. Six named
704/// members, taken from what the two webview apps actually use, plus
705/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
706/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
707/// this layer is absent rather than divergent, which makes it the cheapest of
708/// the schemas to add and the easiest to over-build.
709#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
710pub enum Region<'a> {
711    /// A full-width strip with a title slot and an actions cluster, either of
712    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
713    /// `.header` and `.detail-header` are all this, differing only in which
714    /// slots they fill.
715    Band,
716    /// A persistent column beside the content, holding navigation.
717    Sidebar,
718    /// A region of content with its own scroll.
719    Pane,
720    /// Two panes side by side, where the left chooses what the right shows.
721    Split,
722    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
723    TabGroup,
724    /// Content over a scrim, taking input until dismissed.
725    Modal,
726    /// A region this crate names the *place* of and nothing else. The app owns
727    /// what goes in it.
728    ///
729    /// The escape hatch, and the thing that keeps the description honest about
730    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
731    /// paint interaction over the timeline are not describable here and are not
732    /// going to become describable: a description expressive enough to produce
733    /// a timeline is a widget library wearing a description's name.
734    ///
735    /// But a screen containing one still has to be a screen. Without this
736    /// member the description covers only the boring screens, and the four that
737    /// make goingson worth using would need a second, undescribed path beside
738    /// the router. Two paths is how the vocabulary starts drifting from the app
739    /// again, which is the exact failure this crate exists to end.
740    ///
741    /// So the description says "a thing called `day-plan` goes here" and stops.
742    /// The name is opaque: this crate never interprets it, and no renderer is
743    /// expected to know what it means beyond handing the space over.
744    Bespoke {
745        /// What the app calls it. Never interpreted here.
746        name: &'a str,
747    },
748}
749
750impl Region<'_> {
751    /// How the region sits on what is behind it.
752    #[must_use]
753    pub const fn depth(self) -> Depth {
754        match self {
755            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
756            // A pane is looked into, the same as a table body or a tag tree.
757            Self::Pane => Depth::Well,
758            Self::Modal => Depth::Raised,
759            // Flat because it inherits: a bespoke region takes the depth of
760            // whatever frames it. An app that wants its timeline in a well puts
761            // it in a `Pane`, which composes rather than adding a knob here.
762            Self::Bespoke { .. } => Depth::Flat,
763        }
764    }
765
766    /// Whether this crate can say anything about the region's contents.
767    ///
768    /// A renderer walks the description and hands every region it understands
769    /// to the right drawing code. This is how it tells the two apart, and the
770    /// reason it is a method rather than a `matches!` at each renderer: there
771    /// is exactly one opaque member and there should stay exactly one.
772    #[must_use]
773    pub const fn described(self) -> bool {
774        !matches!(self, Self::Bespoke { .. })
775    }
776}
777
778/// How a screen is laid out.
779///
780/// Two, and the second is not a variant of the first. goingson is list-detail,
781/// Balanced Breakfast is sidebar plus content, and neither app has a third.
782/// The tab group is a modifier rather than a member, because goingson uses it
783/// *inside* the same content region rather than instead of one.
784///
785/// This exists at all because the router has to be able to express a screen
786/// rather than only a control. Discovering the arrangement layer missing after
787/// the renderers exist is a redesign; naming two now is a morning.
788#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
789pub enum Arrangement {
790    /// A list that chooses what the detail beside it shows.
791    ListDetail {
792        /// Whether the detail side is a [`Region::TabGroup`].
793        tabbed: bool,
794    },
795    /// Navigation down the side, content filling the rest.
796    SidebarContent,
797}
798
799/// What kind of value a form field takes.
800///
801/// The union of the two vocabularies that diverged, which is what triggered
802/// this crate. They have since converged on their own: both apps now have a
803/// `renderFormField` emitting the same anatomy, and what is left differing is
804/// the kind set, the error shape, and whether the return is a string or a node.
805///
806/// Validation is deliberately absent. Neither app has a shared story (goingson
807/// validates after collecting the form data, with per-field transform hooks;
808/// Balanced Breakfast has `required` and nothing else), and a schema that
809/// describes fields but not constraints acquires a constraint layer per app,
810/// which is exactly how the current divergence started. Naming it absent is a
811/// decision; leaving it unmentioned would not be.
812/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
813/// the set keeps growing, so growth must not be a lockstep event. Email, Url
814/// and Tel arriving in 0.5.0 is the second growth in two releases.
815#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
816#[non_exhaustive]
817pub enum FieldKind {
818    /// A single line of text.
819    Text,
820    /// A single line of text that must never be echoed, logged or round-tripped
821    /// through anything that might persist it.
822    Secret,
823    /// A number.
824    Number,
825    /// An email address.
826    ///
827    /// Distinct from [`Text`](Self::Text) because the distinction is not
828    /// decoration: a webview renderer emits `type="email"`, which on a touch
829    /// device changes the keyboard that appears and turns on the platform's own
830    /// validation. goingson ships to iOS, so collapsing this into text costs a
831    /// keyboard with no `@` on it.
832    ///
833    /// Added 0.5.0, from goingson's contact form.
834    Email,
835    /// A URL. Same reasoning as [`Email`](Self::Email).
836    ///
837    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
838    Url,
839    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
840    /// clearest case of it: the keyboard is a numeric pad rather than letters.
841    ///
842    /// Added 0.5.0, from goingson's contact-phone form.
843    Tel,
844    /// Several lines of text.
845    Textarea,
846    /// One of a fixed set, offered behind a control that shows one at a time.
847    Select,
848    /// One of a fixed set, with every option on screen at once.
849    ///
850    /// Not a presentation of [`Select`](Self::Select), which is the reading to
851    /// resist: what differs is a property of the *question*. A choice that is
852    /// consequential or irreversible has to be readable without opening
853    /// anything, because a closed control shows one option and hides the rest,
854    /// and the one it shows is whichever was current before the user had read
855    /// the alternatives. audiofiles asks whether a library copies samples into
856    /// its store or references them where they lie — which cannot be changed
857    /// afterwards — and had already promoted that out of a checkbox by hand,
858    /// with a comment giving this reason, before the description could say it.
859    ///
860    /// It is also the one HTML input type this enum was missing. Everything
861    /// else here is an `<input type=...>`, a `<select>` or a `<textarea>`, and
862    /// the hole was `radio`.
863    ///
864    /// Added 0.8.1, from audiofiles' Add Library form.
865    Radio,
866    /// On or off.
867    Checkbox,
868    /// Carried through the form and never shown.
869    Hidden,
870}
871
872impl FieldKind {
873    /// Whether the field is drawn at all.
874    #[must_use]
875    pub const fn visible(self) -> bool {
876        !matches!(self, Self::Hidden)
877    }
878
879    /// Whether the value must be kept out of logs and diagnostics.
880    #[must_use]
881    pub const fn confidential(self) -> bool {
882        matches!(self, Self::Secret)
883    }
884
885    /// Where the field's own label sits.
886    ///
887    /// A checkbox labels itself on the right of the box; everything else takes
888    /// a label above. Both webview apps already do this and both special-case
889    /// it inline, which is the tell that it belongs in the description.
890    ///
891    /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
892    /// naming: its *options* each label themselves, but the field still asks a
893    /// question above them, so the group takes a label like everything else.
894    #[must_use]
895    pub const fn labels_itself(self) -> bool {
896        matches!(self, Self::Checkbox)
897    }
898
899    /// Whether the kind reads [`Field::options`].
900    ///
901    /// Two kinds do, so the pair is named once here rather than spelled out at
902    /// each renderer and again in [`Field::options`]' own doc, where "every
903    /// kind but `Select`" was true for exactly one release. A third
904    /// option-taking kind should land here and nowhere else.
905    #[must_use]
906    pub const fn offers_options(self) -> bool {
907        matches!(self, Self::Select | Self::Radio)
908    }
909}
910
911/// One option offered by a field [`FieldKind::offers_options`] accepts.
912///
913/// Two strings, because the submitted value and the read label are different
914/// facts and every renderer that has tried to collapse them has had to
915/// un-collapse them later. `makeover-webview` invented this shape writing its
916/// form emitter and it is taken here unchanged; moving it down rather than
917/// re-deriving it is the point, since the second and third renderers were each
918/// going to arrive at a near-miss of it.
919#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
920pub struct Choice<'a> {
921    /// What is submitted.
922    pub value: &'a str,
923    /// What is read.
924    pub label: &'a str,
925}
926
927impl<'a> Choice<'a> {
928    /// An option whose submitted value is also its label.
929    #[must_use]
930    pub const fn plain(value: &'a str) -> Self {
931        Self {
932            value,
933            label: value,
934        }
935    }
936}
937
938/// One field of a form.
939///
940/// Borrowed rather than owned: a description is built, read once by a renderer,
941/// and dropped. Nothing here outlives the screen it describes.
942///
943/// # What it carries, and what it does not
944///
945/// Stated here so the next renderer does not re-ask, which is what the first
946/// two both did. It carries everything a renderer needs to *draw* the field:
947/// its kind, what it is called, what it is asked for, its standing help, what
948/// is wrong with it now, whether it is compulsory, whether it hides behind a
949/// disclosure, its ghost text, and the options it offers.
950///
951/// It does not carry the **current value**, and it is not going to. That is the
952/// one thing here that is genuinely renderer state: a webview reads it back out
953/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
954/// and writes through it, and a terminal keeps an edit buffer. A description
955/// that carried the value would have to carry a way to write it back, at which
956/// point it is a form model and no longer a description.
957///
958/// **Validation** is absent for the reason [`FieldKind`] records: [`error`] is
959/// the *result* of validating, supplied by whoever validated. Nothing here
960/// decides that a value is wrong.
961///
962/// [`error`]: Field::error
963#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
964pub struct Field<'a> {
965    /// What kind of value it takes.
966    pub kind: FieldKind,
967    /// The name the value is submitted under.
968    pub name: &'a str,
969    /// What the user is asked for.
970    pub label: &'a str,
971    /// Standing help, shown whether or not anything is wrong.
972    pub hint: Option<&'a str>,
973    /// What is currently wrong with the value.
974    pub error: Option<&'a str>,
975    /// Ghost text shown while the field is empty.
976    ///
977    /// User-facing text, and it sits with `label` and `hint` rather than with
978    /// the value because it is a property of the *question* and not of the
979    /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
980    /// reason and it was not a reading on where it belonged: adding a field to
981    /// a published struct is a breaking change.
982    ///
983    /// Not a substitute for a label. A field labelled only by its placeholder
984    /// loses its label the moment anything is typed, and no renderer here can
985    /// make that not happen, so the description keeps both.
986    pub placeholder: Option<&'a str>,
987    /// The options offered, in the order they are offered.
988    ///
989    /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
990    /// described with no options is sayable on purpose: it is what an app with
991    /// an unfinished-loading option list actually has, and a renderer showing
992    /// an empty control says so on screen rather than in a log.
993    ///
994    /// Which option is *current* is not here. That is the value, and the value
995    /// is renderer state.
996    pub options: &'a [Choice<'a>],
997    /// Whether the form refuses to submit without it.
998    pub required: bool,
999    /// Whether the field lives behind a "more options" disclosure.
1000    pub extended: bool,
1001}
1002
1003impl<'a> Field<'a> {
1004    /// A plain required-nothing field of the given kind.
1005    #[must_use]
1006    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
1007        Self {
1008            kind,
1009            name,
1010            label,
1011            hint: None,
1012            error: None,
1013            placeholder: None,
1014            options: &[],
1015            required: false,
1016            extended: false,
1017        }
1018    }
1019
1020    /// A select offering the given options.
1021    ///
1022    /// One of the two kinds under-described by [`Field::new`], so it gets a
1023    /// constructor rather than leaving every call site to remember that a
1024    /// select with an empty `options` renders as an empty select.
1025    #[must_use]
1026    pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1027        Self::offering(FieldKind::Select, name, label, options)
1028    }
1029
1030    /// A radio group offering the given options.
1031    ///
1032    /// The other. Same hazard as [`select`](Self::select) and a worse one: a
1033    /// radio group with no options draws nothing at all, so a call site that
1034    /// forgot them has an empty rectangle rather than a visibly empty control.
1035    #[must_use]
1036    pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1037        Self::offering(FieldKind::Radio, name, label, options)
1038    }
1039
1040    /// The shared body of the two constructors that take options.
1041    ///
1042    /// Private, and keyed on the kind rather than exposed, because the two
1043    /// public names are the point: a call site says which question it is
1044    /// asking, not which flag it is setting.
1045    const fn offering(
1046        kind: FieldKind,
1047        name: &'a str,
1048        label: &'a str,
1049        options: &'a [Choice<'a>],
1050    ) -> Self {
1051        Self {
1052            options,
1053            ..Self::new(kind, name, label)
1054        }
1055    }
1056
1057    /// Whether the field is currently reporting a problem.
1058    ///
1059    /// Read this rather than testing `error.is_some()` at each renderer: the
1060    /// error state has to mark the field's whole group and not only the
1061    /// message, because a renderer with no descendant selectors (egui, a
1062    /// terminal) cannot find the group from the message. goingson already marks
1063    /// the group and Balanced Breakfast does not, so goingson's shape is the
1064    /// one taken here.
1065    #[must_use]
1066    pub const fn invalid(&self) -> bool {
1067        self.error.is_some()
1068    }
1069}
1070
1071/// How much room a column asks for.
1072///
1073/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
1074/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
1075/// only the first three words of that survive deferral.
1076/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
1077/// renderer matches on this and a vocabulary that grows must not break every
1078/// renderer when it does.
1079#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1080#[non_exhaustive]
1081pub enum Width {
1082    /// Takes what it needs and no more.
1083    Content,
1084    /// A fixed share, the same at every width.
1085    Fixed,
1086    /// Absorbs whatever is left over.
1087    Fill,
1088}
1089
1090/// What a column is worth when there is not room for all of them.
1091///
1092/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
1093/// drops. This replaces addressing columns by position, which is what both
1094/// webview apps do today and is a live bug rather than only verbosity. goingson
1095/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
1096/// inserting a column silently hides the wrong one.
1097/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
1098/// whole point of the type, so a new tier has to be declared in its place in
1099/// the sequence rather than appended.
1100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1101#[non_exhaustive]
1102pub enum Priority {
1103    /// Dropped first.
1104    Optional,
1105    /// Dropped once the optional columns are gone.
1106    Secondary,
1107    /// Never dropped. Without it the row does not identify itself.
1108    Essential,
1109}
1110
1111/// One column of a table.
1112///
1113/// Described once. The grid track, the cell order and the drop behaviour are
1114/// all derived from this, rather than being three hand-written encodings that
1115/// must agree and are never checked against each other.
1116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1117pub struct Column<'a> {
1118    /// The heading, and the name the cell is addressed by.
1119    pub name: &'a str,
1120    /// How much room it asks for.
1121    pub width: Width,
1122    /// What it is worth when room runs out.
1123    pub priority: Priority,
1124}
1125
1126impl<'a> Column<'a> {
1127    /// A column that absorbs slack and drops after the optional ones.
1128    #[must_use]
1129    pub const fn new(name: &'a str) -> Self {
1130        Self {
1131            name,
1132            width: Width::Fill,
1133            priority: Priority::Secondary,
1134        }
1135    }
1136
1137    /// Whether this column survives at the given cutoff.
1138    ///
1139    /// A renderer narrows by raising the cutoff, and never by counting
1140    /// positions.
1141    #[must_use]
1142    pub const fn kept_at(&self, cutoff: Priority) -> bool {
1143        (self.priority as u8) >= (cutoff as u8)
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use super::*;
1150
1151    #[test]
1152    fn inset_is_raised_with_the_light_moved() {
1153        let (rl, rd) = Bevel::Raised.edges();
1154        let (il, id) = Bevel::Inset.edges();
1155        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
1156        assert_eq!((il, id), (rd, rl));
1157    }
1158
1159    #[test]
1160    fn pressing_twice_is_a_no_op() {
1161        for b in [Bevel::Raised, Bevel::Inset] {
1162            assert_eq!(b.pressed().pressed(), b);
1163        }
1164    }
1165
1166    #[test]
1167    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
1168        // The bug this vocabulary exists to make unrepresentable.
1169        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1170        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
1171        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
1172        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
1173    }
1174
1175    #[test]
1176    fn state_is_orthogonal_to_depth() {
1177        // The reason State is its own axis and not a Depth member: a disabled
1178        // button and a disabled field are both disabled and are not the same
1179        // shape, which one shared variant could not have said.
1180        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1181        assert_eq!(Depth::Well.fill(), Some(Fill::Well));
1182        assert!(State::Disabled.suppresses_interaction());
1183    }
1184
1185    #[test]
1186    fn only_disabled_stops_answering() {
1187        // Focus is a thing you can still click. Getting this backwards is how
1188        // a focus ring ends up on something inert.
1189        assert!(!State::Focus.suppresses_interaction());
1190        assert!(State::Disabled.suppresses_interaction());
1191    }
1192
1193    #[test]
1194    fn both_states_resolve_against_intents_makeover_already_derives() {
1195        // Neither needs a new token, so this costs no `makeover` release.
1196        assert_eq!(State::Focus.token(), "focus-ring");
1197        assert_eq!(State::Disabled.token(), "content-muted");
1198    }
1199
1200    #[test]
1201    fn flat_has_neither_edge_nor_fill() {
1202        assert_eq!(Depth::Flat.bevel(), None);
1203        assert_eq!(Depth::Flat.fill(), None);
1204    }
1205
1206    #[test]
1207    fn sunken_is_recessed_by_colour_with_no_edge() {
1208        // The one member carrying a fill without a bevel. A renderer that
1209        // assumes the two arrive together drops the fill silently, which is
1210        // exactly what makeover-webview did before 0.3.0.
1211        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
1212        assert_eq!(Depth::Sunken.bevel(), None);
1213    }
1214
1215    #[test]
1216    fn sunken_and_flat_are_different_claims() {
1217        // Both edgeless, and only one of them needs a colour. Collapsing them
1218        // is what left an unchosen tab unsayable.
1219        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
1220        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
1221    }
1222
1223    #[test]
1224    fn a_sunken_surface_is_not_a_well() {
1225        // Authored in opposite directions: makeover derives surface-well by
1226        // inverting against the theme's content colour, while surface-sunken is
1227        // authored and may sit darker than raised.
1228        assert_ne!(Fill::Sunken, Fill::Well);
1229        assert_eq!(Fill::Sunken.token(), "surface-sunken");
1230        assert_eq!(Fill::Well.token(), "surface-well");
1231    }
1232
1233    #[test]
1234    fn every_selector_describes_both_of_its_states() {
1235        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
1236        // unchosen option fell through to Flat at every renderer.
1237        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
1238            assert_ne!(
1239                s.chosen(),
1240                s.unchosen(),
1241                "{s:?} cannot tell picked from unpicked"
1242            );
1243        }
1244    }
1245
1246    #[test]
1247    fn only_a_tab_inverts_the_other_way() {
1248        // Tabs recede so the chosen one comes forward; a segment and a toggle
1249        // stand up so the chosen one is held in. That inversion is the whole
1250        // content of "picked" once colour is deferred, and it is why the three
1251        // are not one member with a flag.
1252        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1253        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1254
1255        for s in [Selector::Segmented, Selector::Toggle] {
1256            assert_eq!(s.unchosen(), Depth::Raised);
1257            assert_eq!(s.chosen(), Depth::Well);
1258            // Held in is what pressing produces: one appearance, two reasons.
1259            assert_eq!(s.unchosen().pressed(), s.chosen());
1260        }
1261    }
1262
1263    #[test]
1264    fn pressing_a_card_makes_a_well() {
1265        assert_eq!(Depth::Raised.pressed(), Depth::Well);
1266        assert_eq!(
1267            Depth::Raised.pressed().bevel(),
1268            Depth::Raised.bevel().map(Bevel::pressed)
1269        );
1270        // Only raised regions respond to being pressed.
1271        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
1272        assert_eq!(Depth::Well.pressed(), Depth::Well);
1273    }
1274
1275    #[test]
1276    fn intents_name_makeover_tokens_and_nothing_else() {
1277        assert_eq!(Edge::Light.token(), "bevel-light");
1278        assert_eq!(Edge::Dark.token(), "bevel-dark");
1279        assert_eq!(Fill::Raised.token(), "surface-raised");
1280        assert_eq!(Fill::Well.token(), "surface-well");
1281        // No value ever leaves this crate.
1282        for t in [
1283            Edge::Light.token(),
1284            Edge::Dark.token(),
1285            Tone::Danger.token(),
1286            Tone::Neutral.token(),
1287            State::Focus.token(),
1288            State::Disabled.token(),
1289        ] {
1290            assert!(!t.starts_with('#'), "{t} looks like a value");
1291            assert!(
1292                !t.chars().next().unwrap().is_ascii_digit(),
1293                "{t} is a value"
1294            );
1295        }
1296    }
1297
1298    #[test]
1299    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
1300        // The one line that runs through all three apps' taxonomies.
1301        assert!(!Token::Badge.interactive());
1302        assert!(Token::Chip { removable: false }.interactive());
1303        assert!(Token::Chip { removable: true }.interactive());
1304
1305        // A badge is a label, so giving it an edge would lie about it.
1306        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1307        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1308
1309        // A latched chip wears the same shape a pressed one does.
1310        let chip = Token::Chip { removable: false };
1311        assert_eq!(chip.depth(false), Depth::Raised);
1312        assert_eq!(chip.depth(true), Depth::Raised.pressed());
1313    }
1314
1315    #[test]
1316    fn a_toast_and_a_banner_differ_in_more_than_placement() {
1317        assert!(Notice::Toast.transient());
1318        assert!(!Notice::Banner.transient());
1319        // A toast floats above the page; a banner rests in the flow.
1320        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1321        assert_eq!(Notice::Banner.fill(), Fill::Raised);
1322    }
1323
1324    #[test]
1325    fn only_the_actions_part_hides_until_hovered() {
1326        for p in [RowPart::Primary, RowPart::Secondary, RowPart::Meta] {
1327            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
1328        }
1329        assert!(RowPart::Actions.revealed_on_hover());
1330        // Emphasis falls off down the row, and never rises again.
1331        assert_eq!(RowPart::Primary.intent(), "content");
1332        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
1333        assert_eq!(RowPart::Meta.intent(), "content-muted");
1334    }
1335
1336    #[test]
1337    fn a_separator_is_what_tells_a_section_from_a_subsection() {
1338        assert!(Heading::Section.separated());
1339        assert!(!Heading::Subsection.separated());
1340        assert!(!Heading::Page.separated());
1341    }
1342
1343    #[test]
1344    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
1345        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1346        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1347        // The exception, and the whole folder semantic: the open tab joins its
1348        // pane rather than sinking away from it.
1349        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1350
1351        // A held-in segment is indistinguishable from a pressed raised one,
1352        // which is the economy the light model buys over a colour swap.
1353        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
1354
1355        // A toggle stands alone; the other two are built out of parts that
1356        // touch.
1357        assert!(Selector::Segmented.abutting());
1358        assert!(Selector::Tabs.abutting());
1359        assert!(!Selector::Toggle.abutting());
1360    }
1361
1362    #[test]
1363    fn a_pane_is_looked_into_and_a_band_is_not() {
1364        assert_eq!(Region::Pane.depth(), Depth::Well);
1365        assert_eq!(Region::Modal.depth(), Depth::Raised);
1366        for r in [
1367            Region::Band,
1368            Region::Sidebar,
1369            Region::Split,
1370            Region::TabGroup,
1371        ] {
1372            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
1373        }
1374    }
1375
1376    #[test]
1377    fn exactly_one_region_is_opaque() {
1378        // The escape hatch is one member and stays one member. If a second
1379        // undescribed region ever appears, the description has started
1380        // conceding rather than deferring.
1381        for r in [
1382            Region::Band,
1383            Region::Sidebar,
1384            Region::Pane,
1385            Region::Split,
1386            Region::TabGroup,
1387            Region::Modal,
1388        ] {
1389            assert!(r.described(), "{r:?} should be describable");
1390        }
1391        assert!(!Region::Bespoke { name: "day-plan" }.described());
1392    }
1393
1394    #[test]
1395    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
1396        // The app owns the contents, not the placement. An app that wants its
1397        // timeline in a well frames it in a Pane.
1398        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
1399        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
1400    }
1401
1402    #[test]
1403    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
1404        // The argument the member exists for: goingson's day-plan has to be
1405        // routable, or the description covers only the boring screens and the
1406        // interesting four need a second path beside the router.
1407        let day_plan = [
1408            Region::Band,
1409            Region::Bespoke { name: "day-plan" },
1410            Region::Sidebar,
1411        ];
1412        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
1413        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
1414    }
1415
1416    #[test]
1417    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
1418        let secret = Field::new(FieldKind::Secret, "password", "Password");
1419        assert!(secret.kind.confidential());
1420        assert!(secret.kind.visible());
1421
1422        assert!(!FieldKind::Hidden.visible());
1423        // Nothing else is confidential, or the marker means nothing.
1424        for k in [
1425            FieldKind::Text,
1426            FieldKind::Number,
1427            FieldKind::Textarea,
1428            FieldKind::Select,
1429            FieldKind::Checkbox,
1430            FieldKind::Hidden,
1431        ] {
1432            assert!(!k.confidential(), "{k:?} should not be confidential");
1433        }
1434
1435        // Only a checkbox carries its own label.
1436        assert!(FieldKind::Checkbox.labels_itself());
1437        assert!(!FieldKind::Text.labels_itself());
1438    }
1439
1440    #[test]
1441    fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
1442        let text = Field::new(FieldKind::Text, "title", "Title");
1443        assert!(text.options.is_empty());
1444        assert_eq!(text.placeholder, None);
1445
1446        let sizes = [Choice::plain("small"), Choice::plain("large")];
1447        let select = Field::select("size", "Size", &sizes);
1448        assert_eq!(select.kind, FieldKind::Select);
1449        assert_eq!(select.options.len(), 2);
1450    }
1451
1452    #[test]
1453    fn a_choice_says_what_submits_and_what_is_read_apart() {
1454        // The whole reason it is two strings. `plain` is the case where they
1455        // coincide, and it is a shorthand rather than the general shape.
1456        let plain = Choice::plain("7");
1457        assert_eq!((plain.value, plain.label), ("7", "7"));
1458
1459        let spelled = Choice {
1460            value: "7",
1461            label: "One week",
1462        };
1463        assert_ne!(spelled.value, spelled.label);
1464    }
1465
1466    #[test]
1467    fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
1468        // Both offer a fixed set and both read `options`, so the two
1469        // constructors differ in exactly one thing. That one thing is the
1470        // point: a renderer decides whether the alternatives are readable
1471        // without opening anything, and it can only decide that if the
1472        // description said which question was asked.
1473        let styles = [
1474            Choice {
1475                value: "copy",
1476                label: "Copy samples in",
1477            },
1478            Choice {
1479                value: "reference",
1480                label: "Reference in place",
1481            },
1482        ];
1483        let radio = Field::radio("storage", "Storage style", &styles);
1484        let select = Field::select("storage", "Storage style", &styles);
1485
1486        assert_eq!(radio.kind, FieldKind::Radio);
1487        assert_ne!(radio.kind, select.kind);
1488        assert_eq!(radio.options, select.options);
1489        assert_eq!(
1490            Field {
1491                kind: select.kind,
1492                ..radio
1493            },
1494            select
1495        );
1496    }
1497
1498    #[test]
1499    fn exactly_the_option_taking_kinds_say_so() {
1500        // The renderers branch on this rather than on a list of their own, so
1501        // a kind added without a decision here renders its options nowhere.
1502        assert!(FieldKind::Select.offers_options());
1503        assert!(FieldKind::Radio.offers_options());
1504        for kind in [
1505            FieldKind::Text,
1506            FieldKind::Secret,
1507            FieldKind::Number,
1508            FieldKind::Email,
1509            FieldKind::Url,
1510            FieldKind::Tel,
1511            FieldKind::Textarea,
1512            FieldKind::Checkbox,
1513            FieldKind::Hidden,
1514        ] {
1515            assert!(!kind.offers_options(), "{kind:?} does not offer options");
1516        }
1517    }
1518
1519    #[test]
1520    fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
1521        // The near-miss: each option is labelled beside its own button, so a
1522        // renderer could plausibly read the group as self-labelling and drop
1523        // the question. Checkbox is the only kind that does that.
1524        assert!(!FieldKind::Radio.labels_itself());
1525        assert!(FieldKind::Checkbox.labels_itself());
1526    }
1527
1528    #[test]
1529    fn a_select_with_no_options_is_sayable() {
1530        // An app whose option list has not loaded has exactly this. Making it
1531        // unrepresentable would push the state somewhere less visible, and a
1532        // renderer drawing an empty select reports it on screen.
1533        let loading = Field::select("project", "Project", &[]);
1534        assert!(loading.options.is_empty());
1535    }
1536
1537    #[test]
1538    fn the_description_carries_the_question_and_never_the_answer() {
1539        // The line 0.8.0 drew. Placeholder and options are properties of what
1540        // is being asked; the current value is what came back, and no field
1541        // here holds one.
1542        let f = Field {
1543            placeholder: Some("yyyy-mm-dd"),
1544            ..Field::new(FieldKind::Text, "due", "Due")
1545        };
1546        assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
1547        // A placeholder is not a label, and having one does not excuse the
1548        // field from carrying the other.
1549        assert_eq!(f.label, "Due");
1550    }
1551
1552    #[test]
1553    fn a_field_reports_its_own_error_state() {
1554        let mut f = Field::new(FieldKind::Text, "title", "Title");
1555        assert!(!f.invalid());
1556        f.error = Some("Required");
1557        assert!(f.invalid());
1558    }
1559
1560    #[test]
1561    fn columns_drop_by_priority_and_never_by_position() {
1562        let cols = [
1563            Column {
1564                name: "Title",
1565                width: Width::Fill,
1566                priority: Priority::Essential,
1567            },
1568            Column {
1569                name: "Due",
1570                width: Width::Fixed,
1571                priority: Priority::Secondary,
1572            },
1573            Column {
1574                name: "Estimate",
1575                width: Width::Fixed,
1576                priority: Priority::Optional,
1577            },
1578        ];
1579
1580        // Widest: everything survives.
1581        assert_eq!(
1582            cols.iter()
1583                .filter(|c| c.kept_at(Priority::Optional))
1584                .count(),
1585            3
1586        );
1587        // Narrower: the optional column goes first.
1588        let kept: Vec<_> = cols
1589            .iter()
1590            .filter(|c| c.kept_at(Priority::Secondary))
1591            .map(|c| c.name)
1592            .collect();
1593        assert_eq!(kept, ["Title", "Due"]);
1594        // Narrowest: only what identifies the row.
1595        let kept: Vec<_> = cols
1596            .iter()
1597            .filter(|c| c.kept_at(Priority::Essential))
1598            .map(|c| c.name)
1599            .collect();
1600        assert_eq!(kept, ["Title"]);
1601    }
1602
1603    #[test]
1604    fn inserting_a_column_does_not_move_what_gets_dropped() {
1605        // The bug the ordinal form has and this form cannot: goingson hides
1606        // `nth-child(n+5)` against a seven-column table, so a column inserted
1607        // anywhere to the left silently hides a different one.
1608        let before = [
1609            Column::new("Title"),
1610            Column {
1611                name: "Estimate",
1612                width: Width::Fixed,
1613                priority: Priority::Optional,
1614            },
1615        ];
1616        let after = [
1617            Column::new("Title"),
1618            Column::new("Project"), // inserted
1619            Column {
1620                name: "Estimate",
1621                width: Width::Fixed,
1622                priority: Priority::Optional,
1623            },
1624        ];
1625
1626        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
1627            cols.iter()
1628                .filter(|c| !c.kept_at(Priority::Secondary))
1629                .map(|c| c.name)
1630                .collect()
1631        }
1632        assert_eq!(dropped(&before), ["Estimate"]);
1633        assert_eq!(dropped(&after), ["Estimate"]);
1634    }
1635
1636    #[test]
1637    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
1638        // goingson uses the tab group inside the content region rather than
1639        // instead of one, so it is not a third arrangement.
1640        let go = Arrangement::ListDetail { tabbed: true };
1641        let plain = Arrangement::ListDetail { tabbed: false };
1642        assert_ne!(go, plain);
1643        assert_ne!(go, Arrangement::SidebarContent);
1644    }
1645
1646    #[test]
1647    fn readiness_names_the_state_and_not_the_shimmer() {
1648        // Two members and no third. If a skeleton ever appears in this enum,
1649        // the deferral rule has been broken.
1650        assert_ne!(Readiness::Ready, Readiness::Pending);
1651    }
1652}