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//! # Where the description stops
58//!
59//! The bespoke widgets, a day-plan timeline and a kanban board and a calendar,
60//! are not describable here and will not become describable. A description
61//! expressive enough to produce a timeline is a widget library wearing a
62//! description's name. Generate the boring 80% so the bespoke 20% gets the
63//! attention.
64//!
65//! [`Region::Bespoke`] is how that limit is stated rather than hidden. The
66//! description names the *place* and the app owns the contents, so a screen
67//! containing a timeline is still a whole screen and still routable. Without
68//! it, the four goingson screens that make the app worth using would need a
69//! second, undescribed path beside the router, and two paths is how a
70//! vocabulary starts drifting from its app again.
71
72#![forbid(unsafe_code)]
73
74/// A colour intent this crate refers to but never resolves.
75///
76/// The string is the token name `makeover` publishes, so a renderer can look
77/// it up without this crate knowing what colour came back.
78pub trait Intent {
79    /// The `makeover` intent token this resolves against.
80    fn token(self) -> &'static str;
81}
82
83/// Which way the light falls across a two-tone edge.
84///
85/// The whole content of a bevel, once colour and thickness are deferred. The
86/// light is always assumed to come from the top left: every consumer measured
87/// agreed on that and none of them ever varied it, so it is an invariant here
88/// rather than a parameter.
89///
90/// # The two corners that belong to both edges
91///
92/// Top-right and bottom-left are where the lit run meets the shaded one, and
93/// the description's claim is that they belong to *both*. How a renderer says
94/// that is its own business, because the answer is bounded by resolution and
95/// not by taste:
96///
97/// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
98///   to one tone thickens that edge by a cell and reads as one run overrunning
99///   the other. A half-cell glyph divides the cell already, so `makeover-tui`
100///   splits it and recovers real information. Its box-drawing fallback cannot:
101///   a single stroke has no half to give, so there both corners go to dark.
102/// - A pixel bevel is a one-point stroke by default, which makes the corner a
103///   one-point square. There is nothing to divide — a diagonal seam across one
104///   point is sub-pixel, and antialiasing renders it as the blend a mitred join
105///   already produces. So `makeover-immediate` mitres and is *not* diverging;
106///   it is the same rule at a resolution where the split degenerates.
107///
108/// Stated here so the difference reads as a decision rather than as drift. A
109/// renderer with room to divide the corner should; one without should mitre or
110/// pick the shaded tone, and neither is a bug.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub enum Bevel {
113    /// Lit from the top left: light on top and left, dark on bottom and right.
114    Raised,
115    /// The same edge inverted, which is also the pressed state of anything
116    /// that draws itself [`Bevel::Raised`].
117    Inset,
118}
119
120impl Bevel {
121    /// The edge intents, as `(top_left, bottom_right)`.
122    ///
123    /// Split out from any painting because the inversion *is* the idea, and
124    /// it is the one part every renderer implements identically.
125    #[must_use]
126    pub const fn edges(self) -> (Edge, Edge) {
127        match self {
128            Self::Raised => (Edge::Light, Edge::Dark),
129            Self::Inset => (Edge::Dark, Edge::Light),
130        }
131    }
132
133    /// Pressing inverts. A raised control reads as inset while held.
134    ///
135    /// Stated here rather than left to each consumer because a cascade can
136    /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
137    /// resolves this per call site, eighteen times.
138    #[must_use]
139    pub const fn pressed(self) -> Self {
140        match self {
141            Self::Raised => Self::Inset,
142            Self::Inset => Self::Raised,
143        }
144    }
145}
146
147/// One side of a bevel, named by the intent it takes.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149pub enum Edge {
150    /// The lit side.
151    Light,
152    /// The shadowed side.
153    Dark,
154}
155
156impl Intent for Edge {
157    fn token(self) -> &'static str {
158        match self {
159            Self::Light => "bevel-light",
160            Self::Dark => "bevel-dark",
161        }
162    }
163}
164
165/// A surface intent a region is filled with.
166///
167/// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
168/// member is additive rather than breaking. Added 0.4.0, after [`Sunken`]
169/// (an additive member, 0.3.0) hard-broke `makeover-tui` and
170/// `makeover-immediate` at compile time and left neither able to move until
171/// both published. The vocabulary exists to grow and the renderers exist to
172/// disagree about how much of it they answer, so growth must not be a
173/// lockstep event. The renderer's wildcard is not a hole: [`Fill`] is
174/// resolved through a fallible lookup, and a missing intent is answered with
175/// structure rather than with a substituted colour.
176///
177/// [`Sunken`]: Fill::Sunken
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179#[non_exhaustive]
180pub enum Fill {
181    /// The page behind everything.
182    Page,
183    /// A surface lifted off the page: cards, controls, menus, toasts.
184    Raised,
185    /// A surface floating above the page rather than resting on it.
186    Overlay,
187    /// The inside of a well.
188    Well,
189    /// A surface set back from the one it sits on, by colour and nothing else.
190    ///
191    /// Not a well. A well is a hole with an edge, and the two are authored in
192    /// opposite directions: `makeover` derives `surface-well` by inverting
193    /// against the theme's own content colour, while `surface-sunken` is
194    /// authored and free to sit darker than raised (goingson's does). Naming
195    /// only the well left the recessed-with-no-edge surface unsayable, which is
196    /// what an unchosen tab is: it recedes so the chosen one can come forward,
197    /// and it carries no bevel of its own.
198    ///
199    /// Added 0.3.0, from goingson's tab strip, which hand-writes exactly this
200    /// and could not delete the line because no member described it.
201    Sunken,
202}
203
204// No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
205// to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
206// had something to paint. makeover-tui found that wrong within a day: page is
207// the surface a well is usually cut into, so on a terminal that substitution
208// produces exactly the invisibility it was meant to prevent, and the right
209// answer there is a drawn edge rather than a different colour.
210//
211// Substituting one intent for another is renderer policy. The description says
212// what the region is and stops.
213
214impl Intent for Fill {
215    fn token(self) -> &'static str {
216        match self {
217            Self::Page => "surface-page",
218            Self::Raised => "surface-raised",
219            Self::Overlay => "surface-overlay",
220            Self::Well => "surface-well",
221            Self::Sunken => "surface-sunken",
222        }
223    }
224}
225
226/// How a region sits relative to the surface behind it.
227///
228/// Fill and bevel are named together because naming them apart is what let
229/// them disagree. Every consumer measured had at least one region carrying a
230/// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
231/// and recorded the bug in its doc comment, and Balanced Breakfast still had
232/// twelve of them a year later. A single name for the pair makes that
233/// unrepresentable.
234/// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
235/// release: a depth this renderer has no drawing for should cost it a
236/// wildcard arm, not a compile error and a wait on someone else's publish.
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238#[non_exhaustive]
239pub enum Depth {
240    /// Level with its surroundings. No edge.
241    Flat,
242    /// A card laid on the panel it sits in.
243    Raised,
244    /// A hole in the panel, with content down inside it. For anything the
245    /// user looks *into*: a table body, a tag tree, a text field.
246    Well,
247    /// Set back from what it sits on, by colour alone. No edge.
248    ///
249    /// The one member carrying a fill without a bevel, so a renderer cannot
250    /// assume the two arrive together. That is deliberate and it is still the
251    /// pairing rule: both halves come off the same `Depth`, so they cannot
252    /// disagree, and here one half is legitimately absent.
253    ///
254    /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
255    /// Recessed and level-with are different claims, and only one of them
256    /// needs a colour.
257    Sunken,
258}
259
260impl Depth {
261    /// The edge this depth is drawn with, if it has one.
262    #[must_use]
263    pub const fn bevel(self) -> Option<Bevel> {
264        match self {
265            // Sunken joins Flat here, for the opposite reason: Flat has no edge
266            // because nothing separates it from its surroundings, and Sunken has
267            // none because its colour is already doing the separating.
268            Self::Flat | Self::Sunken => None,
269            Self::Raised => Some(Bevel::Raised),
270            Self::Well => Some(Bevel::Inset),
271        }
272    }
273
274    /// The surface this depth is filled with.
275    ///
276    /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
277    /// which is the difference between level-with and painted-the-same-colour.
278    #[must_use]
279    pub const fn fill(self) -> Option<Fill> {
280        match self {
281            Self::Flat => None,
282            Self::Raised => Some(Fill::Raised),
283            Self::Well => Some(Fill::Well),
284            Self::Sunken => Some(Fill::Sunken),
285        }
286    }
287
288    /// Pressing a raised region reads as a well, and nothing else moves.
289    #[must_use]
290    pub const fn pressed(self) -> Self {
291        match self {
292            Self::Raised => Self::Well,
293            other => other,
294        }
295    }
296}
297
298/// What a region is saying, when it is saying something.
299///
300/// The one intent family shared by badges, notices and nothing else. Kept
301/// separate from [`Fill`] because a surface is where a thing sits and a tone is
302/// what it means, and the three apps agree on the four statuses:
303/// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
304/// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
305/// `.toast.error` in Balanced Breakfast.
306///
307/// The per-tag palette (`category-one` through `category-six`) is deliberately
308/// not here. Which colour a *particular* tag takes is app domain, and both
309/// webview apps already carry it as a `data-color` attribute.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub enum Tone {
312    /// No status. Reads as ordinary de-emphasised content.
313    Neutral,
314    /// Something worth knowing and nothing to do about it.
315    Info,
316    /// Something finished and it worked.
317    Success,
318    /// Something the user should look at before continuing.
319    Warning,
320    /// Something broken, or something about to be destroyed.
321    Danger,
322}
323
324impl Intent for Tone {
325    fn token(self) -> &'static str {
326        match self {
327            // Neutral has no status token of its own. It takes the muted
328            // content intent, which is what both webview apps already spell as
329            // `data-color="muted"`.
330            Self::Neutral => "content-muted",
331            Self::Info => "info",
332            Self::Success => "success",
333            Self::Warning => "warning",
334            Self::Danger => "danger",
335        }
336    }
337}
338
339/// A small labelled thing that sits inside something else.
340///
341/// Two members, because the three apps drew three taxonomies and only one line
342/// runs through all of them: does it answer a click. audiofiles has
343/// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
344/// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
345/// `.badge` against `.tag-chip`. goingson is the one that has to move: its
346/// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
347/// to decide which of the two it always was.
348///
349/// The evidence that a chip is a real concept rather than a badge with a
350/// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
351/// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
352/// holds itself down", which is exactly what [`Depth::pressed`] already says.
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
354pub enum Token {
355    /// Non-interactive status or count. Answers no click.
356    Badge,
357    /// An interactive or removable token. Answers a click, and latches if it
358    /// stands for a filter that is either on or off.
359    Chip {
360        /// Whether it carries its own remove affordance.
361        removable: bool,
362    },
363}
364
365impl Token {
366    /// Whether this answers a click.
367    ///
368    /// The whole difference between the two members, and the reason a renderer
369    /// with no hover (a touch surface, a terminal) can still tell them apart.
370    #[must_use]
371    pub const fn interactive(self) -> bool {
372        matches!(self, Self::Chip { .. })
373    }
374
375    /// How it sits, given whether it is currently latched down.
376    ///
377    /// A badge is flat: it is a label, and giving it an edge would say it can
378    /// be pressed. A chip is raised, and inset while latched.
379    #[must_use]
380    pub const fn depth(self, latched: bool) -> Depth {
381        match self {
382            Self::Badge => Depth::Flat,
383            Self::Chip { .. } if latched => Depth::Well,
384            Self::Chip { .. } => Depth::Raised,
385        }
386    }
387}
388
389/// Something the app is telling the user, unprompted.
390///
391/// Two concepts, not one with a placement. They differ in more than where they
392/// sit: a toast is transient, stacked and self-dismissing, and a banner is
393/// persistent, in flow, one per region, and dismissed by fixing the condition
394/// it reports. Folding them into one member with a placement parameter would
395/// make lifetime, stacking and dismissal all placement-dependent, which is the
396/// description leaking renderer policy.
397///
398/// All three apps have banners: `info_banner` and `warning_banner` in
399/// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
400/// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
401/// webview apps also have toasts. So neither member is speculative, and no app
402/// gains a concept it lacks except audiofiles, whose renderer may legitimately
403/// decline to draw a toast at all.
404#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
405pub enum Notice {
406    /// Transient, stacked, dismisses itself.
407    Toast,
408    /// Persistent, in flow, one per region, dismissed by fixing the cause.
409    Banner,
410}
411
412impl Notice {
413    /// Whether it goes away on its own.
414    #[must_use]
415    pub const fn transient(self) -> bool {
416        matches!(self, Self::Toast)
417    }
418
419    /// How it sits.
420    ///
421    /// A toast floats above the page rather than resting on it, which is
422    /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
423    /// flow. Both are raised, and they are raised off different things.
424    #[must_use]
425    pub const fn fill(self) -> Fill {
426        match self {
427            Self::Toast => Fill::Overlay,
428            Self::Banner => Fill::Raised,
429        }
430    }
431}
432
433/// The parts of a list row.
434///
435/// Four, taken from Balanced Breakfast, which is the only consumer that had all
436/// of them (`row-primary`, `row-secondary`, `row-meta`, `row-actions`).
437/// audiofiles has two and no slot structure at all, so it gains meta and
438/// actions as real work rather than a rename; goingson moves off
439/// `task-row` / `task-cell`.
440#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
441pub enum RowPart {
442    /// The thing itself. What the row is called.
443    Primary,
444    /// Supporting text under the primary.
445    Secondary,
446    /// A short trailing fact: a count, a size, a date.
447    Meta,
448    /// Controls that act on this row.
449    Actions,
450}
451
452impl RowPart {
453    /// Whether the part stays hidden until the row is hovered or focused.
454    ///
455    /// Behaviour of the part, not app policy: Balanced Breakfast and goingson
456    /// grew the same hover-reveal on their actions independently and neither
457    /// applies it to anything else.
458    ///
459    /// A renderer with no hover shows it always. That is a renderer decision
460    /// and this returning `true` does not forbid it.
461    #[must_use]
462    pub const fn revealed_on_hover(self) -> bool {
463        matches!(self, Self::Actions)
464    }
465
466    /// The content intent the part takes.
467    #[must_use]
468    pub const fn intent(self) -> &'static str {
469        match self {
470            Self::Primary => "content",
471            Self::Secondary => "content-secondary",
472            Self::Meta => "content-muted",
473            // Actions carry controls rather than text, so they inherit.
474            Self::Actions => "content",
475        }
476    }
477}
478
479/// How far down the heading tree a title sits.
480///
481/// Three, and only the three that are actually headings. The bands those used
482/// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
483/// and `.detail-header`) are arrangement, not type, and live at
484/// [`Region::Band`]. One of them contains no text at all.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
486pub enum Heading {
487    /// Names the whole screen. One per screen.
488    Page,
489    /// Names a block within the screen.
490    Section,
491    /// Names a sub-block inside an already-named section.
492    Subsection,
493}
494
495impl Heading {
496    /// Whether a rule follows the heading.
497    ///
498    /// audiofiles' `section_header` draws a separator and its
499    /// `subsection_label` deliberately does not, which is the only thing
500    /// distinguishing the two once weight and colour are deferred.
501    #[must_use]
502    pub const fn separated(self) -> bool {
503        matches!(self, Self::Section)
504    }
505}
506
507/// A control that picks between things.
508///
509/// Three, because three distinct behaviours are in play and collapsing any two
510/// loses something. A segmented control picks a value; a tab picks a pane; a
511/// toggle picks nothing and simply holds itself on or off.
512#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
513pub enum Selector {
514    /// Exactly one of N, and the options abut.
515    Segmented,
516    /// Independent on or off, on its own.
517    Toggle,
518    /// Navigation between panes. The folder semantic.
519    Tabs,
520}
521
522impl Selector {
523    /// How the chosen option sits.
524    ///
525    /// Held in for a segmented control and a toggle, which is the same shape
526    /// pressing produces and the whole economy of the idiom: one appearance,
527    /// two reasons to wear it. A tab is the exception, because the selected
528    /// folder tab comes *forward* to join the pane it opens.
529    #[must_use]
530    pub const fn chosen(self) -> Depth {
531        match self {
532            Self::Segmented | Self::Toggle => Depth::Well,
533            Self::Tabs => Depth::Raised,
534        }
535    }
536
537    /// How the options that were *not* picked sit.
538    ///
539    /// Added 0.3.0. Describing only [`Selector::chosen`] left the unchosen
540    /// option falling through to [`Depth::Flat`], which says it is level with
541    /// the strip it sits in, and no renderer emitted anything for it. That is
542    /// wrong in both directions and goingson proved it: its unchosen tabs are
543    /// recessed by hand, and being recessed is *why* the chosen one reads as
544    /// coming forward. Against a flat strip, a raised chosen tab is a bevel
545    /// drawn on the strip's own colour, which is a much weaker folder effect
546    /// than the contrast the idiom is named after.
547    ///
548    /// Each member is the inverse of its chosen state, which is the whole
549    /// content of "picked" once colour is deferred:
550    ///
551    /// - Tabs recede, so the chosen one comes forward.
552    /// - A segment and a toggle stand up, so the chosen one is held in.
553    #[must_use]
554    pub const fn unchosen(self) -> Depth {
555        match self {
556            Self::Tabs => Depth::Sunken,
557            Self::Segmented | Self::Toggle => Depth::Raised,
558        }
559    }
560
561    /// Whether the options touch.
562    ///
563    /// The gap is the entire difference between a segmented control and a row
564    /// of buttons that happen to sit near each other, which is what audiofiles'
565    /// `segmented_control` says in its own comment and why it zeroes the
566    /// spacing by hand.
567    #[must_use]
568    pub const fn abutting(self) -> bool {
569        matches!(self, Self::Segmented | Self::Tabs)
570    }
571}
572
573/// Whether the content of a region has arrived.
574///
575/// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
576/// nothing at all is renderer policy, the same class of decision that got
577/// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
578/// each grew a skeleton with differently-named parts; both keep them, as the
579/// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
580/// and needs none, because an immediate-mode renderer simply repaints.
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
582pub enum Readiness {
583    /// The content is here.
584    Ready,
585    /// The content is on its way.
586    Pending,
587}
588
589/// A named part of a screen.
590///
591/// The thing `makeover-geometry` deliberately does not name: it names the space
592/// *between* things by relationship, and nothing named the things. Six named
593/// members, taken from what the two webview apps actually use, plus
594/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
595/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
596/// this layer is absent rather than divergent, which makes it the cheapest of
597/// the schemas to add and the easiest to over-build.
598#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
599pub enum Region<'a> {
600    /// A full-width strip with a title slot and an actions cluster, either of
601    /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
602    /// `.header` and `.detail-header` are all this, differing only in which
603    /// slots they fill.
604    Band,
605    /// A persistent column beside the content, holding navigation.
606    Sidebar,
607    /// A region of content with its own scroll.
608    Pane,
609    /// Two panes side by side, where the left chooses what the right shows.
610    Split,
611    /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
612    TabGroup,
613    /// Content over a scrim, taking input until dismissed.
614    Modal,
615    /// A region this crate names the *place* of and nothing else. The app owns
616    /// what goes in it.
617    ///
618    /// The escape hatch, and the thing that keeps the description honest about
619    /// its own limits. A day-plan timeline, a kanban board, a calendar and the
620    /// paint interaction over the timeline are not describable here and are not
621    /// going to become describable: a description expressive enough to produce
622    /// a timeline is a widget library wearing a description's name.
623    ///
624    /// But a screen containing one still has to be a screen. Without this
625    /// member the description covers only the boring screens, and the four that
626    /// make goingson worth using would need a second, undescribed path beside
627    /// the router. Two paths is how the vocabulary starts drifting from the app
628    /// again, which is the exact failure this crate exists to end.
629    ///
630    /// So the description says "a thing called `day-plan` goes here" and stops.
631    /// The name is opaque: this crate never interprets it, and no renderer is
632    /// expected to know what it means beyond handing the space over.
633    Bespoke {
634        /// What the app calls it. Never interpreted here.
635        name: &'a str,
636    },
637}
638
639impl Region<'_> {
640    /// How the region sits on what is behind it.
641    #[must_use]
642    pub const fn depth(self) -> Depth {
643        match self {
644            Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
645            // A pane is looked into, the same as a table body or a tag tree.
646            Self::Pane => Depth::Well,
647            Self::Modal => Depth::Raised,
648            // Flat because it inherits: a bespoke region takes the depth of
649            // whatever frames it. An app that wants its timeline in a well puts
650            // it in a `Pane`, which composes rather than adding a knob here.
651            Self::Bespoke { .. } => Depth::Flat,
652        }
653    }
654
655    /// Whether this crate can say anything about the region's contents.
656    ///
657    /// A renderer walks the description and hands every region it understands
658    /// to the right drawing code. This is how it tells the two apart, and the
659    /// reason it is a method rather than a `matches!` at each renderer: there
660    /// is exactly one opaque member and there should stay exactly one.
661    #[must_use]
662    pub const fn described(self) -> bool {
663        !matches!(self, Self::Bespoke { .. })
664    }
665}
666
667/// How a screen is laid out.
668///
669/// Two, and the second is not a variant of the first. goingson is list-detail,
670/// Balanced Breakfast is sidebar plus content, and neither app has a third.
671/// The tab group is a modifier rather than a member, because goingson uses it
672/// *inside* the same content region rather than instead of one.
673///
674/// This exists at all because the router has to be able to express a screen
675/// rather than only a control. Discovering the arrangement layer missing after
676/// the renderers exist is a redesign; naming two now is a morning.
677#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
678pub enum Arrangement {
679    /// A list that chooses what the detail beside it shows.
680    ListDetail {
681        /// Whether the detail side is a [`Region::TabGroup`].
682        tabbed: bool,
683    },
684    /// Navigation down the side, content filling the rest.
685    SidebarContent,
686}
687
688/// What kind of value a form field takes.
689///
690/// The union of the two vocabularies that diverged, which is what triggered
691/// this crate. They have since converged on their own: both apps now have a
692/// `renderFormField` emitting the same anatomy, and what is left differing is
693/// the kind set, the error shape, and whether the return is a string or a node.
694///
695/// Validation is deliberately absent. Neither app has a shared story (goingson
696/// validates after collecting the form data, with per-field transform hooks;
697/// Balanced Breakfast has `required` and nothing else), and a schema that
698/// describes fields but not constraints acquires a constraint layer per app,
699/// which is exactly how the current divergence started. Naming it absent is a
700/// decision; leaving it unmentioned would not be.
701/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
702/// the set keeps growing, so growth must not be a lockstep event. Email, Url
703/// and Tel arriving in 0.5.0 is the second growth in two releases.
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
705#[non_exhaustive]
706pub enum FieldKind {
707    /// A single line of text.
708    Text,
709    /// A single line of text that must never be echoed, logged or round-tripped
710    /// through anything that might persist it.
711    Secret,
712    /// A number.
713    Number,
714    /// An email address.
715    ///
716    /// Distinct from [`Text`](Self::Text) because the distinction is not
717    /// decoration: a webview renderer emits `type="email"`, which on a touch
718    /// device changes the keyboard that appears and turns on the platform's own
719    /// validation. goingson ships to iOS, so collapsing this into text costs a
720    /// keyboard with no `@` on it.
721    ///
722    /// Added 0.5.0, from goingson's contact form.
723    Email,
724    /// A URL. Same reasoning as [`Email`](Self::Email).
725    ///
726    /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
727    Url,
728    /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
729    /// clearest case of it: the keyboard is a numeric pad rather than letters.
730    ///
731    /// Added 0.5.0, from goingson's contact-phone form.
732    Tel,
733    /// Several lines of text.
734    Textarea,
735    /// One of a fixed set.
736    Select,
737    /// On or off.
738    Checkbox,
739    /// Carried through the form and never shown.
740    Hidden,
741}
742
743impl FieldKind {
744    /// Whether the field is drawn at all.
745    #[must_use]
746    pub const fn visible(self) -> bool {
747        !matches!(self, Self::Hidden)
748    }
749
750    /// Whether the value must be kept out of logs and diagnostics.
751    #[must_use]
752    pub const fn confidential(self) -> bool {
753        matches!(self, Self::Secret)
754    }
755
756    /// Where the field's own label sits.
757    ///
758    /// A checkbox labels itself on the right of the box; everything else takes
759    /// a label above. Both webview apps already do this and both special-case
760    /// it inline, which is the tell that it belongs in the description.
761    #[must_use]
762    pub const fn labels_itself(self) -> bool {
763        matches!(self, Self::Checkbox)
764    }
765}
766
767/// One field of a form.
768///
769/// Borrowed rather than owned: a description is built, read once by a renderer,
770/// and dropped. Nothing here outlives the screen it describes.
771#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
772pub struct Field<'a> {
773    /// What kind of value it takes.
774    pub kind: FieldKind,
775    /// The name the value is submitted under.
776    pub name: &'a str,
777    /// What the user is asked for.
778    pub label: &'a str,
779    /// Standing help, shown whether or not anything is wrong.
780    pub hint: Option<&'a str>,
781    /// What is currently wrong with the value.
782    pub error: Option<&'a str>,
783    /// Whether the form refuses to submit without it.
784    pub required: bool,
785    /// Whether the field lives behind a "more options" disclosure.
786    pub extended: bool,
787}
788
789impl<'a> Field<'a> {
790    /// A plain required-nothing field of the given kind.
791    #[must_use]
792    pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
793        Self {
794            kind,
795            name,
796            label,
797            hint: None,
798            error: None,
799            required: false,
800            extended: false,
801        }
802    }
803
804    /// Whether the field is currently reporting a problem.
805    ///
806    /// Read this rather than testing `error.is_some()` at each renderer: the
807    /// error state has to mark the field's whole group and not only the
808    /// message, because a renderer with no descendant selectors (egui, a
809    /// terminal) cannot find the group from the message. goingson already marks
810    /// the group and Balanced Breakfast does not, so goingson's shape is the
811    /// one taken here.
812    #[must_use]
813    pub const fn invalid(&self) -> bool {
814        self.error.is_some()
815    }
816}
817
818/// How much room a column asks for.
819///
820/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
821/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
822/// only the first three words of that survive deferral.
823/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
824/// renderer matches on this and a vocabulary that grows must not break every
825/// renderer when it does.
826#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
827#[non_exhaustive]
828pub enum Width {
829    /// Takes what it needs and no more.
830    Content,
831    /// A fixed share, the same at every width.
832    Fixed,
833    /// Absorbs whatever is left over.
834    Fill,
835}
836
837/// What a column is worth when there is not room for all of them.
838///
839/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
840/// drops. This replaces addressing columns by position, which is what both
841/// webview apps do today and is a live bug rather than only verbosity. goingson
842/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
843/// inserting a column silently hides the wrong one.
844/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
845/// whole point of the type, so a new tier has to be declared in its place in
846/// the sequence rather than appended.
847#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
848#[non_exhaustive]
849pub enum Priority {
850    /// Dropped first.
851    Optional,
852    /// Dropped once the optional columns are gone.
853    Secondary,
854    /// Never dropped. Without it the row does not identify itself.
855    Essential,
856}
857
858/// One column of a table.
859///
860/// Described once. The grid track, the cell order and the drop behaviour are
861/// all derived from this, rather than being three hand-written encodings that
862/// must agree and are never checked against each other.
863#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
864pub struct Column<'a> {
865    /// The heading, and the name the cell is addressed by.
866    pub name: &'a str,
867    /// How much room it asks for.
868    pub width: Width,
869    /// What it is worth when room runs out.
870    pub priority: Priority,
871}
872
873impl<'a> Column<'a> {
874    /// A column that absorbs slack and drops after the optional ones.
875    #[must_use]
876    pub const fn new(name: &'a str) -> Self {
877        Self {
878            name,
879            width: Width::Fill,
880            priority: Priority::Secondary,
881        }
882    }
883
884    /// Whether this column survives at the given cutoff.
885    ///
886    /// A renderer narrows by raising the cutoff, and never by counting
887    /// positions.
888    #[must_use]
889    pub const fn kept_at(&self, cutoff: Priority) -> bool {
890        (self.priority as u8) >= (cutoff as u8)
891    }
892}
893
894#[cfg(test)]
895mod tests {
896    use super::*;
897
898    #[test]
899    fn inset_is_raised_with_the_light_moved() {
900        let (rl, rd) = Bevel::Raised.edges();
901        let (il, id) = Bevel::Inset.edges();
902        assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
903        assert_eq!((il, id), (rd, rl));
904    }
905
906    #[test]
907    fn pressing_twice_is_a_no_op() {
908        for b in [Bevel::Raised, Bevel::Inset] {
909            assert_eq!(b.pressed().pressed(), b);
910        }
911    }
912
913    #[test]
914    fn a_raised_region_is_never_filled_with_a_recessed_surface() {
915        // The bug this vocabulary exists to make unrepresentable.
916        assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
917        assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
918        assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
919        assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
920    }
921
922    #[test]
923    fn flat_has_neither_edge_nor_fill() {
924        assert_eq!(Depth::Flat.bevel(), None);
925        assert_eq!(Depth::Flat.fill(), None);
926    }
927
928    #[test]
929    fn sunken_is_recessed_by_colour_with_no_edge() {
930        // The one member carrying a fill without a bevel. A renderer that
931        // assumes the two arrive together drops the fill silently, which is
932        // exactly what makeover-webview did before 0.3.0.
933        assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
934        assert_eq!(Depth::Sunken.bevel(), None);
935    }
936
937    #[test]
938    fn sunken_and_flat_are_different_claims() {
939        // Both edgeless, and only one of them needs a colour. Collapsing them
940        // is what left an unchosen tab unsayable.
941        assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
942        assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
943    }
944
945    #[test]
946    fn a_sunken_surface_is_not_a_well() {
947        // Authored in opposite directions: makeover derives surface-well by
948        // inverting against the theme's content colour, while surface-sunken is
949        // authored and may sit darker than raised.
950        assert_ne!(Fill::Sunken, Fill::Well);
951        assert_eq!(Fill::Sunken.token(), "surface-sunken");
952        assert_eq!(Fill::Well.token(), "surface-well");
953    }
954
955    #[test]
956    fn every_selector_describes_both_of_its_states() {
957        // The gap 0.3.0 closed. Before it, only `chosen` existed and the
958        // unchosen option fell through to Flat at every renderer.
959        for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
960            assert_ne!(
961                s.chosen(),
962                s.unchosen(),
963                "{s:?} cannot tell picked from unpicked"
964            );
965        }
966    }
967
968    #[test]
969    fn only_a_tab_inverts_the_other_way() {
970        // Tabs recede so the chosen one comes forward; a segment and a toggle
971        // stand up so the chosen one is held in. That inversion is the whole
972        // content of "picked" once colour is deferred, and it is why the three
973        // are not one member with a flag.
974        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
975        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
976
977        for s in [Selector::Segmented, Selector::Toggle] {
978            assert_eq!(s.unchosen(), Depth::Raised);
979            assert_eq!(s.chosen(), Depth::Well);
980            // Held in is what pressing produces: one appearance, two reasons.
981            assert_eq!(s.unchosen().pressed(), s.chosen());
982        }
983    }
984
985    #[test]
986    fn pressing_a_card_makes_a_well() {
987        assert_eq!(Depth::Raised.pressed(), Depth::Well);
988        assert_eq!(
989            Depth::Raised.pressed().bevel(),
990            Depth::Raised.bevel().map(Bevel::pressed)
991        );
992        // Only raised regions respond to being pressed.
993        assert_eq!(Depth::Flat.pressed(), Depth::Flat);
994        assert_eq!(Depth::Well.pressed(), Depth::Well);
995    }
996
997    #[test]
998    fn intents_name_makeover_tokens_and_nothing_else() {
999        assert_eq!(Edge::Light.token(), "bevel-light");
1000        assert_eq!(Edge::Dark.token(), "bevel-dark");
1001        assert_eq!(Fill::Raised.token(), "surface-raised");
1002        assert_eq!(Fill::Well.token(), "surface-well");
1003        // No value ever leaves this crate.
1004        for t in [
1005            Edge::Light.token(),
1006            Edge::Dark.token(),
1007            Tone::Danger.token(),
1008            Tone::Neutral.token(),
1009        ] {
1010            assert!(!t.starts_with('#'), "{t} looks like a value");
1011            assert!(
1012                !t.chars().next().unwrap().is_ascii_digit(),
1013                "{t} is a value"
1014            );
1015        }
1016    }
1017
1018    #[test]
1019    fn a_badge_cannot_be_pressed_and_a_chip_latches() {
1020        // The one line that runs through all three apps' taxonomies.
1021        assert!(!Token::Badge.interactive());
1022        assert!(Token::Chip { removable: false }.interactive());
1023        assert!(Token::Chip { removable: true }.interactive());
1024
1025        // A badge is a label, so giving it an edge would lie about it.
1026        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1027        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1028
1029        // A latched chip wears the same shape a pressed one does.
1030        let chip = Token::Chip { removable: false };
1031        assert_eq!(chip.depth(false), Depth::Raised);
1032        assert_eq!(chip.depth(true), Depth::Raised.pressed());
1033    }
1034
1035    #[test]
1036    fn a_toast_and_a_banner_differ_in_more_than_placement() {
1037        assert!(Notice::Toast.transient());
1038        assert!(!Notice::Banner.transient());
1039        // A toast floats above the page; a banner rests in the flow.
1040        assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1041        assert_eq!(Notice::Banner.fill(), Fill::Raised);
1042    }
1043
1044    #[test]
1045    fn only_the_actions_part_hides_until_hovered() {
1046        for p in [RowPart::Primary, RowPart::Secondary, RowPart::Meta] {
1047            assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
1048        }
1049        assert!(RowPart::Actions.revealed_on_hover());
1050        // Emphasis falls off down the row, and never rises again.
1051        assert_eq!(RowPart::Primary.intent(), "content");
1052        assert_eq!(RowPart::Secondary.intent(), "content-secondary");
1053        assert_eq!(RowPart::Meta.intent(), "content-muted");
1054    }
1055
1056    #[test]
1057    fn a_separator_is_what_tells_a_section_from_a_subsection() {
1058        assert!(Heading::Section.separated());
1059        assert!(!Heading::Subsection.separated());
1060        assert!(!Heading::Page.separated());
1061    }
1062
1063    #[test]
1064    fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
1065        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1066        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1067        // The exception, and the whole folder semantic: the open tab joins its
1068        // pane rather than sinking away from it.
1069        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1070
1071        // A held-in segment is indistinguishable from a pressed raised one,
1072        // which is the economy the light model buys over a colour swap.
1073        assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
1074
1075        // A toggle stands alone; the other two are built out of parts that
1076        // touch.
1077        assert!(Selector::Segmented.abutting());
1078        assert!(Selector::Tabs.abutting());
1079        assert!(!Selector::Toggle.abutting());
1080    }
1081
1082    #[test]
1083    fn a_pane_is_looked_into_and_a_band_is_not() {
1084        assert_eq!(Region::Pane.depth(), Depth::Well);
1085        assert_eq!(Region::Modal.depth(), Depth::Raised);
1086        for r in [
1087            Region::Band,
1088            Region::Sidebar,
1089            Region::Split,
1090            Region::TabGroup,
1091        ] {
1092            assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
1093        }
1094    }
1095
1096    #[test]
1097    fn exactly_one_region_is_opaque() {
1098        // The escape hatch is one member and stays one member. If a second
1099        // undescribed region ever appears, the description has started
1100        // conceding rather than deferring.
1101        for r in [
1102            Region::Band,
1103            Region::Sidebar,
1104            Region::Pane,
1105            Region::Split,
1106            Region::TabGroup,
1107            Region::Modal,
1108        ] {
1109            assert!(r.described(), "{r:?} should be describable");
1110        }
1111        assert!(!Region::Bespoke { name: "day-plan" }.described());
1112    }
1113
1114    #[test]
1115    fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
1116        // The app owns the contents, not the placement. An app that wants its
1117        // timeline in a well frames it in a Pane.
1118        assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
1119        assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
1120    }
1121
1122    #[test]
1123    fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
1124        // The argument the member exists for: goingson's day-plan has to be
1125        // routable, or the description covers only the boring screens and the
1126        // interesting four need a second path beside the router.
1127        let day_plan = [
1128            Region::Band,
1129            Region::Bespoke { name: "day-plan" },
1130            Region::Sidebar,
1131        ];
1132        assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
1133        assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
1134    }
1135
1136    #[test]
1137    fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
1138        let secret = Field::new(FieldKind::Secret, "password", "Password");
1139        assert!(secret.kind.confidential());
1140        assert!(secret.kind.visible());
1141
1142        assert!(!FieldKind::Hidden.visible());
1143        // Nothing else is confidential, or the marker means nothing.
1144        for k in [
1145            FieldKind::Text,
1146            FieldKind::Number,
1147            FieldKind::Textarea,
1148            FieldKind::Select,
1149            FieldKind::Checkbox,
1150            FieldKind::Hidden,
1151        ] {
1152            assert!(!k.confidential(), "{k:?} should not be confidential");
1153        }
1154
1155        // Only a checkbox carries its own label.
1156        assert!(FieldKind::Checkbox.labels_itself());
1157        assert!(!FieldKind::Text.labels_itself());
1158    }
1159
1160    #[test]
1161    fn a_field_reports_its_own_error_state() {
1162        let mut f = Field::new(FieldKind::Text, "title", "Title");
1163        assert!(!f.invalid());
1164        f.error = Some("Required");
1165        assert!(f.invalid());
1166    }
1167
1168    #[test]
1169    fn columns_drop_by_priority_and_never_by_position() {
1170        let cols = [
1171            Column {
1172                name: "Title",
1173                width: Width::Fill,
1174                priority: Priority::Essential,
1175            },
1176            Column {
1177                name: "Due",
1178                width: Width::Fixed,
1179                priority: Priority::Secondary,
1180            },
1181            Column {
1182                name: "Estimate",
1183                width: Width::Fixed,
1184                priority: Priority::Optional,
1185            },
1186        ];
1187
1188        // Widest: everything survives.
1189        assert_eq!(
1190            cols.iter()
1191                .filter(|c| c.kept_at(Priority::Optional))
1192                .count(),
1193            3
1194        );
1195        // Narrower: the optional column goes first.
1196        let kept: Vec<_> = cols
1197            .iter()
1198            .filter(|c| c.kept_at(Priority::Secondary))
1199            .map(|c| c.name)
1200            .collect();
1201        assert_eq!(kept, ["Title", "Due"]);
1202        // Narrowest: only what identifies the row.
1203        let kept: Vec<_> = cols
1204            .iter()
1205            .filter(|c| c.kept_at(Priority::Essential))
1206            .map(|c| c.name)
1207            .collect();
1208        assert_eq!(kept, ["Title"]);
1209    }
1210
1211    #[test]
1212    fn inserting_a_column_does_not_move_what_gets_dropped() {
1213        // The bug the ordinal form has and this form cannot: goingson hides
1214        // `nth-child(n+5)` against a seven-column table, so a column inserted
1215        // anywhere to the left silently hides a different one.
1216        let before = [
1217            Column::new("Title"),
1218            Column {
1219                name: "Estimate",
1220                width: Width::Fixed,
1221                priority: Priority::Optional,
1222            },
1223        ];
1224        let after = [
1225            Column::new("Title"),
1226            Column::new("Project"), // inserted
1227            Column {
1228                name: "Estimate",
1229                width: Width::Fixed,
1230                priority: Priority::Optional,
1231            },
1232        ];
1233
1234        fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
1235            cols.iter()
1236                .filter(|c| !c.kept_at(Priority::Secondary))
1237                .map(|c| c.name)
1238                .collect()
1239        }
1240        assert_eq!(dropped(&before), ["Estimate"]);
1241        assert_eq!(dropped(&after), ["Estimate"]);
1242    }
1243
1244    #[test]
1245    fn an_arrangement_carries_the_tab_group_as_a_modifier() {
1246        // goingson uses the tab group inside the content region rather than
1247        // instead of one, so it is not a third arrangement.
1248        let go = Arrangement::ListDetail { tabbed: true };
1249        let plain = Arrangement::ListDetail { tabbed: false };
1250        assert_ne!(go, plain);
1251        assert_ne!(go, Arrangement::SidebarContent);
1252    }
1253
1254    #[test]
1255    fn readiness_names_the_state_and_not_the_shimmer() {
1256        // Two members and no third. If a skeleton ever appears in this enum,
1257        // the deferral rule has been broken.
1258        assert_ne!(Readiness::Ready, Readiness::Pending);
1259    }
1260}