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