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