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/// How much of a set is done.
755///
756/// Added 0.10.0. Nine sites across the two webview apps drew a bar and nothing
757/// here named one, so every described screen concatenated the two numbers into
758/// its heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m
759/// est, over". Every fact survives that and the reading does not, which is the
760/// same loss `RowPart::Tokens` closed when a toned status badge became prose.
761///
762/// # Why a pair and not a percentage
763///
764/// Both numbers, not the percentage the apps compute from them. The percentage
765/// was the obvious shape and it had already been tried: goingson's
766/// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
767/// away the one case the bar exists to show — 45 minutes tracked against a
768/// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
769/// it to recover the fact the clamp dropped. A pair keeps the over-run without a
770/// companion flag, and [`percent`](Meter::percent) is still one call away for a
771/// renderer that wants it.
772///
773/// The pair is also what the apps already have at every site. All seven
774/// determinate bars write the ratio into the accessible layer and never the
775/// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
776/// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
777/// percentage member would have made [`label`](Meter::label) mandatory at every
778/// call site, which is the concatenated text this member removes, moved one
779/// layer down.
780///
781/// # What this is not
782///
783/// The progress of an *operation*. Two of the nine sites are that — goingson's
784/// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
785/// purpose. Both are imperative controllers over a live handle, driven by a tick
786/// or an event stream, and a description is built once and dropped. Holding one
787/// would mean growing a way to update a description between renders, which is a
788/// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
789/// honest part.
790///
791/// The two cases are distinguishable in the markup rather than by taste: every
792/// determinate bar in both apps carries a tone, and neither operation bar
793/// carries one. Two codebases drew that line the same way without coordinating.
794#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
795pub struct Meter<'a> {
796 /// How much is done. May exceed [`total`](Self::total), and that is the
797 /// case worth drawing.
798 pub done: u32,
799 /// How much there is to do. Zero means there is no set, not that the set is
800 /// complete.
801 pub total: u32,
802 /// What the proportion means right now.
803 ///
804 /// Carried rather than derived, because no renderer can work it out. The
805 /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
806 /// a time estimate, and goingson picks between them from `is_over_estimate`,
807 /// a fact about the data and not about the number.
808 pub tone: Tone,
809 /// What is being counted, if the bar says so: "subtasks", "tasks".
810 ///
811 /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
812 /// and the two numbers; handing it the assembled string would put the
813 /// sentence order in the description, where a terminal at one line and a
814 /// tooltip want different ones.
815 pub label: Option<&'a str>,
816}
817
818impl<'a> Meter<'a> {
819 /// A proportion with no tone and no label.
820 #[must_use]
821 pub const fn new(done: u32, total: u32) -> Self {
822 Self {
823 done,
824 total,
825 tone: Tone::Neutral,
826 label: None,
827 }
828 }
829
830 /// What the proportion means.
831 #[must_use]
832 pub const fn tone(mut self, tone: Tone) -> Self {
833 self.tone = tone;
834 self
835 }
836
837 /// What is being counted.
838 #[must_use]
839 pub const fn label(mut self, label: &'a str) -> Self {
840 self.label = Some(label);
841 self
842 }
843
844 /// How full the bar is, 0 to 100, clamped.
845 ///
846 /// For drawing, which is the only thing a clamped number is good for. Ask
847 /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
848 /// is `time_progress`'s bug again with the clamp moved.
849 ///
850 /// An empty set reads as 0. Nothing is done, because there is nothing to do
851 /// and no bar to fill; the apps guard on the count before drawing at all.
852 #[must_use]
853 pub const fn percent(&self) -> u8 {
854 if self.total == 0 {
855 return 0;
856 }
857 let scaled = (self.done as u64 * 100) / self.total as u64;
858 if scaled > 100 { 100 } else { scaled as u8 }
859 }
860
861 /// Whether more is done than there was to do.
862 ///
863 /// The fact [`percent`](Self::percent) destroys, kept reachable so a
864 /// renderer can mark the over-run rather than drawing a full bar and
865 /// implying it landed exactly.
866 #[must_use]
867 pub const fn overflowing(&self) -> bool {
868 self.done > self.total
869 }
870
871 /// Whether there is a set at all.
872 ///
873 /// A meter over nothing is sayable on purpose, for the same reason a field
874 /// with no options is: it is what an app with an unloaded count actually
875 /// has, and a renderer that shows an empty bar says so on screen rather than
876 /// dividing by zero.
877 #[must_use]
878 pub const fn is_empty(&self) -> bool {
879 self.total == 0
880 }
881}
882
883/// A named part of a screen.
884///
885/// The thing `makeover-geometry` deliberately does not name: it names the space
886/// *between* things by relationship, and nothing named the things. Six named
887/// members, taken from what the two webview apps actually use, plus
888/// [`Region::Bespoke`] for the parts no description should reach. Both apps'
889/// `layout.css` currently names exactly two things, `.raised` and `.well`, so
890/// this layer is absent rather than divergent, which makes it the cheapest of
891/// the schemas to add and the easiest to over-build.
892#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
893pub enum Region<'a> {
894 /// A full-width strip with a title slot and an actions cluster, either of
895 /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
896 /// `.header` and `.detail-header` are all this, differing only in which
897 /// slots they fill.
898 Band,
899 /// A persistent column beside the content, holding navigation.
900 Sidebar,
901 /// A region of content with its own scroll.
902 Pane,
903 /// Two panes side by side, where the left chooses what the right shows.
904 Split,
905 /// A set of panes, one visible at a time, with a [`Selector::Tabs`] above.
906 TabGroup,
907 /// Content over a scrim, taking input until dismissed.
908 Modal,
909 /// A region this crate names the *place* of and nothing else. The app owns
910 /// what goes in it.
911 ///
912 /// The escape hatch, and the thing that keeps the description honest about
913 /// its own limits. A day-plan timeline, a kanban board, a calendar and the
914 /// paint interaction over the timeline are not describable here and are not
915 /// going to become describable: a description expressive enough to produce
916 /// a timeline is a widget library wearing a description's name.
917 ///
918 /// But a screen containing one still has to be a screen. Without this
919 /// member the description covers only the boring screens, and the four that
920 /// make goingson worth using would need a second, undescribed path beside
921 /// the router. Two paths is how the vocabulary starts drifting from the app
922 /// again, which is the exact failure this crate exists to end.
923 ///
924 /// So the description says "a thing called `day-plan` goes here" and stops.
925 /// The name is opaque: this crate never interprets it, and no renderer is
926 /// expected to know what it means beyond handing the space over.
927 Bespoke {
928 /// What the app calls it. Never interpreted here.
929 name: &'a str,
930 },
931}
932
933impl Region<'_> {
934 /// How the region sits on what is behind it.
935 #[must_use]
936 pub const fn depth(self) -> Depth {
937 match self {
938 Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
939 // A pane is looked into, the same as a table body or a tag tree.
940 Self::Pane => Depth::Well,
941 Self::Modal => Depth::Raised,
942 // Flat because it inherits: a bespoke region takes the depth of
943 // whatever frames it. An app that wants its timeline in a well puts
944 // it in a `Pane`, which composes rather than adding a knob here.
945 Self::Bespoke { .. } => Depth::Flat,
946 }
947 }
948
949 /// Whether this crate can say anything about the region's contents.
950 ///
951 /// A renderer walks the description and hands every region it understands
952 /// to the right drawing code. This is how it tells the two apart, and the
953 /// reason it is a method rather than a `matches!` at each renderer: there
954 /// is exactly one opaque member and there should stay exactly one.
955 #[must_use]
956 pub const fn described(self) -> bool {
957 !matches!(self, Self::Bespoke { .. })
958 }
959}
960
961/// How a screen is laid out.
962///
963/// Two, and the second is not a variant of the first. goingson is list-detail,
964/// Balanced Breakfast is sidebar plus content, and neither app has a third.
965/// The tab group is a modifier rather than a member, because goingson uses it
966/// *inside* the same content region rather than instead of one.
967///
968/// This exists at all because the router has to be able to express a screen
969/// rather than only a control. Discovering the arrangement layer missing after
970/// the renderers exist is a redesign; naming two now is a morning.
971#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
972pub enum Arrangement {
973 /// A list that chooses what the detail beside it shows.
974 ListDetail {
975 /// Whether the detail side is a [`Region::TabGroup`].
976 tabbed: bool,
977 },
978 /// Navigation down the side, content filling the rest.
979 SidebarContent,
980}
981
982/// What kind of value a form field takes.
983///
984/// The union of the two vocabularies that diverged, which is what triggered
985/// this crate. They have since converged on their own: both apps now have a
986/// `renderFormField` emitting the same anatomy, and what is left differing is
987/// the kind set, the error shape, and whether the return is a string or a node.
988///
989/// Validation is deliberately absent. Neither app has a shared story (goingson
990/// validates after collecting the form data, with per-field transform hooks;
991/// Balanced Breakfast has `required` and nothing else), and a schema that
992/// describes fields but not constraints acquires a constraint layer per app,
993/// which is exactly how the current divergence started. Naming it absent is a
994/// decision; leaving it unmentioned would not be.
995/// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
996/// the set keeps growing, so growth must not be a lockstep event. Email, Url
997/// and Tel arriving in 0.5.0 is the second growth in two releases.
998#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
999#[non_exhaustive]
1000pub enum FieldKind {
1001 /// A single line of text.
1002 Text,
1003 /// A single line of text that must never be echoed, logged or round-tripped
1004 /// through anything that might persist it.
1005 Secret,
1006 /// A number.
1007 Number,
1008 /// An email address.
1009 ///
1010 /// Distinct from [`Text`](Self::Text) because the distinction is not
1011 /// decoration: a webview renderer emits `type="email"`, which on a touch
1012 /// device changes the keyboard that appears and turns on the platform's own
1013 /// validation. goingson ships to iOS, so collapsing this into text costs a
1014 /// keyboard with no `@` on it.
1015 ///
1016 /// Added 0.5.0, from goingson's contact form.
1017 Email,
1018 /// A URL. Same reasoning as [`Email`](Self::Email).
1019 ///
1020 /// Added 0.5.0, from goingson's contact-social and contact-feed forms.
1021 Url,
1022 /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
1023 /// clearest case of it: the keyboard is a numeric pad rather than letters.
1024 ///
1025 /// Added 0.5.0, from goingson's contact-phone form.
1026 Tel,
1027 /// Several lines of text.
1028 Textarea,
1029 /// One of a fixed set, offered behind a control that shows one at a time.
1030 Select,
1031 /// One of a fixed set, with every option on screen at once.
1032 ///
1033 /// Not a presentation of [`Select`](Self::Select), which is the reading to
1034 /// resist: what differs is a property of the *question*. A choice that is
1035 /// consequential or irreversible has to be readable without opening
1036 /// anything, because a closed control shows one option and hides the rest,
1037 /// and the one it shows is whichever was current before the user had read
1038 /// the alternatives. audiofiles asks whether a library copies samples into
1039 /// its store or references them where they lie — which cannot be changed
1040 /// afterwards — and had already promoted that out of a checkbox by hand,
1041 /// with a comment giving this reason, before the description could say it.
1042 ///
1043 /// It is also the one HTML input type this enum was missing. Everything
1044 /// else here is an `<input type=...>`, a `<select>` or a `<textarea>`, and
1045 /// the hole was `radio`.
1046 ///
1047 /// Added 0.8.1, from audiofiles' Add Library form.
1048 Radio,
1049 /// On or off.
1050 Checkbox,
1051 /// Carried through the form and never shown.
1052 Hidden,
1053}
1054
1055impl FieldKind {
1056 /// Whether the field is drawn at all.
1057 #[must_use]
1058 pub const fn visible(self) -> bool {
1059 !matches!(self, Self::Hidden)
1060 }
1061
1062 /// Whether the value must be kept out of logs and diagnostics.
1063 #[must_use]
1064 pub const fn confidential(self) -> bool {
1065 matches!(self, Self::Secret)
1066 }
1067
1068 /// Where the field's own label sits.
1069 ///
1070 /// A checkbox labels itself on the right of the box; everything else takes
1071 /// a label above. Both webview apps already do this and both special-case
1072 /// it inline, which is the tell that it belongs in the description.
1073 ///
1074 /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
1075 /// naming: its *options* each label themselves, but the field still asks a
1076 /// question above them, so the group takes a label like everything else.
1077 #[must_use]
1078 pub const fn labels_itself(self) -> bool {
1079 matches!(self, Self::Checkbox)
1080 }
1081
1082 /// Whether the kind reads [`Field::options`].
1083 ///
1084 /// Two kinds do, so the pair is named once here rather than spelled out at
1085 /// each renderer and again in [`Field::options`]' own doc, where "every
1086 /// kind but `Select`" was true for exactly one release. A third
1087 /// option-taking kind should land here and nowhere else.
1088 #[must_use]
1089 pub const fn offers_options(self) -> bool {
1090 matches!(self, Self::Select | Self::Radio)
1091 }
1092}
1093
1094/// One option offered by a field [`FieldKind::offers_options`] accepts.
1095///
1096/// Two strings, because the submitted value and the read label are different
1097/// facts and every renderer that has tried to collapse them has had to
1098/// un-collapse them later. `makeover-webview` invented this shape writing its
1099/// form emitter and it is taken here unchanged; moving it down rather than
1100/// re-deriving it is the point, since the second and third renderers were each
1101/// going to arrive at a near-miss of it.
1102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1103pub struct Choice<'a> {
1104 /// What is submitted.
1105 pub value: &'a str,
1106 /// What is read.
1107 pub label: &'a str,
1108}
1109
1110impl<'a> Choice<'a> {
1111 /// An option whose submitted value is also its label.
1112 #[must_use]
1113 pub const fn plain(value: &'a str) -> Self {
1114 Self {
1115 value,
1116 label: value,
1117 }
1118 }
1119}
1120
1121/// One field of a form.
1122///
1123/// Borrowed rather than owned: a description is built, read once by a renderer,
1124/// and dropped. Nothing here outlives the screen it describes.
1125///
1126/// # What it carries, and what it does not
1127///
1128/// Stated here so the next renderer does not re-ask, which is what the first
1129/// two both did. It carries everything a renderer needs to *draw* the field:
1130/// its kind, what it is called, what it is asked for, its standing help, what
1131/// is wrong with it now, whether it is compulsory, whether it hides behind a
1132/// disclosure, its ghost text, and the options it offers.
1133///
1134/// It does not carry the **current value**, and it is not going to. That is the
1135/// one thing here that is genuinely renderer state: a webview reads it back out
1136/// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
1137/// and writes through it, and a terminal keeps an edit buffer. A description
1138/// that carried the value would have to carry a way to write it back, at which
1139/// point it is a form model and no longer a description.
1140///
1141/// **Validation** is absent for the reason [`FieldKind`] records: [`error`] is
1142/// the *result* of validating, supplied by whoever validated. Nothing here
1143/// decides that a value is wrong.
1144///
1145/// [`error`]: Field::error
1146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1147pub struct Field<'a> {
1148 /// What kind of value it takes.
1149 pub kind: FieldKind,
1150 /// The name the value is submitted under.
1151 pub name: &'a str,
1152 /// What the user is asked for.
1153 pub label: &'a str,
1154 /// Standing help, shown whether or not anything is wrong.
1155 pub hint: Option<&'a str>,
1156 /// What is currently wrong with the value.
1157 pub error: Option<&'a str>,
1158 /// Ghost text shown while the field is empty.
1159 ///
1160 /// User-facing text, and it sits with `label` and `hint` rather than with
1161 /// the value because it is a property of the *question* and not of the
1162 /// answer. It lived renderer-side in `makeover-webview` until 0.8.0 for one
1163 /// reason and it was not a reading on where it belonged: adding a field to
1164 /// a published struct is a breaking change.
1165 ///
1166 /// Not a substitute for a label. A field labelled only by its placeholder
1167 /// loses its label the moment anything is typed, and no renderer here can
1168 /// make that not happen, so the description keeps both.
1169 pub placeholder: Option<&'a str>,
1170 /// The options offered, in the order they are offered.
1171 ///
1172 /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
1173 /// described with no options is sayable on purpose: it is what an app with
1174 /// an unfinished-loading option list actually has, and a renderer showing
1175 /// an empty control says so on screen rather than in a log.
1176 ///
1177 /// Which option is *current* is not here. That is the value, and the value
1178 /// is renderer state.
1179 pub options: &'a [Choice<'a>],
1180 /// Whether the form refuses to submit without it.
1181 pub required: bool,
1182 /// Whether the field lives behind a "more options" disclosure.
1183 pub extended: bool,
1184}
1185
1186impl<'a> Field<'a> {
1187 /// A plain required-nothing field of the given kind.
1188 #[must_use]
1189 pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
1190 Self {
1191 kind,
1192 name,
1193 label,
1194 hint: None,
1195 error: None,
1196 placeholder: None,
1197 options: &[],
1198 required: false,
1199 extended: false,
1200 }
1201 }
1202
1203 /// A select offering the given options.
1204 ///
1205 /// One of the two kinds under-described by [`Field::new`], so it gets a
1206 /// constructor rather than leaving every call site to remember that a
1207 /// select with an empty `options` renders as an empty select.
1208 #[must_use]
1209 pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1210 Self::offering(FieldKind::Select, name, label, options)
1211 }
1212
1213 /// A radio group offering the given options.
1214 ///
1215 /// The other. Same hazard as [`select`](Self::select) and a worse one: a
1216 /// radio group with no options draws nothing at all, so a call site that
1217 /// forgot them has an empty rectangle rather than a visibly empty control.
1218 #[must_use]
1219 pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
1220 Self::offering(FieldKind::Radio, name, label, options)
1221 }
1222
1223 /// The shared body of the two constructors that take options.
1224 ///
1225 /// Private, and keyed on the kind rather than exposed, because the two
1226 /// public names are the point: a call site says which question it is
1227 /// asking, not which flag it is setting.
1228 const fn offering(
1229 kind: FieldKind,
1230 name: &'a str,
1231 label: &'a str,
1232 options: &'a [Choice<'a>],
1233 ) -> Self {
1234 Self {
1235 options,
1236 ..Self::new(kind, name, label)
1237 }
1238 }
1239
1240 /// Whether the field is currently reporting a problem.
1241 ///
1242 /// Read this rather than testing `error.is_some()` at each renderer: the
1243 /// error state has to mark the field's whole group and not only the
1244 /// message, because a renderer with no descendant selectors (egui, a
1245 /// terminal) cannot find the group from the message. goingson already marks
1246 /// the group and Balanced Breakfast does not, so goingson's shape is the
1247 /// one taken here.
1248 #[must_use]
1249 pub const fn invalid(&self) -> bool {
1250 self.error.is_some()
1251 }
1252}
1253
1254/// How much room a column asks for.
1255///
1256/// An intent, so the actual floor stays with `makeover-geometry`. goingson's
1257/// task table spells these as `minmax(200px, 1fr)`, `140px` and content-sized;
1258/// only the first three words of that survive deferral.
1259/// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
1260/// renderer matches on this and a vocabulary that grows must not break every
1261/// renderer when it does.
1262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1263#[non_exhaustive]
1264pub enum Width {
1265 /// Takes what it needs and no more.
1266 Content,
1267 /// A fixed share, the same at every width.
1268 Fixed,
1269 /// Absorbs whatever is left over.
1270 Fill,
1271}
1272
1273/// What a column is worth when there is not room for all of them.
1274///
1275/// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
1276/// drops. This replaces addressing columns by position, which is what both
1277/// webview apps do today and is a live bug rather than only verbosity. goingson
1278/// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
1279/// inserting a column silently hides the wrong one.
1280/// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
1281/// whole point of the type, so a new tier has to be declared in its place in
1282/// the sequence rather than appended.
1283#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1284#[non_exhaustive]
1285pub enum Priority {
1286 /// Dropped first.
1287 Optional,
1288 /// Dropped once the optional columns are gone.
1289 Secondary,
1290 /// Never dropped. Without it the row does not identify itself.
1291 Essential,
1292}
1293
1294/// One column of a table.
1295///
1296/// Described once. The grid track, the cell order and the drop behaviour are
1297/// all derived from this, rather than being three hand-written encodings that
1298/// must agree and are never checked against each other.
1299#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1300pub struct Column<'a> {
1301 /// The heading, and the name the cell is addressed by.
1302 pub name: &'a str,
1303 /// How much room it asks for.
1304 pub width: Width,
1305 /// What it is worth when room runs out.
1306 pub priority: Priority,
1307}
1308
1309impl<'a> Column<'a> {
1310 /// A column that absorbs slack and drops after the optional ones.
1311 #[must_use]
1312 pub const fn new(name: &'a str) -> Self {
1313 Self {
1314 name,
1315 width: Width::Fill,
1316 priority: Priority::Secondary,
1317 }
1318 }
1319
1320 /// Whether this column survives at the given cutoff.
1321 ///
1322 /// A renderer narrows by raising the cutoff, and never by counting
1323 /// positions.
1324 #[must_use]
1325 pub const fn kept_at(&self, cutoff: Priority) -> bool {
1326 (self.priority as u8) >= (cutoff as u8)
1327 }
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332 use super::*;
1333
1334 #[test]
1335 fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
1336 // The whole reason this is a pair. goingson's `Task::time_progress`
1337 // clamps to 100 and then carries `is_over_estimate` beside it to say
1338 // what the clamp dropped; a meter says both from one fact.
1339 let over = Meter::new(45, 30);
1340 assert_eq!(over.percent(), 100);
1341 assert!(over.overflowing());
1342
1343 let exact = Meter::new(30, 30);
1344 assert_eq!(exact.percent(), over.percent());
1345 assert!(!exact.overflowing());
1346 }
1347
1348 #[test]
1349 fn an_empty_set_does_not_divide_by_zero() {
1350 // Sayable on purpose, so it has to be answerable. A meter over an
1351 // unloaded count is what an app actually has for a frame.
1352 let none = Meter::new(0, 0);
1353 assert_eq!(none.percent(), 0);
1354 assert!(none.is_empty());
1355 assert!(!none.overflowing());
1356 }
1357
1358 #[test]
1359 fn the_ratio_survives_where_a_percentage_would_not() {
1360 // Given 43 nothing can recover "3 of 7", which is why the numbers are
1361 // carried and the label names only the noun.
1362 let m = Meter::new(3, 7).label("subtasks");
1363 assert_eq!(m.percent(), 42);
1364 assert_eq!((m.done, m.total), (3, 7));
1365 assert_eq!(m.label, Some("subtasks"));
1366 }
1367
1368 #[test]
1369 fn tone_is_carried_because_no_renderer_can_derive_it() {
1370 // The same fullness means opposite things on two of goingson's bars,
1371 // and only the app knows which.
1372 let subtasks = Meter::new(9, 10).tone(Tone::Success);
1373 let estimate = Meter::new(9, 10).tone(Tone::Danger);
1374 assert_eq!(subtasks.percent(), estimate.percent());
1375 assert_ne!(subtasks.tone, estimate.tone);
1376 // Untoned by default: a bar says nothing about status until something
1377 // says so, the same way a row is not selectable until told.
1378 assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
1379 }
1380
1381 #[test]
1382 fn a_meter_does_not_overflow_on_large_counts() {
1383 // done * 100 in u32 would wrap somewhere past 42 million. Counts that
1384 // size are not tasks, but a description layer that silently reports 3%
1385 // for a full bar is worse than one that is slow.
1386 let big = Meter::new(u32::MAX, u32::MAX);
1387 assert_eq!(big.percent(), 100);
1388 assert!(!big.overflowing());
1389 }
1390
1391 #[test]
1392 fn inset_is_raised_with_the_light_moved() {
1393 let (rl, rd) = Bevel::Raised.edges();
1394 let (il, id) = Bevel::Inset.edges();
1395 assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
1396 assert_eq!((il, id), (rd, rl));
1397 }
1398
1399 #[test]
1400 fn pressing_twice_is_a_no_op() {
1401 for b in [Bevel::Raised, Bevel::Inset] {
1402 assert_eq!(b.pressed().pressed(), b);
1403 }
1404 }
1405
1406 #[test]
1407 fn a_raised_region_is_never_filled_with_a_recessed_surface() {
1408 // The bug this vocabulary exists to make unrepresentable.
1409 assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1410 assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
1411 assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
1412 assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
1413 }
1414
1415 #[test]
1416 fn state_is_orthogonal_to_depth() {
1417 // The reason State is its own axis and not a Depth member: a disabled
1418 // button and a disabled field are both disabled and are not the same
1419 // shape, which one shared variant could not have said.
1420 assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
1421 assert_eq!(Depth::Well.fill(), Some(Fill::Well));
1422 assert!(State::Disabled.suppresses_interaction());
1423 }
1424
1425 #[test]
1426 fn only_disabled_stops_answering() {
1427 // Focus is a thing you can still click. Getting this backwards is how
1428 // a focus ring ends up on something inert.
1429 assert!(!State::Focus.suppresses_interaction());
1430 assert!(State::Disabled.suppresses_interaction());
1431 }
1432
1433 #[test]
1434 fn both_states_resolve_against_intents_makeover_already_derives() {
1435 // Neither needs a new token, so this costs no `makeover` release.
1436 assert_eq!(State::Focus.token(), "focus-ring");
1437 assert_eq!(State::Disabled.token(), "content-muted");
1438 }
1439
1440 #[test]
1441 fn flat_has_neither_edge_nor_fill() {
1442 assert_eq!(Depth::Flat.bevel(), None);
1443 assert_eq!(Depth::Flat.fill(), None);
1444 }
1445
1446 #[test]
1447 fn sunken_is_recessed_by_colour_with_no_edge() {
1448 // The one member carrying a fill without a bevel. A renderer that
1449 // assumes the two arrive together drops the fill silently, which is
1450 // exactly what makeover-webview did before 0.3.0.
1451 assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
1452 assert_eq!(Depth::Sunken.bevel(), None);
1453 }
1454
1455 #[test]
1456 fn sunken_and_flat_are_different_claims() {
1457 // Both edgeless, and only one of them needs a colour. Collapsing them
1458 // is what left an unchosen tab unsayable.
1459 assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
1460 assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
1461 }
1462
1463 #[test]
1464 fn a_sunken_surface_is_not_a_well() {
1465 // Authored in opposite directions: makeover derives surface-well by
1466 // inverting against the theme's content colour, while surface-sunken is
1467 // authored and may sit darker than raised.
1468 assert_ne!(Fill::Sunken, Fill::Well);
1469 assert_eq!(Fill::Sunken.token(), "surface-sunken");
1470 assert_eq!(Fill::Well.token(), "surface-well");
1471 }
1472
1473 #[test]
1474 fn every_selector_describes_both_of_its_states() {
1475 // The gap 0.3.0 closed. Before it, only `chosen` existed and the
1476 // unchosen option fell through to Flat at every renderer.
1477 for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
1478 assert_ne!(
1479 s.chosen(),
1480 s.unchosen(),
1481 "{s:?} cannot tell picked from unpicked"
1482 );
1483 }
1484 }
1485
1486 #[test]
1487 fn only_a_tab_inverts_the_other_way() {
1488 // Tabs recede so the chosen one comes forward; a segment and a toggle
1489 // stand up so the chosen one is held in. That inversion is the whole
1490 // content of "picked" once colour is deferred, and it is why the three
1491 // are not one member with a flag.
1492 assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1493 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1494
1495 for s in [Selector::Segmented, Selector::Toggle] {
1496 assert_eq!(s.unchosen(), Depth::Raised);
1497 assert_eq!(s.chosen(), Depth::Well);
1498 // Held in is what pressing produces: one appearance, two reasons.
1499 assert_eq!(s.unchosen().pressed(), s.chosen());
1500 }
1501 }
1502
1503 #[test]
1504 fn pressing_a_card_makes_a_well() {
1505 assert_eq!(Depth::Raised.pressed(), Depth::Well);
1506 assert_eq!(
1507 Depth::Raised.pressed().bevel(),
1508 Depth::Raised.bevel().map(Bevel::pressed)
1509 );
1510 // Only raised regions respond to being pressed.
1511 assert_eq!(Depth::Flat.pressed(), Depth::Flat);
1512 assert_eq!(Depth::Well.pressed(), Depth::Well);
1513 }
1514
1515 #[test]
1516 fn intents_name_makeover_tokens_and_nothing_else() {
1517 assert_eq!(Edge::Light.token(), "bevel-light");
1518 assert_eq!(Edge::Dark.token(), "bevel-dark");
1519 assert_eq!(Fill::Raised.token(), "surface-raised");
1520 assert_eq!(Fill::Well.token(), "surface-well");
1521 // No value ever leaves this crate.
1522 for t in [
1523 Edge::Light.token(),
1524 Edge::Dark.token(),
1525 Tone::Danger.token(),
1526 Tone::Neutral.token(),
1527 State::Focus.token(),
1528 State::Disabled.token(),
1529 ] {
1530 assert!(!t.starts_with('#'), "{t} looks like a value");
1531 assert!(
1532 !t.chars().next().unwrap().is_ascii_digit(),
1533 "{t} is a value"
1534 );
1535 }
1536 }
1537
1538 #[test]
1539 fn a_badge_cannot_be_pressed_and_a_chip_latches() {
1540 // The one line that runs through all three apps' taxonomies.
1541 assert!(!Token::Badge.interactive());
1542 assert!(Token::Chip { removable: false }.interactive());
1543 assert!(Token::Chip { removable: true }.interactive());
1544
1545 // A badge is a label, so giving it an edge would lie about it.
1546 assert_eq!(Token::Badge.depth(false), Depth::Flat);
1547 assert_eq!(Token::Badge.depth(true), Depth::Flat);
1548
1549 // A latched chip wears the same shape a pressed one does.
1550 let chip = Token::Chip { removable: false };
1551 assert_eq!(chip.depth(false), Depth::Raised);
1552 assert_eq!(chip.depth(true), Depth::Raised.pressed());
1553 }
1554
1555 #[test]
1556 fn a_toast_and_a_banner_differ_in_more_than_placement() {
1557 assert!(Notice::Toast.transient());
1558 assert!(!Notice::Banner.transient());
1559 // A toast floats above the page; a banner rests in the flow.
1560 assert_eq!(Notice::Toast.fill(), Fill::Overlay);
1561 assert_eq!(Notice::Banner.fill(), Fill::Raised);
1562 }
1563
1564 #[test]
1565 fn only_the_actions_part_hides_until_hovered() {
1566 for p in [
1567 RowPart::Primary,
1568 RowPart::Secondary,
1569 RowPart::Meta,
1570 RowPart::Tokens,
1571 ] {
1572 assert!(!p.revealed_on_hover(), "{p:?} should always be visible");
1573 }
1574 assert!(RowPart::Actions.revealed_on_hover());
1575 // Emphasis falls off down the row, and never rises again.
1576 assert_eq!(RowPart::Primary.intent(), "content");
1577 assert_eq!(RowPart::Secondary.intent(), "content-secondary");
1578 assert_eq!(RowPart::Meta.intent(), "content-muted");
1579 }
1580
1581 #[test]
1582 fn a_token_part_carries_no_intent_of_its_own() {
1583 // Each token carries its own tone, so a part-level intent underneath
1584 // would fight the thing sitting on it. Same reasoning as actions, which
1585 // is why they answer alike.
1586 assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
1587 assert_eq!(RowPart::Tokens.intent(), "content");
1588 }
1589
1590 #[test]
1591 fn a_separator_is_what_tells_a_section_from_a_subsection() {
1592 assert!(Heading::Section.separated());
1593 assert!(!Heading::Subsection.separated());
1594 assert!(!Heading::Page.separated());
1595 }
1596
1597 #[test]
1598 fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
1599 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1600 assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1601 // The exception, and the whole folder semantic: the open tab joins its
1602 // pane rather than sinking away from it.
1603 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1604
1605 // A held-in segment is indistinguishable from a pressed raised one,
1606 // which is the economy the light model buys over a colour swap.
1607 assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
1608
1609 // A toggle stands alone; the other two are built out of parts that
1610 // touch.
1611 assert!(Selector::Segmented.abutting());
1612 assert!(Selector::Tabs.abutting());
1613 assert!(!Selector::Toggle.abutting());
1614 }
1615
1616 #[test]
1617 fn a_pane_is_looked_into_and_a_band_is_not() {
1618 assert_eq!(Region::Pane.depth(), Depth::Well);
1619 assert_eq!(Region::Modal.depth(), Depth::Raised);
1620 for r in [
1621 Region::Band,
1622 Region::Sidebar,
1623 Region::Split,
1624 Region::TabGroup,
1625 ] {
1626 assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
1627 }
1628 }
1629
1630 #[test]
1631 fn exactly_one_region_is_opaque() {
1632 // The escape hatch is one member and stays one member. If a second
1633 // undescribed region ever appears, the description has started
1634 // conceding rather than deferring.
1635 for r in [
1636 Region::Band,
1637 Region::Sidebar,
1638 Region::Pane,
1639 Region::Split,
1640 Region::TabGroup,
1641 Region::Modal,
1642 ] {
1643 assert!(r.described(), "{r:?} should be describable");
1644 }
1645 assert!(!Region::Bespoke { name: "day-plan" }.described());
1646 }
1647
1648 #[test]
1649 fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
1650 // The app owns the contents, not the placement. An app that wants its
1651 // timeline in a well frames it in a Pane.
1652 assert_eq!(Region::Bespoke { name: "day-plan" }.depth(), Depth::Flat);
1653 assert_eq!(Region::Bespoke { name: "kanban" }.depth(), Depth::Flat);
1654 }
1655
1656 #[test]
1657 fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
1658 // The argument the member exists for: goingson's day-plan has to be
1659 // routable, or the description covers only the boring screens and the
1660 // interesting four need a second path beside the router.
1661 let day_plan = [
1662 Region::Band,
1663 Region::Bespoke { name: "day-plan" },
1664 Region::Sidebar,
1665 ];
1666 assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
1667 assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
1668 }
1669
1670 #[test]
1671 fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
1672 let secret = Field::new(FieldKind::Secret, "password", "Password");
1673 assert!(secret.kind.confidential());
1674 assert!(secret.kind.visible());
1675
1676 assert!(!FieldKind::Hidden.visible());
1677 // Nothing else is confidential, or the marker means nothing.
1678 for k in [
1679 FieldKind::Text,
1680 FieldKind::Number,
1681 FieldKind::Textarea,
1682 FieldKind::Select,
1683 FieldKind::Checkbox,
1684 FieldKind::Hidden,
1685 ] {
1686 assert!(!k.confidential(), "{k:?} should not be confidential");
1687 }
1688
1689 // Only a checkbox carries its own label.
1690 assert!(FieldKind::Checkbox.labels_itself());
1691 assert!(!FieldKind::Text.labels_itself());
1692 }
1693
1694 #[test]
1695 fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
1696 let text = Field::new(FieldKind::Text, "title", "Title");
1697 assert!(text.options.is_empty());
1698 assert_eq!(text.placeholder, None);
1699
1700 let sizes = [Choice::plain("small"), Choice::plain("large")];
1701 let select = Field::select("size", "Size", &sizes);
1702 assert_eq!(select.kind, FieldKind::Select);
1703 assert_eq!(select.options.len(), 2);
1704 }
1705
1706 #[test]
1707 fn a_choice_says_what_submits_and_what_is_read_apart() {
1708 // The whole reason it is two strings. `plain` is the case where they
1709 // coincide, and it is a shorthand rather than the general shape.
1710 let plain = Choice::plain("7");
1711 assert_eq!((plain.value, plain.label), ("7", "7"));
1712
1713 let spelled = Choice {
1714 value: "7",
1715 label: "One week",
1716 };
1717 assert_ne!(spelled.value, spelled.label);
1718 }
1719
1720 #[test]
1721 fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
1722 // Both offer a fixed set and both read `options`, so the two
1723 // constructors differ in exactly one thing. That one thing is the
1724 // point: a renderer decides whether the alternatives are readable
1725 // without opening anything, and it can only decide that if the
1726 // description said which question was asked.
1727 let styles = [
1728 Choice {
1729 value: "copy",
1730 label: "Copy samples in",
1731 },
1732 Choice {
1733 value: "reference",
1734 label: "Reference in place",
1735 },
1736 ];
1737 let radio = Field::radio("storage", "Storage style", &styles);
1738 let select = Field::select("storage", "Storage style", &styles);
1739
1740 assert_eq!(radio.kind, FieldKind::Radio);
1741 assert_ne!(radio.kind, select.kind);
1742 assert_eq!(radio.options, select.options);
1743 assert_eq!(
1744 Field {
1745 kind: select.kind,
1746 ..radio
1747 },
1748 select
1749 );
1750 }
1751
1752 #[test]
1753 fn exactly_the_option_taking_kinds_say_so() {
1754 // The renderers branch on this rather than on a list of their own, so
1755 // a kind added without a decision here renders its options nowhere.
1756 assert!(FieldKind::Select.offers_options());
1757 assert!(FieldKind::Radio.offers_options());
1758 for kind in [
1759 FieldKind::Text,
1760 FieldKind::Secret,
1761 FieldKind::Number,
1762 FieldKind::Email,
1763 FieldKind::Url,
1764 FieldKind::Tel,
1765 FieldKind::Textarea,
1766 FieldKind::Checkbox,
1767 FieldKind::Hidden,
1768 ] {
1769 assert!(!kind.offers_options(), "{kind:?} does not offer options");
1770 }
1771 }
1772
1773 #[test]
1774 fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
1775 // The near-miss: each option is labelled beside its own button, so a
1776 // renderer could plausibly read the group as self-labelling and drop
1777 // the question. Checkbox is the only kind that does that.
1778 assert!(!FieldKind::Radio.labels_itself());
1779 assert!(FieldKind::Checkbox.labels_itself());
1780 }
1781
1782 #[test]
1783 fn a_select_with_no_options_is_sayable() {
1784 // An app whose option list has not loaded has exactly this. Making it
1785 // unrepresentable would push the state somewhere less visible, and a
1786 // renderer drawing an empty select reports it on screen.
1787 let loading = Field::select("project", "Project", &[]);
1788 assert!(loading.options.is_empty());
1789 }
1790
1791 #[test]
1792 fn the_description_carries_the_question_and_never_the_answer() {
1793 // The line 0.8.0 drew. Placeholder and options are properties of what
1794 // is being asked; the current value is what came back, and no field
1795 // here holds one.
1796 let f = Field {
1797 placeholder: Some("yyyy-mm-dd"),
1798 ..Field::new(FieldKind::Text, "due", "Due")
1799 };
1800 assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
1801 // A placeholder is not a label, and having one does not excuse the
1802 // field from carrying the other.
1803 assert_eq!(f.label, "Due");
1804 }
1805
1806 #[test]
1807 fn a_field_reports_its_own_error_state() {
1808 let mut f = Field::new(FieldKind::Text, "title", "Title");
1809 assert!(!f.invalid());
1810 f.error = Some("Required");
1811 assert!(f.invalid());
1812 }
1813
1814 #[test]
1815 fn columns_drop_by_priority_and_never_by_position() {
1816 let cols = [
1817 Column {
1818 name: "Title",
1819 width: Width::Fill,
1820 priority: Priority::Essential,
1821 },
1822 Column {
1823 name: "Due",
1824 width: Width::Fixed,
1825 priority: Priority::Secondary,
1826 },
1827 Column {
1828 name: "Estimate",
1829 width: Width::Fixed,
1830 priority: Priority::Optional,
1831 },
1832 ];
1833
1834 // Widest: everything survives.
1835 assert_eq!(
1836 cols.iter()
1837 .filter(|c| c.kept_at(Priority::Optional))
1838 .count(),
1839 3
1840 );
1841 // Narrower: the optional column goes first.
1842 let kept: Vec<_> = cols
1843 .iter()
1844 .filter(|c| c.kept_at(Priority::Secondary))
1845 .map(|c| c.name)
1846 .collect();
1847 assert_eq!(kept, ["Title", "Due"]);
1848 // Narrowest: only what identifies the row.
1849 let kept: Vec<_> = cols
1850 .iter()
1851 .filter(|c| c.kept_at(Priority::Essential))
1852 .map(|c| c.name)
1853 .collect();
1854 assert_eq!(kept, ["Title"]);
1855 }
1856
1857 #[test]
1858 fn inserting_a_column_does_not_move_what_gets_dropped() {
1859 // The bug the ordinal form has and this form cannot: goingson hides
1860 // `nth-child(n+5)` against a seven-column table, so a column inserted
1861 // anywhere to the left silently hides a different one.
1862 let before = [
1863 Column::new("Title"),
1864 Column {
1865 name: "Estimate",
1866 width: Width::Fixed,
1867 priority: Priority::Optional,
1868 },
1869 ];
1870 let after = [
1871 Column::new("Title"),
1872 Column::new("Project"), // inserted
1873 Column {
1874 name: "Estimate",
1875 width: Width::Fixed,
1876 priority: Priority::Optional,
1877 },
1878 ];
1879
1880 fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
1881 cols.iter()
1882 .filter(|c| !c.kept_at(Priority::Secondary))
1883 .map(|c| c.name)
1884 .collect()
1885 }
1886 assert_eq!(dropped(&before), ["Estimate"]);
1887 assert_eq!(dropped(&after), ["Estimate"]);
1888 }
1889
1890 #[test]
1891 fn an_arrangement_carries_the_tab_group_as_a_modifier() {
1892 // goingson uses the tab group inside the content region rather than
1893 // instead of one, so it is not a third arrangement.
1894 let go = Arrangement::ListDetail { tabbed: true };
1895 let plain = Arrangement::ListDetail { tabbed: false };
1896 assert_ne!(go, plain);
1897 assert_ne!(go, Arrangement::SidebarContent);
1898 }
1899
1900 #[test]
1901 fn readiness_names_the_state_and_not_the_shimmer() {
1902 // Two members and no third. If a skeleton ever appears in this enum,
1903 // the deferral rule has been broken.
1904 assert_ne!(Readiness::Ready, Readiness::Pending);
1905 }
1906}