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