Skip to main content

max / makeover-layout

295.2 KB · 6992 lines History Blame Raw
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.** [`Bevel`], [`Edge`], [`Fill`], [`Depth`]: the bevel and the
28 //! surfaces it shapes. Fill and bevel are named together, so a raised bevel
29 //! over a recessed fill is unrepresentable.
30 //! - **Components.** [`Token`] (badge against chip), [`Notice`] (toast against
31 //! banner), [`RowPart`], [`CellPart`], [`Heading`], [`Selector`],
32 //! [`Readiness`], [`Awaiting`], [`Meter`], [`Figure`], [`Track`],
33 //! and [`Tone`], the one intent family they share.
34 //! - **Schemas.** [`Field`] for forms, [`Column`] for lists and tables,
35 //! [`Facet`] for the dimensions a set is narrowed by.
36 //! - **Structure.** [`Region`] for the parts of a screen, [`Arrangement`] for
37 //! how a screen is put together, [`Showing`] for how many of a region's
38 //! children are visible at once.
39 //!
40 //! # What a member is admitted on
41 //!
42 //! A member is added when an app needs a fact the vocabulary cannot state, and
43 //! refused when what it wants is presentation it should be asking a renderer
44 //! for. Three tests, all of which have to pass:
45 //!
46 //! - **Generic against bespoke.** Is this furniture any app would have, or is
47 //! it this app's own? A rule that withholds a word until a second app has
48 //! duplicated the code guarantees the duplication. What the app owns
49 //! keeps [`Region::Handover`] and [`Region::Ceded`].
50 //! - **Every host has an honest answer.** A member no renderer can express
51 //! without borrowing one host's idiom is not a description.
52 //! - **It can be laid out before it is filled.** See *First paint is final
53 //! paint* below.
54 //!
55 //! Count the members a thing needs before refusing it. A refusal is only worth
56 //! as much as the measurement under it.
57 //!
58 //! # What this crate cannot say
59 //!
60 //! - **An address.** What a control calls, and where a button goes. [`Act`]
61 //! names the act and holds no destination.
62 //! - **A current value.** A webview reads it out of the DOM and an
63 //! immediate-mode renderer holds a `&mut` to the app's own field. A
64 //! description carrying it would be a form model.
65 //! - **What has focus.** See below.
66 //! - **A duration or a clock.** No estimate of time remaining, no autosave
67 //! interval, no animation length.
68 //! - **A colour, a size or a position.** The deferral rule.
69 //!
70 //! # Reach, focus and the focus ring
71 //!
72 //! Three terms, and no others, for what sits outside the description.
73 //! **Reach** is which things can take focus and in what order; a browser reads
74 //! it off the document, a TUI derives it from draw order, egui from its own id
75 //! stack. **Focus** is which reached thing has the keyboard right now: the
76 //! renderer's, live, never described and never round-tripped through a
77 //! description. The **focus ring** is the visible cue; the token (`focus-ring`,
78 //! derived by `makeover` from the action colour) is the one shared artifact and
79 //! the drawing is the renderer's. Retired as names for any of this: "focus
80 //! stroke", "focus cue", "wants focus". "Caret" is a different thing — the text
81 //! cursor inside a field — and keeps its name.
82 //!
83 //! # The three tones, and what a colour claims
84 //!
85 //! One rule for how colour says whether a thing can be
86 //! used. Every renderer answers to it, and it is stated here because the
87 //! description is what names the intents.
88 //!
89 //! | the thing | intent |
90 //! |-----------|--------|
91 //! | active, emphasised, the thing itself | `content` |
92 //! | inactive but usable: it still answers a press | `content-secondary` |
93 //! | inert: disabled, or not a control at all | `content-muted` |
94 //!
95 //! `content-muted` is the one with a claim in it. [`State::Disabled`] resolves
96 //! to it, so a live control wearing it is telling the user it will not answer,
97 //! and being wrong about that is worse than being quiet, because the user's
98 //! response is to stop trying. A sortable column heading that was never sorted,
99 //! and every unchosen option in a radio group, read as dead lists if they wear
100 //! it. What is legitimately muted is a caption, a hint, a placeholder, a meter's reading, an axis label: text that
101 //! was never going to answer anything.
102 //!
103 //! The three are one ramp and not three colours. `makeover`'s `Emphasis` derives
104 //! the quieter two from the ink, so "one step back" means the same distance in
105 //! every theme and a renderer cannot land between them by picking its own.
106 //!
107 //! # First paint is final paint
108 //!
109 //! Nothing may change size or position after it is
110 //! first drawn, and nothing may stand in for content that has not arrived yet.
111 //! Both halves are absolute.
112 //!
113 //! It is stated here, rather than left to each renderer, because a renderer can
114 //! only reserve space the description gave it enough to size. A member whose
115 //! size depends on its content therefore owes whatever makes it sizeable while
116 //! the content is still absent, and that is the second admission test for a new
117 //! member: not only does it compose something this crate already names, it can
118 //! be laid out before it is filled.
119 //!
120 //! The mechanism is a reservation, and [`Sort`]'s caret is the worked example.
121 //! The caret is drawn into a box its own width whether or not the column is
122 //! sorted, so pressing a heading cannot reflow the row it sits in. The box names
123 //! no magnitude, which is what keeps it out of `makeover-geometry`'s territory.
124 //! Reserve from what is known; never discover geometry from what has not
125 //! arrived.
126 //!
127 //! The trap is an `Option` that means "not yet". [`Readiness::Pending`] is the
128 //! honest way to say a region is still waiting. An optional *measurement* is
129 //! not: a count that shows up later widens the text that prints it and moves
130 //! everything beside it, which is the reflow this rule exists to forbid. So an
131 //! `Option` on a measurement means the host will never know it — a property of
132 //! the query, fixed for the life of the screen — and a renderer sizes for the
133 //! answer it was handed rather than for the one it hopes is coming.
134 //!
135 //! # Any width, one answer
136 //!
137 //! The sibling of the rule above. That one is
138 //! independence from *when*; this one is independence from *how you got here*.
139 //!
140 //! A rendering is a pure function of the description and the viewport. The same
141 //! description at the same width is the same output, whatever widths came
142 //! before it. No renderer may carry geometry across frames, and none may narrow
143 //! by counting.
144 //!
145 //! The failure this forbids is ordinary enough to be the default everywhere
146 //! else: a page that hides its sidebar below some width, remembers that it hid
147 //! it, and does not bring it back the same way. Layout there is a function of
148 //! `(width, history)`, so dragging a window to 900 wide is a different screen
149 //! depending on whether you came from 1400 or from 600. Nobody chose that; it
150 //! is what measuring and remembering produce.
151 //!
152 //! The mechanism is [`Width`] for what grows and [`Priority`] for what drops.
153 //! Both are declared, both are read off the description, and neither needs a
154 //! measurement. A renderer narrows by raising a cutoff over a total order,
155 //! never by counting what fits and stopping — `makeover-tui`'s table states
156 //! that as its own rule and tests it, and `makeover-webview` reaches the same
157 //! place with `@media` and `display: none`, which is path-independent by
158 //! construction because CSS has nowhere to keep the previous width.
159 //!
160 //! Two things follow for anything new. A member that would need last frame's
161 //! size to lay out this frame is refused, the same way a member that cannot be
162 //! sized before it is filled is refused. And a fact about what disappears
163 //! belongs in the description, because a host that has to infer it can only
164 //! infer it from a measurement.
165 //!
166 //! # Where the description stops
167 //!
168 //! A member is added when an app needs a fact the vocabulary cannot state, and
169 //! refused when what it wants is presentation it should be asking a renderer
170 //! for. It is not a quota, and the goal is every screen described.
171 //!
172 //! A timeline is describable. What it needs and could not previously get is two
173 //! integers, where a thing starts and how long it lasts, which is [`Track`].
174 //! Slot heights, gridline colour, how overlapping things stack and which hour
175 //! scrolls into view stay the renderer's, and `Track` carries none of them.
176 //!
177 //! A kanban board is describable, and the member is [`Region::Columns`]. Every
178 //! card fact is already sayable through `Row`'s parts; what nothing else could
179 //! say is that the columns are *peers*, since [`Arrangement`] offers only
180 //! list-detail and sidebar-content and a board described as either is a lie
181 //! about the screen. Dragging a card between columns does not enter into it: a
182 //! drop's effect is "set status", a discrete action `Row`'s menu already
183 //! carries, and the drag itself is affordance.
184 //!
185 //! A calendar takes no members. The month grid's primacy in calendar apps is an
186 //! artifact of paper: paper cannot be queried, so it has to show every day at
187 //! once as a fallback index, and routes, search and ranking do that job better.
188 //! Three jobs survive that reasoning, and only one of them needs a grid:
189 //!
190 //! 1. **Spans across days**, a stretch of leave, a trip, a sprint. You cannot
191 //! see "away the 3rd to the 17th" in a list without diffing dates. This is
192 //! [`Track`] with [`Unit::Days`], and [`Track::days`] is it.
193 //! 2. **Density at a glance**, which weeks were heavy. That is a heatmap, and a
194 //! heatmap describes as a list.
195 //! 3. **Weekday periodicity**, "every other Tuesday", "the 15th is a Saturday".
196 //! This is the only job that needs the seven-column wrap, because alignment
197 //! is the whole of what makes it visible.
198 //!
199 //! Job 3 is the only open question, and nothing in the tree asks for it. A
200 //! month grid otherwise renders as a [`Table`](crate::Column): seven weekday
201 //! columns, weeks as rows, blanks for the offset. If a screen wants one,
202 //! measure the members it needs before adding any.
203 //!
204 //! [`Region::Handover`] and [`Region::Ceded`] remain for the genuinely
205 //! app-owned. The description
206 //! names the *place* and the app owns the contents, so a screen containing a
207 //! timeline is still a whole screen and still routable. Without it, the screens
208 //! that make an app worth using would need a second, undescribed path beside
209 //! the router, and two paths is how a vocabulary drifts from its app.
210 //!
211 //! [`Region::Widget`] sits between that limit and the primitives, and it does
212 //! not move the limit. A widget is an assembly of members this crate *already*
213 //! has, under a name a renderer may or may not recognise. Anything that needs a
214 //! member the vocabulary does not have is still a finding about the vocabulary
215 //! or still bespoke; naming an assembly buys no new expressive power, which is
216 //! why it is safe to let the set grow outside this crate.
217
218 #![forbid(unsafe_code)]
219
220 /// A colour intent this crate refers to but never resolves.
221 ///
222 /// The string is the token name `makeover` publishes, so a renderer can look
223 /// it up without this crate knowing what colour came back.
224 pub trait Intent {
225 /// The `makeover` intent token this resolves against.
226 fn token(self) -> &'static str;
227 }
228
229 /// Which way the light falls across a two-tone edge.
230 ///
231 /// The whole content of a bevel, once colour and thickness are deferred. The
232 /// light is always assumed to come from the top left: every consumer measured
233 /// agreed on that and none of them ever varied it, so it is an invariant here
234 /// rather than a parameter.
235 ///
236 /// # The two corners that belong to both edges
237 ///
238 /// Top-right and bottom-left are where the lit run meets the shaded one, and
239 /// the description's claim is that they belong to *both*. How a renderer says
240 /// that is its own business, because the answer is bounded by resolution and
241 /// not by taste:
242 ///
243 /// - A terminal cell is roughly 8x17 device pixels, so giving the whole corner
244 /// to one tone thickens that edge by a cell and reads as one run overrunning
245 /// the other. A half-cell glyph divides the cell already, so `makeover-tui`
246 /// splits it and recovers real information. Its box-drawing fallback cannot:
247 /// a single stroke has no half to give, so there both corners go to dark.
248 /// - A pixel bevel is a one-point stroke by default, which makes the corner a
249 /// one-point square. There is nothing to divide — a diagonal seam across one
250 /// point is sub-pixel, and antialiasing renders it as the blend a mitred join
251 /// already produces. So `makeover-immediate` mitres and is *not* diverging;
252 /// it is the same rule at a resolution where the split degenerates.
253 ///
254 /// Stated here so the difference reads as a decision rather than as drift. A
255 /// renderer with room to divide the corner should; one without should mitre or
256 /// pick the shaded tone, and neither is a bug.
257 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
258 pub enum Bevel {
259 /// Lit from the top left: light on top and left, dark on bottom and right.
260 Raised,
261 /// The same edge inverted, which is also the pressed state of anything
262 /// that draws itself [`Bevel::Raised`].
263 Inset,
264 }
265
266 impl Bevel {
267 /// The edge intents, as `(top_left, bottom_right)`.
268 ///
269 /// Split out from any painting because the inversion *is* the idea, and
270 /// it is the one part every renderer implements identically.
271 #[must_use]
272 pub const fn edges(self) -> (Edge, Edge) {
273 match self {
274 Self::Raised => (Edge::Light, Edge::Dark),
275 Self::Inset => (Edge::Dark, Edge::Light),
276 }
277 }
278
279 /// Pressing inverts. A raised control reads as inset while held.
280 ///
281 /// Stated here rather than left to each consumer because a cascade can
282 /// carry a pressed state and an immediate-mode renderer cannot: audiofiles
283 /// resolves this per call site, eighteen times.
284 #[must_use]
285 pub const fn pressed(self) -> Self {
286 match self {
287 Self::Raised => Self::Inset,
288 Self::Inset => Self::Raised,
289 }
290 }
291 }
292
293 /// One side of a bevel, named by the intent it takes.
294 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295 pub enum Edge {
296 /// The lit side.
297 Light,
298 /// The shadowed side.
299 Dark,
300 }
301
302 impl Intent for Edge {
303 fn token(self) -> &'static str {
304 match self {
305 Self::Light => "bevel-light",
306 Self::Dark => "bevel-dark",
307 }
308 }
309 }
310
311 /// A surface intent a region is filled with.
312 ///
313 /// `#[non_exhaustive]`, so a renderer must carry a wildcard arm and a new
314 /// member is additive rather than breaking. The vocabulary exists to grow and
315 /// the renderers exist to disagree about how much of it they answer, so growth
316 /// must not be a lockstep event. The renderer's wildcard is not a hole:
317 /// [`Fill`] is resolved through a fallible lookup, and a missing intent is
318 /// answered with structure rather than with a substituted colour.
319 ///
320 /// [`Sunken`]: Fill::Sunken
321 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
322 #[non_exhaustive]
323 pub enum Fill {
324 /// The page behind everything.
325 Page,
326 /// A surface lifted off the page: cards, controls, menus, toasts.
327 Raised,
328 /// A surface floating above the page rather than resting on it.
329 Overlay,
330 /// The inside of a well.
331 Well,
332 /// A surface set back from the one it sits on, by colour and nothing else.
333 ///
334 /// Not a well. A well is a hole with an edge, and the two are authored in
335 /// opposite directions: `makeover` derives `surface-well` by inverting
336 /// against the theme's own content colour, while `surface-sunken` is
337 /// authored and free to sit darker than raised (goingson's does). Naming
338 /// only the well left the recessed-with-no-edge surface unsayable, which is
339 /// what an unchosen tab is: it recedes so the chosen one can come forward,
340 /// and it carries no bevel of its own.
341 Sunken,
342 }
343
344 // No `fallback` here, deliberately. An earlier cut had `Fill::Well` fall back
345 // to `Fill::Page` so a consumer on makeover 2.2.0, which has no `surface-well`,
346 // had something to paint. makeover-tui found that wrong within a day: page is
347 // the surface a well is usually cut into, so on a terminal that substitution
348 // produces exactly the invisibility it was meant to prevent, and the right
349 // answer there is a drawn edge rather than a different colour.
350 //
351 // Substituting one intent for another is renderer policy. The description says
352 // what the region is and stops.
353
354 impl Intent for Fill {
355 fn token(self) -> &'static str {
356 match self {
357 Self::Page => "surface-page",
358 Self::Raised => "surface-raised",
359 Self::Overlay => "surface-overlay",
360 Self::Well => "surface-well",
361 Self::Sunken => "surface-sunken",
362 }
363 }
364 }
365
366 /// How a region sits relative to the surface behind it.
367 ///
368 /// Fill and bevel are named together because naming them apart is what let
369 /// them disagree. Every consumer measured had at least one region carrying a
370 /// raised bevel over a recessed fill: audiofiles fixed it in `raised_frame`
371 /// and recorded the bug in its doc comment, and Balanced Breakfast still had
372 /// twelve of them a year later. A single name for the pair makes that
373 /// unrepresentable.
374 /// `#[non_exhaustive]` for the same reason as [`Fill`], and in the same
375 /// release: a depth this renderer has no drawing for should cost it a
376 /// wildcard arm, not a compile error and a wait on someone else's publish.
377 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
378 #[non_exhaustive]
379 pub enum Depth {
380 /// Level with its surroundings. No edge.
381 Flat,
382 /// A card laid on the panel it sits in.
383 Raised,
384 /// A hole in the panel, with content down inside it. For anything the
385 /// user looks *into*: a table body, a tag tree, a text field.
386 Well,
387 /// Set back from what it sits on, by colour alone. No edge.
388 ///
389 /// The one member carrying a fill without a bevel, so a renderer cannot
390 /// assume the two arrive together. That is deliberate and it is still the
391 /// pairing rule: both halves come off the same `Depth`, so they cannot
392 /// disagree, and here one half is legitimately absent.
393 ///
394 /// Distinct from [`Depth::Flat`], which has no fill either and inherits.
395 /// Recessed and level-with are different claims, and only one of them
396 /// needs a colour.
397 Sunken,
398 /// A surface sitting *over* the page rather than in it. A modal, a popover,
399 /// a menu.
400 ///
401 /// Takes elevation and no bevel: a surface overlaying the page is lifted
402 /// off it, and a surface in the page is cut into it. That is the same
403 /// pairing rule the rest of the enum holds, applied to the one case where
404 /// the separation is not an edge at all — the lift and the scrim behind it
405 /// are already saying where the surface is.
406 ///
407 /// Every renderer already has the surface: `makeover-tui` carries
408 /// `Palette::overlay`, `makeover-immediate` `Palette::elevation`, and
409 /// `makeover-webview` emits `--elevation-overlay`. This variant is the
410 /// route from a description to any of them, which is why it is one variant
411 /// rather than a feature.
412 Overlay,
413 }
414
415 impl Depth {
416 /// The edge this depth is drawn with, if it has one.
417 #[must_use]
418 pub const fn bevel(self) -> Option<Bevel> {
419 match self {
420 // Sunken joins Flat here, for the opposite reason: Flat has no edge
421 // because nothing separates it from its surroundings, and Sunken has
422 // none because its colour is already doing the separating.
423 Self::Flat | Self::Sunken => None,
424 // A third reason to have no edge, which is why it gets its own arm
425 // rather than joining the two above: an overlay is separated by the
426 // lift and by the scrim behind it, so an edge would be a second
427 // answer to a question already answered.
428 Self::Overlay => None,
429 Self::Raised => Some(Bevel::Raised),
430 Self::Well => Some(Bevel::Inset),
431 }
432 }
433
434 /// The surface this depth is filled with.
435 ///
436 /// [`Depth::Flat`] has no fill of its own: it inherits whatever it sits on,
437 /// which is the difference between level-with and painted-the-same-colour.
438 #[must_use]
439 pub const fn fill(self) -> Option<Fill> {
440 match self {
441 Self::Flat => None,
442 Self::Raised => Some(Fill::Raised),
443 Self::Well => Some(Fill::Well),
444 Self::Sunken => Some(Fill::Sunken),
445 Self::Overlay => Some(Fill::Overlay),
446 }
447 }
448
449 /// Pressing a raised region reads as a well, and nothing else moves.
450 ///
451 /// [`Depth::Overlay`] is untouched along with the rest: an overlay is a
452 /// surface, not a control, so there is nothing there to press.
453 #[must_use]
454 pub const fn pressed(self) -> Self {
455 match self {
456 Self::Raised => Self::Well,
457 other => other,
458 }
459 }
460 }
461
462 /// An interaction state a region can be in, beside whatever [`Depth`] it is.
463 ///
464 /// Orthogonal to depth on purpose. A disabled button is still [`Depth::Raised`]
465 /// and a disabled field is still a [`Depth::Well`], so folding either member
466 /// into `Depth` would make [`Depth::bevel`] and [`Depth::fill`] answer for
467 /// something that is not a depth, and would leave disabled-button and
468 /// disabled-field sharing one variant that cannot tell them apart.
469 ///
470 /// # Why hover and pressed are not members
471 ///
472 /// The line is whether every renderer has the state to express, not whether CSS
473 /// does. Hover is renderer policy and `makeover-webview` says so in its own
474 /// header: a terminal and an immediate-mode painter have no pointer hovering
475 /// over anything, and pressed already arrives through [`Bevel::pressed`] and
476 /// [`Depth::pressed`], where it belongs, because pressing is a depth inversion
477 /// rather than a separate condition.
478 ///
479 /// Focus and disabled are different in kind. A TUI has a focused widget and a
480 /// greyed-out one; so does egui. Both were unsayable here, so all three webview
481 /// consumers supplied them from outside the primitive by out-specifying rules
482 /// they did not own: goingson alone carries 19 of them, and the MNW server
483 /// another 21. That is the divergence this crate exists to end, arriving one
484 /// layer down.
485 ///
486 /// # The principle this encodes
487 ///
488 /// A primitive owns every state it implies. A renderer that emits a hover rule
489 /// for a thing owes disabled and the capability answer for that same thing,
490 /// because anything less exports the completion work to N consumers who will
491 /// each do it differently.
492 ///
493 /// Focus is not on that list and is not on this axis. It is the renderer's,
494 /// decided after the description; see the crate header, "Reach,
495 /// focus and the focus ring", for the three terms and who owns each.
496 ///
497 /// `#[non_exhaustive]` for the reason [`Fill`] and [`Depth`] carry it: growth
498 /// must not be a lockstep event across the three renderers.
499 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
500 #[non_exhaustive]
501 pub enum State {
502 /// Present, visible, and not answering.
503 ///
504 /// Not the same as absent, and deliberately not a [`Fill`]: a disabled
505 /// control keeps the surface it always had and stops responding, so what
506 /// changes is its content and its interactivity rather than what it is.
507 Disabled,
508 }
509
510 impl State {
511 /// Whether a region in this state stops answering the pointer.
512 ///
513 /// Stated in the description rather than left to each renderer, on the same
514 /// reasoning as [`Bevel::pressed`]: a cascade carries it for free and an
515 /// immediate-mode renderer resolves it per call site, so leaving it unsaid
516 /// means resolving it once per consumer and disagreeing.
517 #[must_use]
518 pub const fn suppresses_interaction(self) -> bool {
519 // A match rather than a bare `true`, so a member added to this
520 // `#[non_exhaustive]` axis has to answer the question rather than
521 // inheriting an answer.
522 match self {
523 Self::Disabled => true,
524 }
525 }
526 }
527
528 impl Intent for State {
529 fn token(self) -> &'static str {
530 match self {
531 // Reusing the muted content intent rather than minting a
532 // `disabled` colour. Disabled is a reduction and not a status, and
533 // `makeover-webview`'s progress rules already record the reading
534 // that `content-muted` is what disabled looks like.
535 Self::Disabled => "content-muted",
536 }
537 }
538 }
539
540 /// What a region is saying, when it is saying something.
541 ///
542 /// The one intent family shared by badges, notices and nothing else. Kept
543 /// separate from [`Fill`] because a surface is where a thing sits and a tone is
544 /// what it means, and the three apps agree on the four statuses:
545 /// `info_banner` / `warning_banner` in audiofiles, `.toast-info` /
546 /// `.toast-success` / `.toast-error` in goingson, `.toast.success` /
547 /// `.toast.error` in Balanced Breakfast.
548 ///
549 /// The per-tag palette (`category-one` through `category-six`) is deliberately
550 /// not here. Which colour a *particular* tag takes is app domain, and both
551 /// webview apps already carry it as a `data-color` attribute.
552 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
553 pub enum Tone {
554 /// No status.
555 ///
556 /// Ordinary content, at full weight. It does not also mean muted: a
557 /// badge reads quiet because [`Token::Badge`] answers no click, which is
558 /// the renderer's knowledge and not this axis's. A renderer wanting a
559 /// muted badge reaches for [`Token::interactive`] itself rather than
560 /// expecting `Neutral` to have muted it.
561 Neutral,
562 /// Something worth knowing and nothing to do about it.
563 Info,
564 /// Something finished and it worked.
565 Success,
566 /// Something the user should look at before continuing.
567 Warning,
568 /// Something broken, or something about to be destroyed.
569 Danger,
570 }
571
572 impl Intent for Tone {
573 fn token(self) -> &'static str {
574 match self {
575 // Neutral has no status token of its own, so it takes the plain
576 // content intent. It used to answer `content-muted`, which read
577 // "no status" as "de-emphasised" and muted every figure value in
578 // the webview. Muting is a renderer's call about a particular
579 // token, not something the status axis knows.
580 Self::Neutral => "content",
581 Self::Info => "info",
582 Self::Success => "success",
583 Self::Warning => "warning",
584 Self::Danger => "danger",
585 }
586 }
587 }
588
589 /// A small labelled thing that sits inside something else.
590 ///
591 /// Two members, because the three apps drew three taxonomies and only one line
592 /// runs through all of them: does it answer a click. audiofiles has
593 /// `classification_badge` (a label) against `tag_chip`, `tag_chip_removable`
594 /// and `selectable_tag` (all of which do). Balanced Breakfast has `.tag` and
595 /// `.badge` against `.tag-chip`. goingson is the one that has to move: its
596 /// `.tag` and `.badge` are a single CSS rule, so every call site has to be read
597 /// to decide which of the two it always was.
598 ///
599 /// The evidence that a chip is a real concept rather than a badge with a
600 /// cursor: audiofiles inverts its bevel on press and Balanced Breakfast latches
601 /// `.tag-chip.active` with the inset bevel. Two independent arrivals at "a chip
602 /// holds itself down", which is exactly what [`Depth::pressed`] already says.
603 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
604 pub enum Token {
605 /// Non-interactive status or count. Answers no click.
606 Badge,
607 /// An interactive or removable token. Answers a click, and latches if it
608 /// stands for a filter that is either on or off.
609 Chip {
610 /// Whether it carries its own remove affordance.
611 removable: bool,
612 },
613 }
614
615 impl Token {
616 /// Whether this answers a click.
617 ///
618 /// The whole difference between the two members, and the reason a renderer
619 /// with no hover (a touch surface, a terminal) can still tell them apart.
620 #[must_use]
621 pub const fn interactive(self) -> bool {
622 matches!(self, Self::Chip { .. })
623 }
624
625 /// How it sits, given whether it is currently latched down.
626 ///
627 /// A badge is flat: it is a label, and giving it an edge would say it can
628 /// be pressed. A chip is raised, and inset while latched.
629 #[must_use]
630 pub const fn depth(self, latched: bool) -> Depth {
631 match self {
632 Self::Badge => Depth::Flat,
633 Self::Chip { .. } if latched => Depth::Well,
634 Self::Chip { .. } => Depth::Raised,
635 }
636 }
637 }
638
639 /// Something the app is telling the user, unprompted.
640 ///
641 /// Two concepts, not one with a placement. They differ in more than where they
642 /// sit: a toast is transient, stacked and self-dismissing, and a banner is
643 /// persistent, in flow, one per region, and dismissed by fixing the condition
644 /// it reports. Folding them into one member with a placement parameter would
645 /// make lifetime, stacking and dismissal all placement-dependent, which is the
646 /// description leaking renderer policy.
647 ///
648 /// All three apps have banners: `info_banner` and `warning_banner` in
649 /// audiofiles, five of them in goingson (sync, sync-result, vacation-day,
650 /// timer-active, past-review), `.update-banner` in Balanced Breakfast. The two
651 /// webview apps also have toasts. So neither member is speculative, and no app
652 /// gains a concept it lacks except audiofiles, whose renderer may legitimately
653 /// decline to draw a toast at all.
654 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
655 pub enum Notice {
656 /// Transient, stacked, dismisses itself.
657 Toast,
658 /// Persistent, in flow, one per region, dismissed by fixing the cause.
659 Banner,
660 }
661
662 impl Notice {
663 /// Whether it goes away on its own.
664 #[must_use]
665 pub const fn transient(self) -> bool {
666 matches!(self, Self::Toast)
667 }
668
669 /// How it sits.
670 ///
671 /// A toast floats above the page rather than resting on it, which is
672 /// [`Fill::Overlay`]'s whole reason to exist. A banner is a card in the
673 /// flow. Both are raised, and they are raised off different things.
674 #[must_use]
675 pub const fn fill(self) -> Fill {
676 match self {
677 Self::Toast => Fill::Overlay,
678 Self::Banner => Fill::Raised,
679 }
680 }
681 }
682
683 /// The parts of a list row.
684 ///
685 /// `#[non_exhaustive]`: a renderer carries a wildcard arm, so a new part is not
686 /// a lockstep event across three renderers.
687 ///
688 /// # Meta against Tokens
689 ///
690 /// The line is whether the thing has its own standing. `Meta` is one short
691 /// trailing fact about the row, written as text: a count, a size, a date.
692 /// `Tokens` is a set of small labelled things, each of which can be toned and
693 /// can answer a click. "3 files" is meta. A status badge that is amber, and a
694 /// tag you can click to filter by, are tokens.
695 ///
696 /// Keeping them apart is what a single widened slot would have foreclosed. A
697 /// renderer can right-align one string and cannot usefully do the same to a
698 /// strip of chips, and a fact that is not clickable should not be drawn as
699 /// though it were.
700 /// How much vertical room a part's text may take.
701 ///
702 /// A row is an inline run and every part in it is a leaf, so a part's text has
703 /// always been drawn on one line and no description could say otherwise. Two
704 /// apps say otherwise in their own stylesheets, both to the same number and
705 /// both with a comment explaining it: Balanced Breakfast clamps a feed row's
706 /// title to two lines (`.row--article .row-primary`, whose comment reads
707 /// "overrides .row-primary's single flex line"), and goingson clamps a
708 /// problem's body to two ("two lines is enough to recognize one, and the full
709 /// text is in the task once promoted").
710 ///
711 /// Two named tiers rather than a line count, and the count is what the measured
712 /// demand argues against. Both sites want exactly one tier past the default,
713 /// and a number invites a row whose primary is a paragraph, which is a block
714 /// and has no business in a run. A third tier is a decision, made here, rather
715 /// than something a call site can reach for.
716 ///
717 /// What a renderer owes it: `Tight` is what a run already does and needs no
718 /// answer. `Relaxed` is at most two lines and then truncation, however that
719 /// renderer truncates -- a webview clamps, a terminal wraps into two rows of
720 /// cells, an immediate-mode renderer caps the galley. A renderer that cannot
721 /// give two lines may draw one; what it may not do is grow without bound,
722 /// because the run is a line and the row's neighbours are relying on that.
723 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
724 #[non_exhaustive]
725 pub enum Flow {
726 /// One line. What every part did before this type existed.
727 #[default]
728 Tight,
729 /// Up to two lines, then truncated.
730 Relaxed,
731 }
732
733 impl Flow {
734 /// How many lines the part may take.
735 ///
736 /// A number here rather than in the enum, because a renderer needs one and
737 /// a call site does not. That asymmetry is the whole argument for the
738 /// tiers: the description says how much room the thing deserves and this
739 /// says what that costs, so a third tier changes one line rather than every
740 /// consumer's arithmetic.
741 #[must_use]
742 pub const fn lines(self) -> u8 {
743 match self {
744 Self::Relaxed => 2,
745 // Including any tier added later: one line is the safe reading of
746 // an unknown flow, since it is what the run guaranteed before flows
747 // existed.
748 _ => 1,
749 }
750 }
751 }
752
753 /// How deep a row sits inside a set: a tree, an outline, a threaded list.
754 ///
755 /// [`RowPart`] below already names what is *in* a row; nothing named where a
756 /// row sits relative to its siblings, so every consumer that had a hierarchy
757 /// carried a bare number and every renderer decided for itself what one was
758 /// worth.
759 ///
760 /// # Not `Depth`, and the collision is the reason
761 ///
762 /// [`Depth`] is taken and means something else entirely: surface bevel --
763 /// `Flat`, `Raised`, `Well`, `Sunken`, `Overlay` -- a fact about a surface
764 /// rather than a position in a hierarchy. Two meanings under one word in one
765 /// crate is the collision that costs a reader an hour, and the word this
766 /// concept wants is the one that would cause it.
767 ///
768 /// # The magnitude is the renderer's, and that is the precedent
769 ///
770 /// [`Awaiting`] is the shape: this crate names the fact and declines to name
771 /// what it is worth. makeover-webview writes the rule as a custom property with
772 /// a fallback -- the way it writes `margin-inline-start: var(--awaiting-gap,
773 /// 0.5ch)` -- so a level has one answer per renderer and an app can override
774 /// it. A terminal spends columns, a browser spends inline space, and neither
775 /// number belongs in a description.
776 ///
777 /// # Zero is a real answer
778 ///
779 /// [`top`](Self::top) is the default and is what a flat list says: every row is
780 /// at the top level, which is true and is the reading a renderer needs. An
781 /// `Option` here would make "not nested" and "nested at zero" two spellings of
782 /// one thing, the same argument `Discovery`'s `indexable` makes about defaults
783 /// that are meaningful.
784 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
785 #[non_exhaustive]
786 pub struct Nesting {
787 /// How many levels in, counting from zero.
788 ///
789 /// `u8` because a hierarchy a reader can follow is not 256 deep, and a
790 /// renderer indenting by a level has to multiply it by something -- a wider
791 /// integer here is a wider integer in every renderer's arithmetic for a
792 /// range nothing will use.
793 pub level: u8,
794 }
795
796 impl Nesting {
797 /// The top level: not nested. The default, and what a flat list says.
798 #[must_use]
799 pub const fn top() -> Self {
800 Self { level: 0 }
801 }
802
803 /// A row this many levels in.
804 #[must_use]
805 pub const fn at(level: u8) -> Self {
806 Self { level }
807 }
808
809 /// Whether this row sits under another.
810 ///
811 /// The question every renderer asks before it spends anything on indenting,
812 /// answered once here rather than by a `> 0` in each -- which is
813 /// [`Awaiting::is_determinate`]'s reason too.
814 #[must_use]
815 pub const fn is_nested(self) -> bool {
816 self.level > 0
817 }
818 }
819
820 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
821 #[non_exhaustive]
822 pub enum RowPart {
823 /// The thing itself. What the row is called.
824 Primary,
825 /// Supporting text under the primary.
826 Secondary,
827 /// A short trailing fact: a count, a size, a date.
828 Meta,
829 /// Controls that act on this row.
830 Actions,
831 /// Small labelled things belonging to the row: badges, chips, tags.
832 ///
833 /// Each carries its own [`Token`] kind and [`Tone`], so a renderer with no
834 /// colour still has the kind to work with, and one with no chips still has
835 /// the label. That is the constrained-consumer test this vocabulary exists
836 /// to pass, and it is why the tone lives on the token rather than on the
837 /// part.
838 Tokens,
839 /// How much of a set the row's thing has done: a [`Meter`] in the row.
840 ///
841 /// A row holds no nodes, by the rule that a row part may not carry an
842 /// arbitrary node, which is the door through which a description becomes a
843 /// templating language. So the part carries the *description of a bar* rather than a node, exactly as
844 /// `Tokens` carries tags rather than nodes.
845 ///
846 /// Without it a row flattens the proportion into [`Meta`](Self::Meta) as
847 /// "3/7 subtasks", which keeps both numbers and loses the reading, the same
848 /// way a toned status badge read as prose before `Tokens`.
849 Proportion,
850 }
851
852 impl RowPart {
853 /// What the part is worth when the run does not fit.
854 ///
855 /// The default only. A part may say otherwise, and a renderer reads the
856 /// part rather than the role; this is what a description that has never
857 /// heard of [`Priority`] means, which is every description written before
858 /// the field existed.
859 ///
860 /// Deriving it from the role is the thing this vocabulary has otherwise
861 /// been moving away from, and it is right here for one reason: the roles
862 /// already encode this ranking and every consumer already assumes it.
863 /// [`Primary`](Self::Primary) is what the row is called, and
864 /// [`Priority::Essential`]'s own doc was written about exactly that --
865 /// "without it the row does not identify itself".
866 ///
867 /// [`Actions`](Self::Actions) is `Essential` and it is the interesting one.
868 /// A control is not a fact, so dropping it does not cost the reader a
869 /// detail; it costs them the only way to act on the row, and in a terminal
870 /// it silently removes something focus had already been claimed for. A
871 /// renderer that needs room takes it from what the row *says*, never from
872 /// what it *offers*.
873 ///
874 /// An unknown member reads as [`Priority::Secondary`]: droppable, but not
875 /// first, since guessing `Optional` for something this crate has not been
876 /// taught would make a new member the first thing to vanish.
877 #[must_use]
878 pub const fn priority(self) -> Priority {
879 match self {
880 Self::Primary | Self::Actions => Priority::Essential,
881 Self::Meta | Self::Proportion => Priority::Optional,
882 _ => Priority::Secondary,
883 }
884 }
885
886 /// The content intent the part takes.
887 #[must_use]
888 pub const fn intent(self) -> &'static str {
889 match self {
890 Self::Primary => "content",
891 Self::Secondary => "content-secondary",
892 Self::Meta => "content-muted",
893 // Actions carry controls rather than text, so they inherit.
894 Self::Actions => "content",
895 // So do tokens: each one carries its own tone, and a part-level
896 // intent underneath it would fight the token that sits on it.
897 Self::Tokens => "content",
898 // And so does a proportion, for the same reason: the meter carries
899 // the tone, and it is about the ratio rather than about the row.
900 Self::Proportion => "content",
901 }
902 }
903 }
904
905 /// How far down the heading tree a title sits.
906 ///
907 /// Three, and only the three that are actually headings. The bands those used
908 /// to be filed with (goingson's `.page-header`, Balanced Breakfast's `.header`
909 /// and `.detail-header`) are arrangement, not type, and live at
910 /// [`Region::Band`]. One of them contains no text at all.
911 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
912 pub enum Heading {
913 /// Names the whole screen. One per screen.
914 Page,
915 /// Names a block within the screen.
916 Section,
917 /// Names a sub-block inside an already-named section.
918 Subsection,
919 }
920
921 impl Heading {
922 /// Whether a rule follows the heading.
923 ///
924 /// audiofiles' `section_header` draws a separator and its
925 /// `subsection_label` deliberately does not, which is the only thing
926 /// distinguishing the two once weight and colour are deferred.
927 #[must_use]
928 pub const fn separated(self) -> bool {
929 matches!(self, Self::Section)
930 }
931 }
932
933 /// A control that picks between things.
934 ///
935 /// Three, because three distinct behaviours are in play and collapsing any two
936 /// loses something. A segmented control picks a value; a tab picks a pane; a
937 /// toggle picks nothing and simply holds itself on or off.
938 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
939 pub enum Selector {
940 /// Exactly one of N, and the options abut.
941 Segmented,
942 /// Independent on or off, on its own.
943 Toggle,
944 /// Navigation between panes. The folder semantic.
945 Tabs,
946 }
947
948 impl Selector {
949 /// How the chosen option sits.
950 ///
951 /// Held in for a segmented control and a toggle, which is the same shape
952 /// pressing produces and the whole economy of the idiom: one appearance,
953 /// two reasons to wear it. A tab is the exception, because the selected
954 /// folder tab comes *forward* to join the pane it opens.
955 #[must_use]
956 pub const fn chosen(self) -> Depth {
957 match self {
958 Self::Segmented | Self::Toggle => Depth::Well,
959 Self::Tabs => Depth::Raised,
960 }
961 }
962
963 /// How the options that were *not* picked sit.
964 ///
965 /// Describing only [`Selector::chosen`] left the unchosen option falling
966 /// through to [`Depth::Flat`], which says it is level with the strip it
967 /// sits in, and no renderer emitted anything for it. That is wrong in both
968 /// directions and goingson proved it: its unchosen tabs are recessed by
969 /// hand, and being recessed is *why* the chosen one reads as coming
970 /// forward. Against a flat strip, a raised chosen tab is a bevel drawn on
971 /// the strip's own colour, which is a much weaker folder effect than the
972 /// contrast the idiom is named after.
973 ///
974 /// Each member is the inverse of its chosen state, which is the whole
975 /// content of "picked" once colour is deferred:
976 ///
977 /// - Tabs recede, so the chosen one comes forward.
978 /// - A segment and a toggle stand up, so the chosen one is held in.
979 #[must_use]
980 pub const fn unchosen(self) -> Depth {
981 match self {
982 Self::Tabs => Depth::Sunken,
983 Self::Segmented | Self::Toggle => Depth::Raised,
984 }
985 }
986
987 /// Whether the options touch.
988 ///
989 /// The gap is the entire difference between a segmented control and a row
990 /// of buttons that happen to sit near each other, which is what audiofiles'
991 /// `segmented_control` says in its own comment and why it zeroes the
992 /// spacing by hand.
993 #[must_use]
994 pub const fn abutting(self) -> bool {
995 matches!(self, Self::Segmented | Self::Tabs)
996 }
997 }
998
999 /// What is in a region right now.
1000 ///
1001 /// The state, not the shimmer. Whether pending paints a skeleton, a spinner or
1002 /// nothing at all is renderer policy, the same class of decision that got
1003 /// `Fill::fallback` deleted from this crate. goingson and Balanced Breakfast
1004 /// each grew a skeleton with differently-named parts; both keep them, as the
1005 /// webview renderer's expression of [`Readiness::Pending`]. audiofiles has none
1006 /// and needs none, because an immediate-mode renderer simply repaints.
1007 ///
1008 /// # Four states and not two
1009 ///
1010 /// Naming only `Ready` and `Pending` leaves a screen whose list came back empty
1011 /// with nothing to say about it, so it renders an empty region or invents its
1012 /// own placeholder text and neither says what it is. Left to the apps, the
1013 /// class family drifts: `empty-state`, `empty-state--error`, `error-state` and
1014 /// six more.
1015 ///
1016 /// The four are one axis because they are mutually exclusive: a region shows its
1017 /// content, or a sign that it is coming, or a sign that there is none, or a sign
1018 /// that it broke. Never two. That is the test for one enum against several
1019 /// fields, and it is why this grew rather than a new member arriving beside it.
1020 ///
1021 /// # What is not here
1022 ///
1023 /// **The message.** "No projects yet" is content, and this names a state. It
1024 /// lives with whatever holds the region — in quasi's case a `Slot` — alongside
1025 /// the action that leads out of the emptiness, since an address is the one thing
1026 /// this crate never names.
1027 ///
1028 /// **How much room it gets.** goingson's `--compact`, `--dashboard` and
1029 /// `--padded` are the same state at three sizes, and a size is
1030 /// `makeover-geometry`'s question. Naming them here would be this crate stating
1031 /// values again.
1032 ///
1033 /// **The icon.** Presentation, and each host has its own answer or none.
1034 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1035 #[non_exhaustive]
1036 pub enum Readiness {
1037 /// The content is here.
1038 Ready,
1039 /// The content is on its way.
1040 ///
1041 /// For a region that changes *after* the first paint, and never for the
1042 /// first paint itself: see "First paint is final paint" in the crate header.
1043 /// A host that renders once, with its data already in hand, has nothing to
1044 /// say this about, and a screen arriving in this state is describing a
1045 /// moment its host should not have been in.
1046 ///
1047 /// What stands in occupies the geometry the content will occupy. A stand-in
1048 /// sized to itself rather than to what replaces it is the reflow the rule
1049 /// forbids, arriving one repaint later.
1050 Pending,
1051 /// The content arrived and there is none of it.
1052 ///
1053 /// Not a failure. An empty list is the normal state of a new install, and a
1054 /// renderer that drew it in a danger tone would be reporting a fault where
1055 /// there is none.
1056 Empty,
1057 /// The content did not arrive.
1058 Failed,
1059 }
1060
1061 impl Readiness {
1062 /// Whether the region draws its own content, or something standing in for
1063 /// it.
1064 ///
1065 /// The question every renderer asks first, so it is answered once here
1066 /// rather than by a `matches!` in each. A state added later is a stand-in
1067 /// until proven otherwise: falling back to drawing content that may not be
1068 /// there is the worse of the two mistakes.
1069 #[must_use]
1070 pub const fn shows_content(self) -> bool {
1071 matches!(self, Self::Ready)
1072 }
1073
1074 /// What the state means, for a renderer choosing a colour.
1075 ///
1076 /// Derived rather than carried, which is the opposite of [`Meter`] and
1077 /// [`Figure`], and the difference is worth stating: a proportion's meaning
1078 /// depends on what is being counted and only the app knows it, while
1079 /// "nothing here yet" and "this broke" mean the same thing in every app that
1080 /// will ever have them.
1081 #[must_use]
1082 pub const fn tone(self) -> Tone {
1083 match self {
1084 Self::Failed => Tone::Danger,
1085 _ => Tone::Neutral,
1086 }
1087 }
1088 }
1089
1090 /// An action is waiting on something that resolves once, in expected finite
1091 /// time.
1092 ///
1093 /// The control-side sibling of [`Readiness`]. That enum names four states for a
1094 /// region and named nothing at all for the button that is currently doing what
1095 /// it was clicked for, so the in-flight treatment is hand-written wherever it
1096 /// exists: the MNW server carries 57 in-flight indicators against 2 guards
1097 /// against a second press, which is the spinner mostly present and the guard
1098 /// mostly absent, on a codebase whose money path is a purchase button.
1099 ///
1100 /// # What is described here, and what is not
1101 ///
1102 /// The fact is that there is an outstanding thing which will complete. Not that
1103 /// the address is remote: a heavy local query waits too, and a server calling a
1104 /// payment provider is not the browser leaving the app. Not that the call is
1105 /// slow either, which is a judgement about a call rather than a property of one.
1106 ///
1107 /// Resolving **once** is the boundary, and it is what separates this from a
1108 /// screen that keeps changing. A live screen never resolves and has no name in
1109 /// this crate yet.
1110 ///
1111 /// # One mark, two renderings
1112 ///
1113 /// | what reads it | what it does |
1114 /// |---|---|
1115 /// | a control that was pressed | goes busy and refuses a second press until it resolves |
1116 /// | a region fed by it | stands in as [`Readiness::Pending`], then fills |
1117 ///
1118 /// The two were on the table separately and both were taken. Controls alone
1119 /// leaves a slow region hand-split into its own route, which is what MNW's user
1120 /// dashboard does with its payout summary; regions alone leaves the purchase
1121 /// button unguarded.
1122 ///
1123 /// # A quantity when it is measured, never a duration
1124 ///
1125 /// [`amount`](Self::amount) is stated only when it is a measured fact about the
1126 /// payload. An upload's file length, yes; a round trip to a payment provider,
1127 /// [`None`]. A duration is described nowhere, and a renderer may not manufacture
1128 /// one from the amount either: a determinate bar shows what is done over what
1129 /// there is, plus the time it has taken so far, and never a remaining time, an
1130 /// arrival time or a rate extrapolated forwards. A prediction is wrong the
1131 /// moment the transfer stalls, and being confidently wrong is worse than being
1132 /// honestly indeterminate.
1133 ///
1134 /// This is why the crate refuses to say how long an undo stays offered and
1135 /// accepts a byte count here. The refusal is about naming a decision that
1136 /// belongs to the renderer; a file's length is not a decision, nobody chose it.
1137 ///
1138 /// # Not [`Meter`]
1139 ///
1140 /// [`Meter`] is how much of a set is done, and its own docs refuse the progress
1141 /// of an operation on the grounds that a description is built once and dropped
1142 /// while an operation runs between renders. That refusal stands. This names the
1143 /// operation and its size, which is all that is known before it starts; how much
1144 /// of it has gone through is the renderer's to observe live, and nothing round
1145 /// trips through a description to say so.
1146 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1147 #[non_exhaustive]
1148 pub struct Awaiting {
1149 /// Total work to get through, when it is a measured fact about the payload.
1150 ///
1151 /// `None` when the wait has no countable size, which is the common case and
1152 /// the default.
1153 ///
1154 /// Unit-agnostic on purpose. Bytes for an upload, rows for an import; what
1155 /// is being counted is the app's business and a renderer draws a proportion
1156 /// either way.
1157 pub amount: Option<u64>,
1158 }
1159
1160 impl Awaiting {
1161 /// A wait with no countable size.
1162 #[must_use]
1163 pub const fn unmeasured() -> Self {
1164 Self { amount: None }
1165 }
1166
1167 /// A wait whose size is known.
1168 ///
1169 /// Reach for it only with a measured figure. An estimate written in here is
1170 /// a prediction wearing a fact's clothes, and the renderer has no way to
1171 /// tell the two apart.
1172 #[must_use]
1173 pub const fn of(amount: u64) -> Self {
1174 Self {
1175 amount: Some(amount),
1176 }
1177 }
1178
1179 /// Whether there is a proportion to draw.
1180 ///
1181 /// The question every renderer asks first, answered once here rather than by
1182 /// a `matches!` in each. False means indeterminate, which is the honest
1183 /// drawing when nothing countable was measured.
1184 #[must_use]
1185 pub const fn is_determinate(self) -> bool {
1186 self.amount.is_some()
1187 }
1188 }
1189
1190 /// How much of a set is done.
1191 ///
1192 /// Nine sites across the two webview apps drew a bar and nothing here named
1193 /// one, so every described screen concatenated the two numbers into its
1194 /// heading text instead: "Subtasks 3/7", "Time Tracking 45m tracked / 30m est,
1195 /// over". Every fact survives that and the reading does not, which is the same
1196 /// loss `RowPart::Tokens` closed when a toned status badge became prose.
1197 ///
1198 /// # Why a pair and not a percentage
1199 ///
1200 /// Both numbers, not the percentage the apps compute from them. The percentage
1201 /// was the obvious shape and it had already been tried: goingson's
1202 /// `Task::time_progress` divides, rounds, and then clamps to 100, which throws
1203 /// away the one case the bar exists to show — 45 minutes tracked against a
1204 /// 30-minute estimate. It carries a separate `is_over_estimate` boolean beside
1205 /// it to recover the fact the clamp dropped. A pair keeps the over-run without a
1206 /// companion flag, and [`percent`](Meter::percent) is still one call away for a
1207 /// renderer that wants it.
1208 ///
1209 /// The pair is also what the apps already have at every site. All seven
1210 /// determinate bars write the ratio into the accessible layer and never the
1211 /// percentage: `title="3/7 subtasks"`, `aria-label="3 of 7 subtasks completed"`,
1212 /// a milestone's own `3/7` span. Given 43 nothing can recover "3 of 7", so a
1213 /// percentage member would have made [`label`](Meter::label) mandatory at every
1214 /// call site, which is the concatenated text this member removes, moved one
1215 /// layer down.
1216 ///
1217 /// # What this is not
1218 ///
1219 /// The progress of an *operation*. Two of the nine sites are that — goingson's
1220 /// focus timer, Balanced Breakfast's feed fetch — and they get nothing here, on
1221 /// purpose. Both are imperative controllers over a live handle, driven by a tick
1222 /// or an event stream, and a description is built once and dropped. Holding one
1223 /// would mean growing a way to update a description between renders, which is a
1224 /// different feature. [`Readiness::Pending`] and a [`Notice::Toast`] carry the
1225 /// honest part.
1226 ///
1227 /// The two cases are distinguishable in the markup rather than by taste: every
1228 /// determinate bar in both apps carries a tone, and neither operation bar
1229 /// carries one. Two codebases drew that line the same way without coordinating.
1230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1231 pub struct Meter<'a> {
1232 /// How much is done. May exceed [`total`](Self::total), and that is the
1233 /// case worth drawing.
1234 pub done: u32,
1235 /// How much there is to do. Zero means there is no set, not that the set is
1236 /// complete.
1237 pub total: u32,
1238 /// What the proportion means right now.
1239 ///
1240 /// Carried rather than derived, because no renderer can work it out. The
1241 /// same 90% is [`Tone::Success`] on a subtask rollup and [`Tone::Danger`] on
1242 /// a time estimate, and goingson picks between them from `is_over_estimate`,
1243 /// a fact about the data and not about the number.
1244 pub tone: Tone,
1245 /// What is being counted, if the bar says so: "subtasks", "tasks".
1246 ///
1247 /// The noun, not the ratio. A renderer builds "3 of 7 subtasks" from this
1248 /// and the two numbers; handing it the assembled string would put the
1249 /// sentence order in the description, where a terminal at one line and a
1250 /// tooltip want different ones.
1251 pub label: Option<&'a str>,
1252 }
1253
1254 impl<'a> Meter<'a> {
1255 /// A proportion with no tone and no label.
1256 #[must_use]
1257 pub const fn new(done: u32, total: u32) -> Self {
1258 Self {
1259 done,
1260 total,
1261 tone: Tone::Neutral,
1262 label: None,
1263 }
1264 }
1265
1266 /// What the proportion means.
1267 #[must_use]
1268 pub const fn tone(mut self, tone: Tone) -> Self {
1269 self.tone = tone;
1270 self
1271 }
1272
1273 /// What is being counted.
1274 #[must_use]
1275 pub const fn label(mut self, label: &'a str) -> Self {
1276 self.label = Some(label);
1277 self
1278 }
1279
1280 /// How full the bar is, 0 to 100, clamped.
1281 ///
1282 /// For drawing, which is the only thing a clamped number is good for. Ask
1283 /// [`overflowing`](Self::overflowing) before reporting it as a fact, or this
1284 /// is `time_progress`'s bug again with the clamp moved.
1285 ///
1286 /// An empty set reads as 0. Nothing is done, because there is nothing to do
1287 /// and no bar to fill; the apps guard on the count before drawing at all.
1288 #[must_use]
1289 pub const fn percent(&self) -> u8 {
1290 if self.total == 0 {
1291 return 0;
1292 }
1293 let scaled = (self.done as u64 * 100) / self.total as u64;
1294 if scaled > 100 { 100 } else { scaled as u8 }
1295 }
1296
1297 /// Whether more is done than there was to do.
1298 ///
1299 /// The fact [`percent`](Self::percent) destroys, kept reachable so a
1300 /// renderer can mark the over-run rather than drawing a full bar and
1301 /// implying it landed exactly.
1302 #[must_use]
1303 pub const fn overflowing(&self) -> bool {
1304 self.done > self.total
1305 }
1306
1307 /// Whether there is a set at all.
1308 ///
1309 /// A meter over nothing is sayable on purpose, for the same reason a field
1310 /// with no options is: it is what an app with an unloaded count actually
1311 /// has, and a renderer that shows an empty bar says so on screen rather than
1312 /// dividing by zero.
1313 #[must_use]
1314 pub const fn is_empty(&self) -> bool {
1315 self.total == 0
1316 }
1317 }
1318
1319 /// One figure with a caption: a number and what it counts.
1320 ///
1321 /// The dashboard shape. A large value over a small caption, several of them in
1322 /// a strip: a current streak, a completion rate, a total. Four put the value
1323 /// above the caption and one inverts it, which is drift inside the shape
1324 /// rather than a second shape.
1325 ///
1326 /// # Why the value is text
1327 ///
1328 /// "17", "84%", "12/30", "3d". A figure is whatever the app computed, already
1329 /// formatted, and the formatting is the app's because only it knows whether the
1330 /// number is a percentage, a duration or a ratio. This carries none of the
1331 /// arithmetic [`Meter`] carries, and that is the difference between them: a
1332 /// meter is a proportion a renderer draws, and a figure is a fact a renderer
1333 /// sets in type.
1334 ///
1335 /// # Tone is carried, for [`Meter`]'s reason
1336 ///
1337 /// Three of the five sites tone the figure by their own means — `red`/`blue` on
1338 /// the weekly review, a `${type}` class on the monthly one, `sync-stat-warn` on
1339 /// sync. So tone is carried at every site that needs it and derived at none, and
1340 /// no renderer can work out that a streak of zero is worth colouring.
1341 ///
1342 /// # What is not here
1343 ///
1344 /// Whether the figure answers a click. One of the five is a control — sync's
1345 /// "Not Applied: 3" opens the list — and an action is not something this crate
1346 /// can name: nothing here knows what a route is. That belongs beside the figure
1347 /// in whatever layer holds the actions, the same way a row's activation sits
1348 /// beside its parts rather than inside them.
1349 ///
1350 /// The arrangement is not here either. Several figures in a strip is a set, and
1351 /// a renderer given them one at a time cannot tell it is looking at one; the
1352 /// layer that holds the tree is where the set gets said.
1353 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1354 pub struct Figure<'a> {
1355 /// The number, formatted the way the app means it to read.
1356 pub value: &'a str,
1357 /// What it counts. The caption under the value.
1358 pub caption: &'a str,
1359 /// How the value has moved, if the app is tracking that.
1360 ///
1361 /// Text, for [`value`](Self::value)'s reason: only the app knows whether a
1362 /// move reads as `+12.5%`, `+3` or `2x`, and a renderer handed a number
1363 /// would have to guess.
1364 ///
1365 /// This is what [`tone`](Self::tone) was for and had no consumer of. The MNW
1366 /// server has four screens whose stat card is a label, a value and a delta,
1367 /// and the delta is the toned part: the figure itself is an ordinary fact
1368 /// and it is the movement that reads as good or bad. Without this the delta
1369 /// has to be folded into the caption, which loses the tone and reads as a
1370 /// longer caption rather than as a second, smaller line.
1371 pub change: Option<&'a str>,
1372 /// What the figure means right now. [`Tone::Neutral`] is an ordinary fact.
1373 ///
1374 /// Applies to [`change`](Self::change) where there is one, since that is the
1375 /// part that carries the judgement, and to the value where there is not.
1376 pub tone: Tone,
1377 }
1378
1379 impl<'a> Figure<'a> {
1380 /// A figure that is an ordinary fact.
1381 #[must_use]
1382 pub const fn new(value: &'a str, caption: &'a str) -> Self {
1383 Self {
1384 value,
1385 caption,
1386 change: None,
1387 tone: Tone::Neutral,
1388 }
1389 }
1390
1391 /// How the value has moved.
1392 #[must_use]
1393 pub const fn change(mut self, change: &'a str) -> Self {
1394 self.change = Some(change);
1395 self
1396 }
1397
1398 /// What the figure means.
1399 #[must_use]
1400 pub const fn tone(mut self, tone: Tone) -> Self {
1401 self.tone = tone;
1402 self
1403 }
1404 }
1405
1406 /// Something the user can do, and what it costs to say so.
1407 ///
1408 /// Beside [`Meter`] and [`Figure`] for the reason those are here: a renderer
1409 /// that is handed the parts has to decide how to say them, and a renderer that
1410 /// is handed a finished string has already had the decision made for it.
1411 ///
1412 /// No address. Where a control goes is the app's business and every host
1413 /// follows it differently — an `hx-get`, a protocol URL, a function call — so
1414 /// the description says what the control *is* and the caller keeps what it
1415 /// does. That is the same split [`Choice`] makes.
1416 ///
1417 /// No confirmation flag either, and that one is a finding rather than an
1418 /// omission: a question asked *after* a control is pressed belongs to whatever
1419 /// is holding the interaction, and a renderer that drew it would be asking
1420 /// before there was anything to answer.
1421 /// How a picture sits in the box it is given.
1422 ///
1423 /// An intent rather than a value, so a renderer picks the expression it has:
1424 /// `object-fit` in a webview, a texture's UV rect in egui, and in a terminal a
1425 /// choice about how many cells the blit gets. Named because MNW already makes
1426 /// the distinction deliberately at 17 sites and makes it three different ways,
1427 /// which is a policy the app decided rather than one a shared crate would be
1428 /// picking by accident.
1429 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1430 #[non_exhaustive]
1431 pub enum Fit {
1432 /// The picture's own proportions, and the box takes the height they imply.
1433 ///
1434 /// The default because it is the only one that shows the whole picture at
1435 /// its own shape, so a renderer that ignores this enum entirely is still
1436 /// right about the common case. A screenshot wants this; the shipped MNW
1437 /// carousel sets no `object-fit` at all, which is this.
1438 #[default]
1439 Natural,
1440 /// Fill the box and crop whatever does not fit.
1441 ///
1442 /// For a picture in a slot whose shape the layout fixed: a thumbnail, an
1443 /// avatar, cover art. 15 of MNW's 17 sites.
1444 Cover,
1445 /// Fit inside the box whole, leaving space on two sides.
1446 ///
1447 /// The letterbox. For when the whole picture matters more than filling the
1448 /// space, and the space is not the picture's shape.
1449 Contain,
1450 }
1451
1452 /// A picture's own pixel dimensions.
1453 ///
1454 /// Deliberately not [`makeover_geometry`]'s business. Geometry answers *how
1455 /// much space a thing should get*, which is a scale question with the same
1456 /// answer on every screen. This is the intrinsic size of one asset, which is a
1457 /// fact about that asset and varies per picture.
1458 ///
1459 /// [`makeover_geometry`]: https://docs.rs/makeover-geometry
1460 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1461 pub struct Extent {
1462 /// Width in the picture's own pixels.
1463 pub width: u32,
1464 /// Height in the picture's own pixels.
1465 pub height: u32,
1466 }
1467
1468 impl Extent {
1469 /// A picture's dimensions.
1470 #[must_use]
1471 pub const fn new(width: u32, height: u32) -> Self {
1472 Self { width, height }
1473 }
1474
1475 /// Width over height, or `None` if either side is zero.
1476 ///
1477 /// The form a renderer actually reserves space with: a box that knows its
1478 /// proportion holds the right height at any width, which is what a
1479 /// responsive picture needs and what a fixed pixel height cannot give.
1480 #[must_use]
1481 pub fn ratio(self) -> Option<f32> {
1482 (self.width > 0 && self.height > 0).then(|| self.width as f32 / self.height as f32)
1483 }
1484 }
1485
1486 /// When a picture is needed.
1487 ///
1488 /// A claim about *importance and position* rather than a fetch mechanism, which
1489 /// is why it is the description's to make: only the app knows whether a picture
1490 /// is the first thing on the screen or the fortieth thing down a list.
1491 ///
1492 /// # Eager is the default, and that is a correctness choice
1493 ///
1494 /// Emitting the webview's `loading="lazy"` for every picture reads one
1495 /// consumer's habit as a rule. Deferring a picture that is on screen at first paint does not
1496 /// save anything -- it is needed immediately either way -- and it delays the
1497 /// arrival, so the space it eventually takes is claimed later and the shift is
1498 /// more visible, not less.
1499 ///
1500 /// So the safe answer is the default and the optimisation is opted into. A
1501 /// carousel is the case that proves the two cannot be one setting for the
1502 /// renderer to choose: its first frame is on screen and its other frames are
1503 /// not, in the same widget, at the same moment.
1504 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1505 #[non_exhaustive]
1506 pub enum Loading {
1507 /// Needed with the screen. Fetch it now.
1508 #[default]
1509 Eager,
1510 /// Not on screen yet. It can wait until it is near.
1511 Lazy,
1512 }
1513
1514 /// What a [`Track`]'s integers count.
1515 ///
1516 /// `Track::fraction` never needed this -- the arithmetic is the same whatever
1517 /// the numbers mean -- which is exactly how the ruler came to assume minutes
1518 /// and print `00:00` over a month. A renderer drawing an axis has to write a
1519 /// label, and it cannot derive the unit from the numbers.
1520 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1521 #[non_exhaustive]
1522 pub enum Unit {
1523 /// Minutes from the start of a day. A day view.
1524 #[default]
1525 Minutes,
1526 /// Whole days. A month strip, a sprint, a stretch of leave.
1527 ///
1528 /// A day-granularity axis is a *strip*, not a calendar: one line with
1529 /// spans laid along it. What it deliberately does not do is wrap into
1530 /// weeks, which is the shape that makes weekday periodicity visible and
1531 /// the one job of a month grid that a strip cannot take over. See the
1532 /// crate header.
1533 Days,
1534 }
1535
1536 /// A window on an axis, in whatever [`Unit`] its [`Track`] counts.
1537 ///
1538 /// The axis a [`Track`] draws. Offsets rather than instants, because a
1539 /// description carrying a `DateTime` would carry a timezone with it and the
1540 /// vocabulary has no business holding one. The app knows which day or month
1541 /// this is; the description says how far along it a thing sits.
1542 ///
1543 /// `to` is exclusive and may exceed the natural period, which is how a span
1544 /// running past the end is said without a second date: under
1545 /// [`Unit::Minutes`], `Span::new(1320, 1560)` is 22:00 to 02:00.
1546 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1547 pub struct Span {
1548 from: u16,
1549 to: u16,
1550 }
1551
1552 impl Span {
1553 /// Midnight to midnight, the ordinary day.
1554 pub const DAY: Self = Self { from: 0, to: 1440 };
1555
1556 /// A span, clamped to a sane one.
1557 ///
1558 /// An empty or backwards span is a caller bug that should not cost a
1559 /// renderer a division by zero, so `to` is forced at least one minute past
1560 /// `from` rather than returning an error nobody can act on. Same reasoning
1561 /// as [`Share::percent`], which clamps rather than refuses.
1562 #[must_use]
1563 pub const fn new(from: u16, to: u16) -> Self {
1564 Self {
1565 from,
1566 to: if to > from { to } else { from + 1 },
1567 }
1568 }
1569
1570 /// The first minute on the axis.
1571 #[must_use]
1572 pub const fn from(self) -> u16 {
1573 self.from
1574 }
1575
1576 /// One past the last minute on the axis.
1577 #[must_use]
1578 pub const fn to(self) -> u16 {
1579 self.to
1580 }
1581
1582 /// How much the axis covers, in its track's unit. Never zero.
1583 #[must_use]
1584 pub const fn length(self) -> u16 {
1585 self.to - self.from
1586 }
1587
1588 /// Whether an offset falls on this axis.
1589 #[must_use]
1590 pub const fn holds(self, minute: u16) -> bool {
1591 minute >= self.from && minute < self.to
1592 }
1593 }
1594
1595 impl Default for Span {
1596 fn default() -> Self {
1597 Self::DAY
1598 }
1599 }
1600
1601 /// Where a thing sits on a [`Track`], and for how long.
1602 ///
1603 /// The one fact a list cannot carry and the whole reason this primitive exists.
1604 /// A list says what order things come in; a track says a thing starts 135
1605 /// minutes along and lasts 45, which is a different claim and not derivable
1606 /// from the first.
1607 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1608 pub struct Placement {
1609 at: u16,
1610 length: u16,
1611 }
1612
1613 impl Placement {
1614 /// A placement, clamped to a drawable one.
1615 ///
1616 /// Zero length becomes one for the same reason [`Span::new`] clamps: a
1617 /// zero-height thing is invisible rather than expressive, and every
1618 /// renderer would need its own guard.
1619 #[must_use]
1620 pub const fn new(at: u16, length: u16) -> Self {
1621 Self {
1622 at,
1623 length: if length == 0 { 1 } else { length },
1624 }
1625 }
1626
1627 /// Offset from the axis origin, matching [`Span`]'s.
1628 #[must_use]
1629 pub const fn at(self) -> u16 {
1630 self.at
1631 }
1632
1633 /// How long it lasts, in its track's unit. Never zero.
1634 #[must_use]
1635 pub const fn length(self) -> u16 {
1636 self.length
1637 }
1638
1639 /// One past its last minute.
1640 #[must_use]
1641 pub const fn end(self) -> u16 {
1642 self.at + self.length
1643 }
1644
1645 /// Whether two placements cover any of the same time.
1646 ///
1647 /// Geometry, and deliberately not a described field. Whether an overlap is
1648 /// a *conflict* is the app's judgment -- a meeting inside a block of free
1649 /// time overlaps and is fine -- and that judgment travels the way every
1650 /// other judgment does, as a [`Tone`] on the thing itself. What a renderer
1651 /// needs in order to lay two things side by side instead of on top of each
1652 /// other is this, and it can compute it.
1653 ///
1654 /// The alternative was a `conflicts: bool` on each entry, which is state
1655 /// that can disagree with the times beside it. Two sources for one fact is
1656 /// how a screen starts rendering a conflict badge on a thing that no longer
1657 /// conflicts.
1658 #[must_use]
1659 pub const fn overlaps(self, other: Self) -> bool {
1660 self.at < other.end() && other.at < self.end()
1661 }
1662 }
1663
1664 /// A time axis: things placed by when they happen, rather than flowed.
1665 ///
1666 /// # Why this is a primitive
1667 ///
1668 /// The argument against naming a timeline is that a description expressive
1669 /// enough to draw one is a component library wearing a description's name. It
1670 /// does not hold here, and being precise about why matters, because the
1671 /// reasoning applies to real cases.
1672 ///
1673 /// What a timeline needs that a [`List`](Region::Pane) does not is **one**
1674 /// thing: placement. Where a thing sits is a fact about the thing, the way a
1675 /// row's primary text is, and it is not derivable from order. Everything else a
1676 /// day view draws -- the labels, the gridlines, the item bodies, the tones --
1677 /// is furniture this vocabulary already names. Measured against goingson's
1678 /// `day-planning-render.js`, the only members it needed and could not get were
1679 /// `at` and `minutes`.
1680 ///
1681 /// So the timeline was never a component library's worth of vocabulary. It was
1682 /// two integers, and the refusal was priced as though it were the whole widget.
1683 /// The test that matters is not "does this shape look complicated" but "how
1684 /// many members does it actually add, and are they facts or presentation".
1685 /// Slot heights, gridline colour, how overlaps stack and which hour scrolls
1686 /// into view on open are all presentation and all stay the renderer's, which is
1687 /// why they are absent here.
1688 ///
1689 /// # What it does not carry
1690 ///
1691 /// No pixel measure, no scroll offset, no drag affordance. A renderer draws the
1692 /// span at whatever density its host uses; `makeover-geometry` owns that the
1693 /// way it owns everything else measured in pixels.
1694 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1695 pub struct Track {
1696 /// The window the axis covers.
1697 pub span: Span,
1698 /// The granularity a thing can be placed on, in minutes.
1699 ///
1700 /// goingson's day view is 15, giving 96 slots across a day. A renderer uses
1701 /// it to decide where gridlines fall and what a drop lands on; it does not
1702 /// constrain [`Placement`], because data arriving from a calendar does not
1703 /// respect anyone's grid.
1704 pub slot: u16,
1705 /// How often the axis labels itself, in its own unit.
1706 ///
1707 /// 60 gives an hourly ruler over a 15-minute grid, which is the common
1708 /// shape and the reason this is separate from `slot`. Zero means an
1709 /// unlabelled axis.
1710 pub tick: u16,
1711 /// What `span`, `slot`, `tick` and every [`Placement`] on it count.
1712 ///
1713 /// The one field here a renderer cannot derive, and the reason it exists:
1714 /// [`fraction`](Self::fraction) is unit-agnostic, so a day-granularity
1715 /// track produced correct geometry under an hours-and-minutes ruler until
1716 /// this was added. Geometry never needed it; a label always did.
1717 pub unit: Unit,
1718 }
1719
1720 impl Track {
1721 /// An ordinary day: midnight to midnight, quarter-hour slots, hourly ticks.
1722 pub const DAY: Self = Self {
1723 span: Span::DAY,
1724 slot: 15,
1725 tick: 60,
1726 unit: Unit::Minutes,
1727 };
1728
1729 /// A track over `span`, with the day's usual granularity.
1730 #[must_use]
1731 pub const fn over(span: Span) -> Self {
1732 Self {
1733 span,
1734 slot: 15,
1735 tick: 60,
1736 unit: Unit::Minutes,
1737 }
1738 }
1739
1740 /// A strip of whole days: one slot a day, a label a week.
1741 ///
1742 /// The shape a stretch of leave or a sprint is drawn on. Not a calendar --
1743 /// it does not wrap into weeks, and the crate header says why that
1744 /// distinction is the whole of what a month grid still has over this.
1745 #[must_use]
1746 pub const fn days(span: Span) -> Self {
1747 Self {
1748 span,
1749 slot: 1,
1750 tick: 7,
1751 unit: Unit::Days,
1752 }
1753 }
1754
1755 /// How many slots the axis holds.
1756 ///
1757 /// Rounded up, so a span that does not divide evenly by `slot` still has a
1758 /// slot covering its tail rather than dropping it. Never zero: `slot` of 0
1759 /// reads as one slot spanning the whole axis rather than a division by
1760 /// zero, since a renderer asking this question has already committed to
1761 /// drawing something.
1762 #[must_use]
1763 pub const fn slots(self) -> u16 {
1764 if self.slot == 0 {
1765 1
1766 } else {
1767 self.span.length().div_ceil(self.slot)
1768 }
1769 }
1770
1771 /// Where a placement sits on the axis, as a fraction from 0.0 to 1.0.
1772 ///
1773 /// The one calculation every renderer would otherwise write itself, and the
1774 /// place the three would drift apart. Clamped, so a placement outside the
1775 /// span draws at the edge rather than off it -- an event running past
1776 /// midnight is a real thing and truncating it is better than either
1777 /// panicking or drawing it somewhere impossible.
1778 #[must_use]
1779 pub fn fraction(self, minute: u16) -> f32 {
1780 let span = f32::from(self.span.length());
1781 let offset = f32::from(minute.saturating_sub(self.span.from()));
1782 (offset / span).clamp(0.0, 1.0)
1783 }
1784 }
1785
1786 impl Default for Track {
1787 fn default() -> Self {
1788 Self::DAY
1789 }
1790 }
1791
1792 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1793 pub struct Act<'a> {
1794 /// What the control says.
1795 pub label: &'a str,
1796 /// The key that reaches it where a host has keys.
1797 ///
1798 /// The one member written for a terminal before there was one. A webview
1799 /// hangs it off `accesskey` or ignores it; a terminal has nothing else to
1800 /// offer, so this is the whole of how a control is reached there.
1801 pub key: Option<&'a str>,
1802 /// What pressing it means. [`Tone::Danger`] is the destructive one.
1803 pub tone: Tone,
1804 /// Disabled, or nothing said.
1805 ///
1806 /// [`State::Disabled`] is what changes what a renderer may do: see
1807 /// [`State::suppresses_interaction`], which is what says a disabled control
1808 /// is drawn and not reachable. A control's focus is not sayable here at
1809 /// all: see the crate header, "Reach, focus and the focus ring".
1810 pub state: Option<State>,
1811 /// A sentence that is always true of this control, shown rather than hunted
1812 /// for.
1813 ///
1814 /// Standing help, not a message and not a tooltip. Half the hosts that read
1815 /// this have no pointer: a hover is one spelling of it, and the shipped
1816 /// apps reached for that spelling only because egui and a browser both had
1817 /// one. What is being said is that the sentence is true, never that it is
1818 /// hidden until a pointer arrives.
1819 ///
1820 /// # Why it is here rather than a layer up
1821 ///
1822 /// A hint left to `quasi_router::Act` alone means each renderer draws it
1823 /// for itself: `makeover_tui` had no hint to read, so quasi-tui built
1824 /// the muted line, and quasi-immediate called `on_hover_text` outside
1825 /// [`crate::Act`] rather than inside it. `Field::hint` was here the whole
1826 /// time, so the same idea sat at two layers depending on which thing
1827 /// carried it, and a host that was not quasi could say it of a field and
1828 /// not of a control.
1829 ///
1830 /// What kept it out was price rather than doubt: this crate declares
1831 /// `links`, so a member here moves 25 manifests across 12 repos. That is a
1832 /// release's forward-fix pass, which is a cost and was being read as a
1833 /// barrier.
1834 ///
1835 /// # What a renderer owes it
1836 ///
1837 /// Somewhere to put it, or nothing. Dropping it is legitimate; drawing it
1838 /// *instead of* the label is not, and neither is drawing it in a way that
1839 /// takes it out of the accessible tree, which is the failure `title` alone
1840 /// has on a browser. Nothing may live only in a hint.
1841 ///
1842 /// `None` is a control whose label is the whole of it, which is nearly all
1843 /// of them.
1844 pub hint: Option<&'a str>,
1845 }
1846
1847 impl<'a> Act<'a> {
1848 /// An ordinary control, reachable, with no key.
1849 #[must_use]
1850 pub const fn new(label: &'a str) -> Self {
1851 Self {
1852 label,
1853 key: None,
1854 tone: Tone::Neutral,
1855 state: None,
1856 hint: None,
1857 }
1858 }
1859
1860 /// The sentence that is always true of it; see [`hint`](Self::hint).
1861 ///
1862 /// A renderer with nowhere to put it drops it, so this must never be the
1863 /// only place a fact appears.
1864 #[must_use]
1865 pub const fn hinted(mut self, hint: &'a str) -> Self {
1866 self.hint = Some(hint);
1867 self
1868 }
1869
1870 /// The key that reaches it.
1871 #[must_use]
1872 pub const fn key(mut self, key: &'a str) -> Self {
1873 self.key = Some(key);
1874 self
1875 }
1876
1877 /// What pressing it means.
1878 #[must_use]
1879 pub const fn tone(mut self, tone: Tone) -> Self {
1880 self.tone = tone;
1881 self
1882 }
1883
1884 /// Focus, or disabled.
1885 #[must_use]
1886 pub const fn state(mut self, state: State) -> Self {
1887 self.state = Some(state);
1888 self
1889 }
1890
1891 /// Whether the control is drawn and does not answer.
1892 #[must_use]
1893 pub fn disabled(&self) -> bool {
1894 self.state.is_some_and(State::suppresses_interaction)
1895 }
1896 }
1897
1898 /// A named part of a screen.
1899 ///
1900 /// The thing `makeover-geometry` deliberately does not name: it names the space
1901 /// *between* things by relationship, and nothing named the things. Six named
1902 /// members, taken from what the two webview apps actually use, plus
1903 /// [`Region::Handover`] and [`Region::Ceded`] for the parts no description
1904 /// should reach. Both apps'
1905 /// `layout.css` currently names exactly two things, `.raised` and `.well`, so
1906 /// this layer is absent rather than divergent, which makes it the cheapest of
1907 /// the schemas to add and the easiest to over-build.
1908 ///
1909 /// `#[non_exhaustive]`, for [`RowPart`]'s and [`Readiness`]' reason: the member
1910 /// after this one should not be a lockstep event across three renderers.
1911 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1912 #[non_exhaustive]
1913 pub enum Region<'a> {
1914 /// A full-width strip with a title slot and an actions cluster, either of
1915 /// which may be empty. goingson's `.page-header`, Balanced Breakfast's
1916 /// `.header` and `.detail-header` are all this, differing only in which
1917 /// slots they fill.
1918 Band,
1919 /// A persistent column beside the content, holding navigation.
1920 Sidebar,
1921 /// A region of content with its own scroll.
1922 Pane,
1923 /// Things that belong together, and nothing else.
1924 ///
1925 /// The block [`Heading::Section`] names, which the vocabulary otherwise
1926 /// cannot contain. A section heading is a leaf sitting
1927 /// *beside* the things it names, so nothing said where a section started or
1928 /// ended and a renderer learned one had ended only because the next heading
1929 /// arrived.
1930 ///
1931 /// # The measurement
1932 ///
1933 /// 41 [`Heading::Section`] sites across the ten screens described through
1934 /// the router, not one of them contained. audiofiles' settings screen is the
1935 /// clearest: one pane holding a heading, a field, a heading, two toggles, a
1936 /// heading, a toggle and a heading, which is four sections and no
1937 /// containers. Under the hand-written CSS the ports are replacing the same
1938 /// block is spelled `.settings-section` in goingson, `.form-section` and
1939 /// `.content-section` in the MNW server, `.help-section` in Balanced
1940 /// Breakfast: three apps, four names, one shape.
1941 ///
1942 /// # Why the existing members were the wrong answer
1943 ///
1944 /// [`Pane`](Self::Pane) is what apps reached for, and it is 28 of the 45
1945 /// regions in the described screens. It claims a scroll of its own and
1946 /// [`Depth::Well`], so four settings groups inside a pane are four wells
1947 /// inside a well and four scroll contexts. Neither claim is true of a group.
1948 ///
1949 /// [`Widget`](Self::Widget) is wrong from the other side. Its own docs say a
1950 /// widget is never how a primitive gets added by the back door, and a run of
1951 /// related controls under a heading is furniture any app would have, which
1952 /// is the generic-against-bespoke bar a primitive has to clear.
1953 ///
1954 /// # What it does not carry
1955 ///
1956 /// **A heading.** A group usually has one and it is an ordinary node in the
1957 /// body, the way it already was. A group of related toggles with no heading
1958 /// is a real thing and a mandatory slot would forbid it.
1959 ///
1960 /// **A depth.** [`Depth::Flat`], on [`Handover`](Self::Handover)'s reasoning:
1961 /// it inherits, and an app that wants its group in a well puts it in a
1962 /// [`Pane`](Self::Pane), which composes rather than adding a knob here.
1963 ///
1964 /// **A colour.** Distinguishing sibling groups by colour is the thing this
1965 /// member was asked for and it is deliberately not stated here. The
1966 /// description says these things belong together; which of the theme's
1967 /// categorical colours a renderer reaches for, and whether it reaches for
1968 /// one at all, is derived from sibling order at the renderer. A terminal
1969 /// that tints nothing and separates with a rule is honouring this.
1970 Group,
1971 /// Two panes side by side, where the left chooses what the right shows.
1972 Split,
1973 /// Peer regions across, all of them equals.
1974 ///
1975 /// A kanban board's columns, and the shape [`Split`](Self::Split) is not:
1976 /// a split's two panes stand in a master-detail relationship, where the
1977 /// left chooses what the right shows. These choose nothing about each
1978 /// other. Each is a whole region and the set is the arrangement.
1979 ///
1980 /// # What it does not carry
1981 ///
1982 /// **How many.** The children say, and a count here would be a second
1983 /// source for something the description already states by containing them.
1984 ///
1985 /// **How wide.** Peers are equal by definition, so there is no [`Share`] to
1986 /// state. A board whose columns wanted different widths would be a
1987 /// different member, and no app has one.
1988 ///
1989 /// **What happens when there is no room.** Scroll across, wrap, or collapse
1990 /// to one column at a time: all three are right on some host, none is
1991 /// derivable from the description, and every one of them is presentation.
1992 /// A terminal that stacks them vertically is honouring this, not degrading
1993 /// it.
1994 ///
1995 /// # Why it is not an `Arrangement`
1996 ///
1997 /// [`Arrangement`] is the page's shape, and a board is usually a region
1998 /// *inside* a page that also has a band over it. Naming it here composes;
1999 /// naming it there would make a screen either a board or a list-detail and
2000 /// never a band above a board. It also keeps [`Arrangement::share`]
2001 /// meaningful, which a peer arrangement has no answer for.
2002 Columns,
2003 /// A set of panes, one visible at a time, and a [`Selector::Tabs`] that
2004 /// chooses between them.
2005 ///
2006 /// Says nothing about where the strip sits. A row over the panes, a column
2007 /// beside them, a wrapped run of links under them: all three are the same
2008 /// member drawn by a renderer that knows its host, the way the strip's
2009 /// overflow is.
2010 TabGroup,
2011 /// Content over a scrim, taking input until dismissed.
2012 Modal,
2013 /// A region this crate names the *place* of, whose contents the app still
2014 /// owes every host.
2015 ///
2016 /// The escape hatch, and the thing that keeps the description honest about
2017 /// its own limits. A day-plan timeline, a kanban board, a calendar and the
2018 /// paint interaction over the timeline are not describable here and are not
2019 /// going to become describable: a description expressive enough to produce
2020 /// a timeline is a widget library wearing a description's name.
2021 ///
2022 /// But a screen containing one still has to be a screen. Without this
2023 /// member the description covers only the boring screens, and the four that
2024 /// make goingson worth using would need a second, undescribed path beside
2025 /// the router. Two paths is how the vocabulary starts drifting from the app
2026 /// again, which is the exact failure this crate exists to end.
2027 ///
2028 /// So the description says "a thing called `day-plan` goes here" and stops.
2029 /// The name is opaque: this crate never interprets it, and no renderer is
2030 /// expected to know what it means beyond handing the space over.
2031 ///
2032 /// # What separates it from [`Ceded`](Self::Ceded)
2033 ///
2034 /// **A fill is owed here in every host's currency.** A renderer handed one
2035 /// of these and given nothing to put in it is looking at a hole the app
2036 /// meant to fill, and saying so is the honest drawing. [`owed`](Self::owed)
2037 /// is how it asks.
2038 ///
2039 /// That is the whole of the split. Before it there was one opaque member,
2040 /// so a region the description had given up on and a region nobody had
2041 /// converted yet were the same value, and both drew as a silently empty
2042 /// box on the two renderers that answer no fill.
2043 Handover {
2044 /// What the app calls it. Never interpreted here.
2045 name: &'a str,
2046 },
2047 /// A region this crate names the place of, whose contents no host is owed.
2048 ///
2049 /// The other half of the old single opaque member. The app has decided this
2050 /// space is not the description's to fill and is not going to become so:
2051 /// a chart, a waveform, a rendered picture of domain data with marks
2052 /// painted over it at positions no description knows.
2053 ///
2054 /// **Silence is the correct drawing.** A renderer with no fill for this
2055 /// draws nothing and is right to; unlike [`Handover`](Self::Handover) there
2056 /// is nothing missing. That is what makes the pair worth two members rather
2057 /// than a flag: the two want opposite behaviour from a renderer that cannot
2058 /// fill them, and one name cannot carry both.
2059 ///
2060 /// The measured sites are MNW's analytics charts, which already carry the
2061 /// ruling that a bar chart is not describable and should not be, and
2062 /// audiofiles' waveform, whose exclusion had no vocabulary to live in and
2063 /// was recorded in a doc comment instead.
2064 Ceded {
2065 /// What the app calls it. Never interpreted here.
2066 name: &'a str,
2067 },
2068 /// A named assembly of things the vocabulary already says.
2069 ///
2070 /// The third tier, between a primitive and the two opaque members.
2071 ///
2072 /// # What separates it from the two members either side
2073 ///
2074 /// A primitive is a thing every renderer draws from scratch, and the test
2075 /// it has to pass is that every host has an honest answer. A carousel fails
2076 /// that test — a terminal has no carousel — which is the same refusal
2077 /// `Node::Html` got and is why the carousel sat unsayable for months.
2078 ///
2079 /// [`Handover`](Self::Handover) fails it from the other side. It is for
2080 /// what one app owns and nobody will build twice, and it carries *no*
2081 /// contents: the description names the place and stops. A carousel is
2082 /// furniture any app would have, and every part of it — an ordered set of
2083 /// frames, a position, prev and next, a strip of position indicators — is
2084 /// already sayable. Only the assembly had no name.
2085 ///
2086 /// So this member is the pair the other two are not: a name **and**
2087 /// contents. The contents are the assembly, in the region's own body, said
2088 /// in members that already exist.
2089 ///
2090 /// # Why the name does not have to be understood
2091 ///
2092 /// A renderer that recognises the name draws it the way its host does it: a
2093 /// carousel in a webview, a pager with a count in a terminal, a selector in
2094 /// egui. A renderer that does not recognise it walks the body, which is
2095 /// primitives all the way down and which it can already draw.
2096 ///
2097 /// That is what lets the widget set be **open** without every renderer
2098 /// knowing every widget. An unrecognised widget degrades to its assembly
2099 /// instead of failing, so a second or third party can name one without
2100 /// three renderers releasing in lockstep to accept it. Contrast
2101 /// [`Handover`](Self::Handover), which no renderer can degrade: there is
2102 /// nothing under it to fall back to.
2103 ///
2104 /// # What it does not do
2105 ///
2106 /// A widget is an assembly of things the vocabulary *already* says, so it
2107 /// buys no expressive power. Anything needing a member the vocabulary does
2108 /// not have is a finding about the vocabulary, and the answer to a finding
2109 /// is to add the member. A widget is never the way a primitive gets added
2110 /// by the back door. A timeline is describable because [`Track`] was added
2111 /// to say it, not because a screen was dressed up as an assembly.
2112 Widget {
2113 /// What the assembly is called. This crate never interprets it, and a
2114 /// renderer is free not to know it.
2115 name: &'a str,
2116 },
2117 }
2118
2119 impl<'a> Region<'a> {
2120 /// How the region sits on what is behind it.
2121 #[must_use]
2122 pub const fn depth(self) -> Depth {
2123 match self {
2124 Self::Band | Self::Sidebar | Self::Split | Self::TabGroup => Depth::Flat,
2125 // Flat, and it inherits. A group says its contents belong together
2126 // and says nothing about the surface they sit on, so a group in a
2127 // pane is in a well and a group on the page is on the page. An app
2128 // wanting one lifted puts it in a `Pane`.
2129 Self::Group => Depth::Flat,
2130 // Flat, and it is the container rather than the columns. Each
2131 // column is its own region and brings its own depth; a well here
2132 // would put a second edge around a row of wells.
2133 Self::Columns => Depth::Flat,
2134 // A pane is looked into, the same as a table body or a tag tree.
2135 Self::Pane => Depth::Well,
2136 Self::Modal => Depth::Raised,
2137 // Flat because it inherits: a bespoke region takes the depth of
2138 // whatever frames it. An app that wants its timeline in a well puts
2139 // it in a `Pane`, which composes rather than adding a knob here.
2140 //
2141 // A widget inherits for the same reason and it matters more here,
2142 // because a widget is drawn by whichever renderer recognises it. A
2143 // depth set here would be this crate deciding that a carousel is
2144 // raised on every host, which is the kind of value the deferral
2145 // rule exists to refuse.
2146 Self::Handover { .. } | Self::Ceded { .. } | Self::Widget { .. } => Depth::Flat,
2147 }
2148 }
2149
2150 /// Whether this crate can say anything about the region's contents.
2151 ///
2152 /// A renderer walks the description and hands every region it understands
2153 /// to the right drawing code. This is how it tells the two apart, and the
2154 /// reason it is a method rather than a `matches!` at each renderer: there
2155 /// is exactly one opaque member and there should stay exactly one.
2156 ///
2157 /// [`Widget`](Self::Widget) is described, and that is the whole of what
2158 /// separates it from the two opaque members here. All three carry a name
2159 /// this crate never interprets; only the widget carries contents under it.
2160 /// A renderer that does not recognise a widget's name still walks its body,
2161 /// so there is nothing for it to hand over and nothing it cannot draw.
2162 #[must_use]
2163 pub const fn described(self) -> bool {
2164 !matches!(self, Self::Handover { .. } | Self::Ceded { .. })
2165 }
2166
2167 /// Whether a fill is owed here, for a renderer that has none.
2168 ///
2169 /// The question the single opaque member could not answer. True for
2170 /// [`Handover`](Self::Handover): the app meant to fill this and a renderer
2171 /// with nothing to put in it should say so. False for everything else,
2172 /// [`Ceded`](Self::Ceded) included, where silence is the correct drawing
2173 /// because nothing is missing.
2174 ///
2175 /// A method rather than a `matches!` at each renderer, for
2176 /// [`described`](Self::described)'s reason: three renderers writing the
2177 /// same match is three chances to disagree about what an empty region
2178 /// means.
2179 #[must_use]
2180 pub const fn owed(self) -> bool {
2181 matches!(self, Self::Handover { .. })
2182 }
2183
2184 /// The name an app gave this region, if it gave one.
2185 ///
2186 /// [`Handover`](Self::Handover), [`Ceded`](Self::Ceded) and
2187 /// [`Widget`](Self::Widget) are the members that carry a name, for two
2188 /// different purposes: the first two say what the app puts in the space,
2189 /// the third says what the assembly under it is called. A renderer dispatching on either wants the string without
2190 /// caring which member it came from, and writing that `matches!` at each
2191 /// renderer is how the two drift apart.
2192 #[must_use]
2193 pub const fn name(self) -> Option<&'a str> {
2194 match self {
2195 Self::Handover { name } | Self::Ceded { name } | Self::Widget { name } => Some(name),
2196 // Spelled out rather than a wildcard, so a member added later has
2197 // to answer whether it carries a name instead of inheriting `None`
2198 // by sitting under a `_`.
2199 Self::Band
2200 | Self::Sidebar
2201 | Self::Pane
2202 | Self::Group
2203 | Self::Split
2204 | Self::Columns
2205 | Self::TabGroup
2206 | Self::Modal => None,
2207 }
2208 }
2209 }
2210
2211 /// How many of a region's children are visible at once.
2212 ///
2213 /// One sentence covering three shapes: *this region holds several children and
2214 /// shows some of them, and the reader can change which.* A tab group, a
2215 /// carousel and a disclosure all need it, and without it a renderer has two
2216 /// moves: hardcode a widget name, or draw every child. That is what puts
2217 /// per-widget code in renderers.
2218 ///
2219 /// # What is here and what is not
2220 ///
2221 /// The *kind*, and only the kind. Which child is currently up is the current
2222 /// answer, and a layer that defers every address does not hold the current
2223 /// answer either — the split [`Selector`] already makes, where this crate says
2224 /// what kind of chooser a thing is and the router says which option is picked.
2225 /// So a holder of regions carries the index and the per-child label beside this.
2226 ///
2227 /// # What a renderer does with it
2228 ///
2229 /// Derives its chrome, once, for every widget rather than per name:
2230 ///
2231 /// - Children carrying labels get a strip of the labels, the current one marked.
2232 /// - Children carrying none get previous, position, next.
2233 /// - [`AtMostOne`](Self::AtMostOne) over one child gets a summary line that
2234 /// opens.
2235 ///
2236 /// The name on [`Region::Widget`] survives as app vocabulary, for a renderer
2237 /// that wants to do something *special* with one, which is what it should have
2238 /// been from the start.
2239 ///
2240 /// Degradation runs the way it already did: a renderer ignoring this draws every
2241 /// child, which is more content rather than less.
2242 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2243 #[non_exhaustive]
2244 pub enum Showing {
2245 /// Every child, in order. What every region did before this existed.
2246 #[default]
2247 All,
2248 /// Exactly one. A carousel, a tab group.
2249 One,
2250 /// One, or none. A disclosure, which is closed until it is opened.
2251 AtMostOne,
2252 }
2253
2254 impl Showing {
2255 /// Whether the reader can change which child is up.
2256 ///
2257 /// The question every renderer's region arm asks before deriving any
2258 /// chrome, and a method rather than a `matches!` at each renderer for
2259 /// [`Region::name`]'s reason: three renderers writing the same comparison is
2260 /// how they come to disagree about a member added later.
2261 #[must_use]
2262 pub const fn selective(self) -> bool {
2263 !matches!(self, Self::All)
2264 }
2265
2266 /// Whether showing nothing is a legal state.
2267 ///
2268 /// True only for [`AtMostOne`](Self::AtMostOne). A renderer needs this to
2269 /// know whether its control closes as well as moves: a carousel's row moves
2270 /// between frames and never reaches empty, and a disclosure's summary line
2271 /// is the same control wearing its closed state.
2272 #[must_use]
2273 pub const fn dismissible(self) -> bool {
2274 matches!(self, Self::AtMostOne)
2275 }
2276 }
2277
2278 /// A window onto a sequence: where it starts, how much it covers, and how long
2279 /// the sequence is when that is known.
2280 ///
2281 /// The mechanism under two things the vocabulary deliberately keeps apart. A
2282 /// carousel is a window of one frame over children that are all present; a
2283 /// paged list is a window of a page over rows most of which were never fetched.
2284 /// Those are different facts and they stay different types — [`Showing`] says
2285 /// which child is up, [`Paging`] says where a reader is in a query — but the
2286 /// arithmetic underneath is one piece of code, so a terminal and a browser
2287 /// cannot come to disagree about which frame is last.
2288 ///
2289 /// # Why `of` is optional and `count` is not
2290 ///
2291 /// `count` is what is on screen and is therefore always known. `of` is the
2292 /// length of the thing being windowed, and a host that cannot count says so by
2293 /// leaving it empty **for the life of the screen**. It is never "not counted
2294 /// yet": see "First paint is final paint" in the crate header. A total that
2295 /// turns up on a later pass widens the text that prints it.
2296 ///
2297 /// # Clamping
2298 ///
2299 /// Every derivation clamps rather than refusing, and a zero `count` answers
2300 /// `None` rather than dividing. A window past the end is a bug in the host, and
2301 /// a renderer that answered it by drawing nothing would report a region that
2302 /// vanished, which is the hardest kind of bug to find from what is on screen.
2303 /// [`Share::percent`] clamps for the same reason.
2304 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2305 pub struct Window {
2306 /// The index into the sequence where the window starts.
2307 pub from: usize,
2308 /// How many the window covers. One, for a carousel.
2309 pub count: usize,
2310 /// How long the sequence is, when the host can say.
2311 pub of: Option<usize>,
2312 }
2313
2314 impl Window {
2315 /// A window of `count`, starting at `from`, over a sequence of unknown
2316 /// length.
2317 #[must_use]
2318 pub const fn new(from: usize, count: usize) -> Self {
2319 Self {
2320 from,
2321 count,
2322 of: None,
2323 }
2324 }
2325
2326 /// How long the sequence is.
2327 #[must_use]
2328 pub const fn of(mut self, of: usize) -> Self {
2329 self.of = Some(of);
2330 self
2331 }
2332
2333 /// One item of a sequence whose length is known. A carousel frame.
2334 #[must_use]
2335 pub const fn frame(at: usize, of: usize) -> Self {
2336 Self {
2337 from: at,
2338 count: 1,
2339 of: Some(of),
2340 }
2341 }
2342
2343 /// Which window this is, counting from zero.
2344 ///
2345 /// `None` when `count` is zero, which is the only input with no answer
2346 /// rather than a clamped one.
2347 #[must_use]
2348 pub const fn index(self) -> Option<usize> {
2349 if self.count == 0 {
2350 return None;
2351 }
2352 Some(self.from / self.count)
2353 }
2354
2355 /// How many windows the sequence holds.
2356 ///
2357 /// `None` unless both the length and a non-zero `count` are known. A
2358 /// partial answer here would be a renderer drawing "of 0".
2359 #[must_use]
2360 pub const fn windows(self) -> Option<usize> {
2361 match self.of {
2362 Some(of) if self.count > 0 => Some(of.div_ceil(self.count)),
2363 _ => None,
2364 }
2365 }
2366
2367 /// Whether anything sits before this window.
2368 #[must_use]
2369 pub const fn has_before(self) -> bool {
2370 self.from > 0
2371 }
2372
2373 /// How many sit after this window, when the length is known.
2374 ///
2375 /// Here rather than in each renderer for [`Showing::selective`]'s reason:
2376 /// three of them writing the same subtraction is how they come to disagree,
2377 /// and this one has an underflow in it for whoever writes it fourth.
2378 #[must_use]
2379 pub const fn after(self) -> Option<usize> {
2380 match self.of {
2381 Some(of) => Some(of.saturating_sub(self.from.saturating_add(self.count))),
2382 None => None,
2383 }
2384 }
2385
2386 /// Whether anything sits after it.
2387 ///
2388 /// `true` when the length is unknown: a host that cannot count cannot rule
2389 /// out more, and offering a way forward that turns out to be empty is the
2390 /// cheaper of the two mistakes.
2391 #[must_use]
2392 pub const fn has_after(self) -> bool {
2393 match self.of {
2394 Some(of) => self.from.saturating_add(self.count) < of,
2395 None => true,
2396 }
2397 }
2398
2399 /// The window with `from` brought inside the sequence.
2400 ///
2401 /// A no-op when the length is unknown, since there is nothing to clamp
2402 /// against.
2403 #[must_use]
2404 pub const fn clamped(mut self) -> Self {
2405 if let Some(of) = self.of
2406 && self.from >= of
2407 {
2408 // `max(1)` by hand: `Ord::max` is not const yet, and a zero-count
2409 // window would otherwise clamp onto the end rather than inside it.
2410 let step = if self.count == 0 { 1 } else { self.count };
2411 self.from = of.saturating_sub(step);
2412 }
2413 self
2414 }
2415 }
2416
2417 /// Where a reader is in a set that arrived in parts.
2418 ///
2419 /// A [`Window`] wearing the paged reading of itself. Distinct from a carousel's
2420 /// window at the top level on purpose, because the intent differs and a call
2421 /// site should say which one it means, while the arithmetic below is shared so
2422 /// the two cannot drift apart.
2423 ///
2424 /// # The two idioms, and which one a renderer may draw
2425 ///
2426 /// Load-more and numbered pages are both this type. Which is honest is
2427 /// [`paged`](Self::paged): a set whose page size is known can be drawn as
2428 /// "Page 3 of 8", and one without can only be drawn as "150 of 400" and a way
2429 /// forward. Saying it here rather than letting each renderer guess is the point
2430 /// — three renderers inferring it from the numbers is how they come to disagree.
2431 ///
2432 /// # What it does not carry
2433 ///
2434 /// No addresses. `makeover-layout` cannot name an action, and the way to ask for
2435 /// the next part is the host's: `quasi_router` pairs this with the addresses the
2436 /// same way `Row` pairs its parts with `Row::activate`. That split is the reason
2437 /// this type is reusable by a carousel, which has nothing to ask.
2438 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2439 pub struct Paging {
2440 /// The window onto the set.
2441 pub window: Window,
2442 /// Whether the parts are a fixed size, and so whether pages are countable.
2443 ///
2444 /// `false` for load-more, where the window simply grew and "page 2" would
2445 /// name nothing.
2446 pub paged: bool,
2447 }
2448
2449 impl Paging {
2450 /// A page of `per`, starting at `from`.
2451 #[must_use]
2452 pub const fn pages(from: usize, per: usize) -> Self {
2453 Self {
2454 window: Window::new(from, per),
2455 paged: true,
2456 }
2457 }
2458
2459 /// The first `shown`, with more behind them.
2460 ///
2461 /// The load-more shape: the window starts at the beginning and grows, so
2462 /// there is no page to number.
2463 #[must_use]
2464 pub const fn more(shown: usize) -> Self {
2465 Self {
2466 window: Window::new(0, shown),
2467 paged: false,
2468 }
2469 }
2470
2471 /// How many there are altogether.
2472 ///
2473 /// Left unsaid by a host that cannot count, and left unsaid **for good**:
2474 /// a total arriving later widens whatever prints it. See "First paint is
2475 /// final paint" in the crate header.
2476 #[must_use]
2477 pub const fn of(mut self, of: usize) -> Self {
2478 self.window = self.window.of(of);
2479 self
2480 }
2481
2482 /// Which page this is, counting from one, when pages are countable.
2483 ///
2484 /// One-based because it is read aloud. [`Window::index`] is the zero-based
2485 /// form for anyone indexing with it.
2486 #[must_use]
2487 pub const fn page(self) -> Option<usize> {
2488 if !self.paged {
2489 return None;
2490 }
2491 match self.window.index() {
2492 Some(index) => Some(index + 1),
2493 None => None,
2494 }
2495 }
2496
2497 /// How many pages there are, when that is countable.
2498 #[must_use]
2499 pub const fn pages_total(self) -> Option<usize> {
2500 if !self.paged {
2501 return None;
2502 }
2503 self.window.windows()
2504 }
2505
2506 /// How many are on screen.
2507 #[must_use]
2508 pub const fn shown(self) -> usize {
2509 self.window.count
2510 }
2511
2512 /// How many there are, when the host counted.
2513 #[must_use]
2514 pub const fn total(self) -> Option<usize> {
2515 self.window.of
2516 }
2517
2518 /// How many are not shown yet, when the host counted.
2519 ///
2520 /// The figure a load-more control puts in its label. `None` is the honest
2521 /// and common case: a set that cannot say how many more there are still has
2522 /// a way to ask for them.
2523 #[must_use]
2524 pub const fn remaining(self) -> Option<usize> {
2525 self.window.after()
2526 }
2527
2528 /// Whether there is anything further on.
2529 #[must_use]
2530 pub const fn has_more(self) -> bool {
2531 self.window.has_after()
2532 }
2533
2534 /// Whether there is anything back the other way.
2535 #[must_use]
2536 pub const fn has_previous(self) -> bool {
2537 self.window.has_before()
2538 }
2539 }
2540
2541 /// How much of the width an arrangement's first region takes.
2542 ///
2543 /// Nothing said how much room a region got, so every renderer invented its own
2544 /// number and two hosts showing one screen disagreed about its proportions. A
2545 /// webview never noticed, because the stylesheet answered once for every
2546 /// consumer; a terminal has no stylesheet to inherit from, so `quasi-tui`
2547 /// picked 24 columns for a sidebar and 40% for a list pane and neither had
2548 /// anything behind it.
2549 ///
2550 /// # A proportion, never a unit
2551 ///
2552 /// Held as a percentage, and that is the only form it comes in. A description
2553 /// carrying columns would be describing a terminal and one carrying pixels a
2554 /// webview, and the whole point is that both honour the same fact: a terminal
2555 /// resolves it against a column count, a webview writes it into a grid, and
2556 /// neither has to know what the other did.
2557 ///
2558 /// It is not [`makeover_geometry::Ratio`]'s job either, which was the first
2559 /// guess. Geometry is scales that answer the same for every screen and takes
2560 /// no input that would let a sidebar screen differ from a list-detail one.
2561 ///
2562 /// [`makeover_geometry::Ratio`]: https://docs.rs/makeover-geometry
2563 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
2564 pub struct Share(u8);
2565
2566 impl Share {
2567 /// What a sidebar takes, when nobody says otherwise.
2568 ///
2569 /// A quarter. `quasi-tui` drew 24 columns, which is a quarter of a
2570 /// 96-column terminal and about a fifth of a wide one; a quarter is that
2571 /// number said in the form a webview can honour too.
2572 pub const SIDEBAR: Self = Self(25);
2573
2574 /// What the list side of a list-detail takes, when nobody says otherwise.
2575 ///
2576 /// `quasi-tui`'s 40%, which was already a proportion and is the one number
2577 /// this member did not have to invent.
2578 pub const LIST: Self = Self(40);
2579
2580 /// A share of the width, as a percentage.
2581 ///
2582 /// Clamped to 5..=95 rather than refused. A description that asked for a
2583 /// region of nothing is a bug in the app, and a renderer drawing a region
2584 /// zero cells wide reports it as a region that vanished, which is the
2585 /// hardest kind of bug to find from what is on the screen.
2586 #[must_use]
2587 pub const fn percent(percent: u8) -> Self {
2588 Self(if percent < 5 {
2589 5
2590 } else if percent > 95 {
2591 95
2592 } else {
2593 percent
2594 })
2595 }
2596
2597 /// The share as a percentage.
2598 #[must_use]
2599 pub const fn as_percent(self) -> u8 {
2600 self.0
2601 }
2602
2603 /// This share of a width, rounded to the nearest whole unit.
2604 ///
2605 /// What a terminal calls to turn the proportion into columns. At least one,
2606 /// because a region the description named should be visible: a screen
2607 /// 3 columns wide is unusable either way, and a sidebar that is there is a
2608 /// truer picture of the description than a sidebar that is not.
2609 #[must_use]
2610 pub const fn of(self, whole: u16) -> u16 {
2611 let taken = (whole as u32 * self.0 as u32).div_ceil(100);
2612 if taken == 0 { 1 } else { taken as u16 }
2613 }
2614 }
2615
2616 /// How a screen is laid out.
2617 ///
2618 /// Three, and no one of them is a variant of another. goingson is list-detail,
2619 /// Balanced Breakfast is sidebar plus content, and MNW's embeds are one region
2620 /// filling the document. The tab group is a modifier rather than a member,
2621 /// because goingson uses it *inside* the same content region rather than
2622 /// instead of one.
2623 ///
2624 /// This exists at all because the router has to be able to express a screen
2625 /// rather than only a control. Discovering the arrangement layer missing after
2626 /// the renderers exist is a redesign; naming two now is a morning.
2627 ///
2628 /// # Why the share rides here
2629 ///
2630 /// A share is per-arrangement: how much a sidebar takes and how much a list
2631 /// side takes are different questions, and this enum is the only thing that
2632 /// knows which one is being asked. Geometry would have had to invent a channel
2633 /// to be told.
2634 ///
2635 /// [`list_detail`](Self::list_detail) and
2636 /// [`sidebar_content`](Self::sidebar_content) build these with the default
2637 /// shares, so a screen that has no opinion does not have to have one.
2638 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2639 pub enum Arrangement {
2640 /// A list that chooses what the detail beside it shows.
2641 ListDetail {
2642 /// Whether the detail side is a [`Region::TabGroup`].
2643 tabbed: bool,
2644 /// How much of the width the list side takes.
2645 share: Share,
2646 },
2647 /// Navigation down the side, content filling the rest.
2648 SidebarContent {
2649 /// How much of the width the sidebar takes.
2650 share: Share,
2651 },
2652 /// One region, filling the document.
2653 ///
2654 /// The other two are both about dividing a width between two regions, so a
2655 /// screen that is one region had to borrow one of them and then undo it:
2656 /// MNW's five embeds said `list_detail(title, false)` and the host spent a
2657 /// `display: block` cancelling the grid that produced. A host writing CSS
2658 /// to contradict the description rather than to add to it is the thing
2659 /// this member ends.
2660 ///
2661 /// Carries no [`Share`], because there is no division to describe. That is
2662 /// why [`share`](Self::share) answers `None` here.
2663 Single,
2664 }
2665
2666 impl Arrangement {
2667 /// A list and a detail beside it, at the default share.
2668 #[must_use]
2669 pub const fn list_detail(tabbed: bool) -> Self {
2670 Self::ListDetail {
2671 tabbed,
2672 share: Share::LIST,
2673 }
2674 }
2675
2676 /// A sidebar and content beside it, at the default share.
2677 #[must_use]
2678 pub const fn sidebar_content() -> Self {
2679 Self::SidebarContent {
2680 share: Share::SIDEBAR,
2681 }
2682 }
2683
2684 /// How much of the width the first region takes, when two regions divide it.
2685 ///
2686 /// `None` for [`Single`](Self::Single): one region takes the width, and a
2687 /// renderer that asked how to divide it was asking the wrong question. It
2688 /// answers `Option` rather than a full-width `Share` so that a host cannot
2689 /// quietly draw a one-region screen as a grid with an empty second column.
2690 #[must_use]
2691 pub const fn share(self) -> Option<Share> {
2692 match self {
2693 Self::ListDetail { share, .. } | Self::SidebarContent { share } => Some(share),
2694 Self::Single => None,
2695 }
2696 }
2697
2698 /// The same arrangement, at this share.
2699 ///
2700 /// [`Single`](Self::Single) is returned unchanged: it has no division to
2701 /// set, so a share named for it is a statement about nothing rather than an
2702 /// error worth refusing a screen over.
2703 #[must_use]
2704 pub const fn with_share(self, share: Share) -> Self {
2705 match self {
2706 Self::ListDetail { tabbed, .. } => Self::ListDetail { tabbed, share },
2707 Self::SidebarContent { .. } => Self::SidebarContent { share },
2708 Self::Single => Self::Single,
2709 }
2710 }
2711 }
2712
2713 /// How wide the content of a whole screen runs.
2714 ///
2715 /// Both are the description's, which is what answering the two together
2716 /// settled.
2717 ///
2718 /// Measured in the MNW server, where 69 of 72 templates carry exactly one of
2719 /// three mutually exclusive classes and the choice is per screen. GoingsOn
2720 /// reaches for `max-width` 56 times and Balanced Breakfast 12, neither with a
2721 /// token for it, so three apps were solving one thing by hand.
2722 ///
2723 /// # Named for the measure, not for MNW's classes
2724 ///
2725 /// A renderer that is not a browser has to answer this too, and `padded-page`
2726 /// tells a terminal nothing. The three say how wide the text runs, which is a
2727 /// question every renderer can answer: a webview with a `max-width`, a terminal
2728 /// with gutters, an immediate-mode frame with its own width.
2729 ///
2730 /// `#[non_exhaustive]` for [`Fill`]'s reason. The set is closed today because
2731 /// the measurement found three, and a fourth arriving should not be a lockstep
2732 /// release across nine repos.
2733 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2734 #[non_exhaustive]
2735 pub enum Measure {
2736 /// The whole width, with gutters. The default, and 53 of the 69.
2737 ///
2738 /// What a dashboard, a table and a settings screen want: the content is
2739 /// wide because the content *is* wide, and constraining it would waste the
2740 /// window.
2741 #[default]
2742 Wide,
2743 /// Capped at a comfortable page width, centred. 13 of the 69.
2744 ///
2745 /// A form, a sign-in, a purchase. Content that does not get better by
2746 /// getting wider, but is not prose either.
2747 Contained,
2748 /// Capped at a line length that reads well. 3 of the 69.
2749 ///
2750 /// Prose. The narrowest of the three, and the one with a reason outside
2751 /// taste: a line of text past roughly 75 characters costs the reader the
2752 /// return sweep.
2753 Reading,
2754 }
2755
2756 impl Measure {
2757 /// A stable name, for a renderer that needs to spell it.
2758 ///
2759 /// Here rather than in each renderer for [`Sort::as_str`]'s reason: three
2760 /// renderers spelling one enum is three chances to spell it differently.
2761 #[must_use]
2762 pub const fn as_str(self) -> &'static str {
2763 match self {
2764 Self::Wide => "wide",
2765 Self::Contained => "contained",
2766 Self::Reading => "reading",
2767 }
2768 }
2769 }
2770
2771 /// What kind of value a form field takes.
2772 ///
2773 /// The union of the two vocabularies that diverged, which is what triggered
2774 /// this crate. They have since converged on their own: both apps now have a
2775 /// `renderFormField` emitting the same anatomy, and what is left differing is
2776 /// the kind set, the error shape, and whether the return is a string or a node.
2777 ///
2778 /// Validation is deliberately absent. Neither app has a shared story (goingson
2779 /// validates after collecting the form data, with per-field transform hooks;
2780 /// Balanced Breakfast has `required` and nothing else), and a schema that
2781 /// describes fields but not constraints acquires a constraint layer per app,
2782 /// which is exactly how the current divergence started. Naming it absent is a
2783 /// decision; leaving it unmentioned would not be.
2784 /// `#[non_exhaustive]` for the reason [`Fill`] is: renderers match on this and
2785 /// the set keeps growing, so growth must not be a lockstep event.
2786 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2787 #[non_exhaustive]
2788 pub enum FieldKind {
2789 /// A single line of text.
2790 Text,
2791 /// A single line of text that must never be echoed, logged or round-tripped
2792 /// through anything that might persist it.
2793 Secret,
2794 /// A number.
2795 Number,
2796 /// A number inside bounds the user drags across, where the range being
2797 /// visible is the point.
2798 ///
2799 /// Not [`Number`](Self::Number) with [`min`](Field::min) and
2800 /// [`max`](Field::max), which is the reading to resist and is the same
2801 /// resistance [`Radio`](Self::Radio) needed against `Select`. A bounded
2802 /// number and a validated number are different *questions*. A validated
2803 /// number is typed and can be wrong: the bounds are a rule the answer is
2804 /// checked against, and being told "must be at least 1" afterwards is the
2805 /// normal course of it. A range cannot be out of range at all, because the
2806 /// bounds are the control's extent rather than a rule, and the two ends are
2807 /// what the question means — audiofiles asks for a classifier threshold
2808 /// between 0 and 1, where 0 is never and 1 is only-on-certainty, and a typed
2809 /// 0.72 says nothing without both ends on screen beside it.
2810 ///
2811 /// A renderer cannot infer which one is meant from `min`/`max` alone, which
2812 /// is why this is a kind and not an inference: goingson's `min="1"` duration
2813 /// is a validated number and would become a slider.
2814 ///
2815 /// The membership test passes without stretching: a webview emits
2816 /// `<input type="range">`, egui has `Slider`, a terminal draws a bar and
2817 /// takes arrow keys, a CLI takes a bounded argument.
2818 ///
2819 /// # It owes its bounds
2820 ///
2821 /// [`min`](Field::min) and [`max`](Field::max) are `Option` for every other
2822 /// kind and are **required** here, in the sense the description can require
2823 /// anything: [`Field::bounded`] is the check, and a range missing one has no
2824 /// extent for a renderer to draw. What a renderer does with an unbounded
2825 /// range is its own call and both answers are honest — fall back to a typed
2826 /// number, or pick a host default — so this is stated rather than enforced,
2827 /// the way every other constraint here is.
2828 ///
2829 /// [`Field::step`] is the third fact and is genuinely optional: absent, the
2830 /// host's own granularity stands.
2831 Range,
2832 /// One question with two ends: a lower value and an upper one, submitted
2833 /// under two names.
2834 ///
2835 /// "Show me samples between 90 and 130 BPM" has a single answer with two
2836 /// ends, and the ends constrain each other: a minimum above the maximum is
2837 /// not a wrong value, it is an empty result nobody asked for. Described as
2838 /// two [`Number`](Self::Number) fields that is unsayable — nothing says they
2839 /// are one question, so a renderer draws two controls with two labels and no
2840 /// relationship, and [`Field::error`] can only be attached to one side of a
2841 /// fault that belongs to both.
2842 ///
2843 /// Not [`Range`](Self::Range), which was the reading to resist and the
2844 /// resistance is the same one `Range` itself needed against `Number`. A
2845 /// range describes *one* value inside an extent; this describes two, and the
2846 /// extent is a bound on each rather than the question's meaning. The two
2847 /// come apart in the answer: a range has a value, an interval has a pair,
2848 /// and either end may be absent while the other stands.
2849 ///
2850 /// # It states both names
2851 ///
2852 /// [`Field::name`] is the lower end and [`Field::upper_name`] is the upper
2853 /// one, stated rather than derived. One member instead of a naming
2854 /// convention this crate would then own forever.
2855 ///
2856 /// Direction is carried by which member the name sits in, so nothing
2857 /// separate says which end is which.
2858 ///
2859 /// # What it does not enforce
2860 ///
2861 /// The crossing rule. A lower end above the upper one is describable here
2862 /// and always was, exactly as an out-of-[`min`](Field::min) number is: this
2863 /// crate carries constraints and never checks them, and deciding a value is
2864 /// wrong stays with whoever validated. What the description buys is that the
2865 /// fault now has one place to be reported rather than two.
2866 ///
2867 /// # Both ends take the same facts
2868 ///
2869 /// [`min`](Field::min), [`max`](Field::max), [`step`](Field::step) and
2870 /// [`unit`](Field::unit) describe the axis rather than one end of it, so
2871 /// they are read once and applied to both. Six of audiofiles' filter axes
2872 /// are exactly this: one extent, one unit, one granularity, two ends.
2873 ///
2874 /// The bounds are optional here, unlike `Range`. They are a rule the answer
2875 /// is checked against rather than the control's extent, which is
2876 /// [`Number`](Self::Number)'s arrangement and not a slider's.
2877 Interval,
2878 /// An email address.
2879 ///
2880 /// Distinct from [`Text`](Self::Text) because the distinction is not
2881 /// decoration: a webview renderer emits `type="email"`, which on a touch
2882 /// device changes the keyboard that appears and turns on the platform's own
2883 /// validation. goingson ships to iOS, so collapsing this into text costs a
2884 /// keyboard with no `@` on it.
2885 Email,
2886 /// A URL. Same reasoning as [`Email`](Self::Email).
2887 Url,
2888 /// A telephone number. Same reasoning as [`Email`](Self::Email), and the
2889 /// clearest case of it: the keyboard is a numeric pad rather than letters.
2890 Tel,
2891 /// A calendar day, with no time of day in it.
2892 ///
2893 /// [`Email`](Self::Email)'s argument, and it carries further: a webview
2894 /// emits `type="date"`, which is a native picker, the platform's own
2895 /// validation, and on a touch device the date keyboard. Described as
2896 /// [`Text`](Self::Text) with a hint reading "YYYY-MM-DD", all three are
2897 /// lost and the hint is doing the platform's job in prose.
2898 ///
2899 /// The membership test passes on every host without stretching: a webview
2900 /// and a Tauri app emit the input, egui has a date picker, a terminal
2901 /// prompts for a day and can validate it, a CLI takes an argument.
2902 ///
2903 /// # The value is ISO 8601, `YYYY-MM-DD`
2904 ///
2905 /// Named here rather than left to each host, because a host that picks
2906 /// differently sends a server something it parses differently, and the
2907 /// failure is silent and per-host. It is `<input type="date">`'s own wire
2908 /// format, so the webview renderer owes nothing to honour it and the other
2909 /// hosts have one spelling to meet. [`DATE_FORMAT`] is the constant, and a
2910 /// test asserts this doc and that constant agree.
2911 Date,
2912 /// A calendar day and a time of day together.
2913 ///
2914 /// Apart from [`Date`](Self::Date) because the question is different rather
2915 /// than more precise: "which day does this expire" and "at what moment does
2916 /// this publish" are asked by different screens and answered by different
2917 /// controls. A webview emits `type="datetime-local"` for one and
2918 /// `type="date"` for the other, and a host that collapsed them would ask
2919 /// half the tree for a precision it does not want.
2920 ///
2921 /// Both arrived together on measurement rather than on symmetry: 13 sites
2922 /// of each across the MNW server and goingson, and **zero** of `time`,
2923 /// `month` or `week`, which is why those are not here. A member added for a
2924 /// case nobody has is a member designed against nothing, which is
2925 /// [`File`](Self::File)'s reasoning about `accept` applied to a whole
2926 /// member.
2927 ///
2928 /// # The value is `YYYY-MM-DDTHH:MM`, local, with no zone
2929 ///
2930 /// `<input type="datetime-local">`'s own format, and the "local" is the
2931 /// load-bearing half: the value carries no offset and no `Z`, so the moment
2932 /// it names is only fixed once something supplies a zone. That is the app's
2933 /// business and not the description's. Seconds are absent, which is the
2934 /// browser's own default and is left as the rule rather than restated as a
2935 /// constraint. [`DATETIME_FORMAT`] is the constant.
2936 ///
2937 /// [`Field::min`] and [`Field::max`] already take "the host's own spelling
2938 /// of a bound", so a floor of *not in the past* needs nothing new here: it
2939 /// is a string in this same format.
2940 DateTime,
2941 /// Several lines of text.
2942 Textarea,
2943 /// Several lines of text the user writes markdown in.
2944 ///
2945 /// The editing counterpart of prose a description carries as markdown
2946 /// source, and the reason it can exist at all is the same one that lets the
2947 /// source be carried: editing markdown is editing text, so a terminal, an
2948 /// immediate-mode host and a webview all have an honest answer, and none of
2949 /// them has to refuse. A kind that meant "rich text" in the WYSIWYG sense
2950 /// would have been a document model, and two of the three hosts would have
2951 /// had to draw something they cannot.
2952 ///
2953 /// What the mark buys over [`Textarea`](Self::Textarea) is that a renderer
2954 /// may offer the affordances markdown has and plain text does not — a
2955 /// preview, a syntax pass, a monospaced face for the source — and that a
2956 /// host reading the value back knows what it is holding. A renderer with
2957 /// none of that draws a textarea, which is why this is additive rather than
2958 /// a second control.
2959 ///
2960 /// It says nothing about **when** the value is saved. Autosave is a clock,
2961 /// clocks are not described here, and the four MNW editors this was measured
2962 /// against each keep their own.
2963 ///
2964 /// Sanitising stays where it already is for markdown that is only displayed:
2965 /// with the renderer, at the point markup is produced. Being described is
2966 /// not a safety property, and a host with its own sanitiser and its own
2967 /// content-security posture still owns both.
2968 Rich,
2969 /// One of a fixed set, offered behind a control that shows one at a time.
2970 Select,
2971 /// One of a fixed set, with every option on screen at once.
2972 ///
2973 /// Not a presentation of [`Select`](Self::Select), which is the reading to
2974 /// resist: what differs is a property of the *question*. A choice that is
2975 /// consequential or irreversible has to be readable without opening
2976 /// anything, because a closed control shows one option and hides the rest,
2977 /// and the one it shows is whichever was current before the user had read
2978 /// the alternatives. audiofiles asks whether a library copies samples into
2979 /// its store or references them where they lie — which cannot be changed
2980 /// afterwards — and had already promoted that out of a checkbox by hand,
2981 /// with a comment giving this reason, before the description could say it.
2982 ///
2983 /// Everything here is an `<input type=...>`, a `<select>` or a
2984 /// `<textarea>`, and the way this enum grows is by a site being measured
2985 /// rather than by a list being completed. No member is ever "the last one".
2986 Radio,
2987 /// On or off.
2988 Checkbox,
2989 /// A file the user picks from wherever the host keeps files.
2990 ///
2991 /// It was filed as a router finding — a control whose destination is a
2992 /// host capability rather than an address — and splitting it is what made
2993 /// it two answers instead of one member satisfying neither. *Opening* a
2994 /// file is a one-way handoff and needs no new API. *Picking* one returns a
2995 /// value into a write, which is a form concern, which is this.
2996 ///
2997 /// The membership test passes on every host and not by a stretch: a Tauri
2998 /// app opens a native picker, a server renders `<input type="file">`, a
2999 /// terminal prompts for a path, a CLI takes an argument. That is closer to
3000 /// [`Email`](Self::Email), which exists because it changes the keyboard,
3001 /// than to anything bespoke.
3002 ///
3003 /// # The four things an upload says, and where each of them lives
3004 ///
3005 /// | axis | where |
3006 /// |---|---|
3007 /// | what it accepts | [`Field::accept`] |
3008 /// | one file or several | [`Field::multiple`] |
3009 /// | where the bytes go | the router's action, not here |
3010 /// | how far along it is | [`Awaiting`] on that action |
3011 ///
3012 /// Only the first two are this crate's, and that split is the answer to
3013 /// "describe an upload in full" rather than a gap in it. A destination is an
3014 /// address and this crate holds no addresses; progress is a live number and
3015 /// a description is built once, so the number is the renderer's to observe
3016 /// against the size [`Awaiting::amount`] carried before the transfer began.
3017 ///
3018 /// # How the file is handed over is the host's
3019 ///
3020 /// A drop area, a button opening a native picker, a path typed at a prompt:
3021 /// all three are the same field, and every measured site has the first. It
3022 /// is not described for the reason no gesture is — this crate owns no
3023 /// coordinates and no pointer, and a terminal that cannot be dropped on
3024 /// would be refusing a description it can otherwise honour completely.
3025 ///
3026 /// [`Field::accept`] and [`Field::multiple`] are measured rather than
3027 /// deferred. A member designed against nothing is the rule to keep: count
3028 /// the sites before adding one.
3029 File,
3030 /// Which theme the app wears.
3031 ///
3032 /// The one member here that names a *subject* rather than a shape of
3033 /// answer, and it is worth saying why that is not the door it looks like.
3034 /// Every other kind is a question a screen might ask about anything; this
3035 /// one is a specific question every app in the family asks, once, on its
3036 /// settings screen, and three of them wrote the same control by hand.
3037 ///
3038 /// # It is furniture, and the measurement is what says so
3039 ///
3040 /// The reading to resist is that this is [`Select`](Self::Select) with a
3041 /// grouped option list. Max rejected that: `optgroup` appears at one live
3042 /// site in the tree and the non-theme grouping count is zero, so the thing
3043 /// that recurs is this picker rather than option lists that group.
3044 ///
3045 /// # What it carries that a select cannot
3046 ///
3047 /// [`Field::themes`] rather than [`Field::options`], because a theme is
3048 /// four facts and an option is two. The two extra facts are the ones no
3049 /// app can supply without redoing work the theme layer has already done:
3050 /// which [`ThemeVariant`] group a theme is in, and how legible its muted
3051 /// text measured. `Choice::new(id, format!("{name} ({variant})"))` is what
3052 /// the three apps had, and it flattens the group into prose and loses the
3053 /// tier entirely.
3054 ///
3055 /// [`Field::follows`] carries the entry that is not a theme.
3056 ///
3057 /// # The cost, stated rather than discovered later
3058 ///
3059 /// This puts one screen's shape into a vocabulary that otherwise holds
3060 /// none, which was the objection raised against it and accepted going in.
3061 /// The mitigation is narrowness: this describes a theme picker, not a
3062 /// general "list the host resolved" mechanism. A second host-resolved list
3063 /// is when that generalisation gets measured, and not before.
3064 ///
3065 /// A renderer that has not heard of it draws a select over
3066 /// [`Field::themes`]' names and loses the grouping, which is the state
3067 /// every app was in before this member. Degrading to the status quo ante
3068 /// is the floor the member is designed against.
3069 Theme,
3070 /// Carried through the form and never shown.
3071 Hidden,
3072 }
3073
3074 /// The wire format a [`FieldKind::Date`] value takes: ISO 8601, `YYYY-MM-DD`.
3075 ///
3076 /// A constant rather than a sentence in a doc comment, because the reason to
3077 /// name the format at all is that a host picking its own would fail silently
3078 /// against a server parsing another. A host that cannot emit the native control
3079 /// still has one spelling to meet, and can say which one it meant.
3080 pub const DATE_FORMAT: &str = "%Y-%m-%d";
3081
3082 /// The wire format a [`FieldKind::DateTime`] value takes: `YYYY-MM-DDTHH:MM`,
3083 /// local, carrying no zone and no seconds.
3084 ///
3085 /// [`DATE_FORMAT`]'s sibling and there for its reason. The absent zone is a
3086 /// property of the value rather than an omission: the moment is not fixed until
3087 /// something outside the description supplies one.
3088 pub const DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M";
3089
3090 impl FieldKind {
3091 /// Whether the value the kind takes is a moment rather than a string.
3092 ///
3093 /// Named once here for the reason [`offers_options`](Self::offers_options)
3094 /// is: two kinds answer yes, and a host that has to parse or format a value
3095 /// needs to ask without spelling the pair out at each renderer. A third
3096 /// temporal kind should land here and nowhere else.
3097 ///
3098 /// The format each one takes is [`DATE_FORMAT`] and [`DATETIME_FORMAT`].
3099 #[must_use]
3100 pub const fn temporal(self) -> bool {
3101 matches!(self, Self::Date | Self::DateTime)
3102 }
3103
3104 /// Whether the field is drawn at all.
3105 #[must_use]
3106 pub const fn visible(self) -> bool {
3107 !matches!(self, Self::Hidden)
3108 }
3109
3110 /// Whether the value must be kept out of logs and diagnostics.
3111 #[must_use]
3112 pub const fn confidential(self) -> bool {
3113 matches!(self, Self::Secret)
3114 }
3115
3116 /// Where the field's own label sits.
3117 ///
3118 /// A checkbox labels itself on the right of the box; everything else takes
3119 /// a label above. Both webview apps already do this and both special-case
3120 /// it inline, which is the tell that it belongs in the description.
3121 ///
3122 /// A [`Radio`](Self::Radio) is not one of them, and the near-miss is worth
3123 /// naming: its *options* each label themselves, but the field still asks a
3124 /// question above them, so the group takes a label like everything else.
3125 #[must_use]
3126 pub const fn labels_itself(self) -> bool {
3127 matches!(self, Self::Checkbox)
3128 }
3129
3130 /// Whether the kind reads [`Field::options`].
3131 ///
3132 /// Two kinds do, so the pair is named once here rather than spelled out at
3133 /// each renderer and again in [`Field::options`]' own doc, where "every
3134 /// kind but `Select`" was true for exactly one release. A third
3135 /// option-taking kind should land here and nowhere else.
3136 #[must_use]
3137 pub const fn offers_options(self) -> bool {
3138 matches!(self, Self::Select | Self::Radio)
3139 }
3140
3141 /// Whether the kind reads [`Field::themes`] and [`Field::follows`].
3142 ///
3143 /// One member answers yes, and it gets a name for
3144 /// [`takes_files`](Self::takes_files)'s reason rather than in spite of
3145 /// being alone: four renderers ask it before they read either member, and
3146 /// a `matches!` per renderer is where the next one goes missing.
3147 ///
3148 /// Deliberately not folded into
3149 /// [`offers_options`](Self::offers_options). A theme picker offers no
3150 /// [`Choice`]es at all, so a renderer walking `options` for it walks an
3151 /// empty slice and draws an empty control.
3152 #[must_use]
3153 pub const fn offers_themes(self) -> bool {
3154 matches!(self, Self::Theme)
3155 }
3156
3157 /// Whether the value runs to more than one line.
3158 ///
3159 /// Named once here for [`temporal`](Self::temporal)'s reason: two kinds
3160 /// answer yes, every renderer has to ask it before it can size anything,
3161 /// and a `matches!` per renderer is the pair drifting apart one member at a
3162 /// time. What a host does with the markdown, if anything, it reads from the
3163 /// kind itself; this is only whether one line is enough.
3164 #[must_use]
3165 pub const fn multiline(self) -> bool {
3166 matches!(self, Self::Textarea | Self::Rich)
3167 }
3168
3169 /// Whether the value is a file the host picks rather than a string typed
3170 /// into a box.
3171 ///
3172 /// One member answers yes, which is [`visible`](Self::visible)'s and
3173 /// [`confidential`](Self::confidential)'s footing rather than a departure
3174 /// from it: the question gets a name because three renderers ask it before
3175 /// they can read [`Field::accept`] or [`Field::multiple`], and a `matches!`
3176 /// per renderer is where a second file-taking kind would go missing.
3177 #[must_use]
3178 pub const fn takes_files(self) -> bool {
3179 matches!(self, Self::File)
3180 }
3181
3182 /// Whether the value is a quantity, so [`Field::unit`] means something.
3183 ///
3184 /// The numeric kinds and nothing else. A date is a quantity in the sense
3185 /// that it is ordered, and it is not one in the sense that matters here:
3186 /// its unit is fixed by the kind, so `Date` carrying `days` would be the
3187 /// description restating what [`kind`](Field::kind) already said.
3188 ///
3189 /// [`takes_files`](Self::takes_files)'s footing, and for its reason: the
3190 /// renderers ask this before they decide where a unit goes, and a
3191 /// `matches!` per renderer is where the next measurable kind goes missing.
3192 ///
3193 /// [`Interval`](Self::Interval) is measurable too: an axis is measured in
3194 /// something and both its ends are in it.
3195 #[must_use]
3196 pub const fn measurable(self) -> bool {
3197 matches!(self, Self::Number | Self::Range | Self::Interval)
3198 }
3199 }
3200
3201 /// A family of media a file can belong to.
3202 ///
3203 /// Three members, because three is what a media type's own first segment offers
3204 /// that a renderer can do anything with. `text` and `application` are families
3205 /// too and neither buys a disclosure — there is no preview of an
3206 /// `application/octet-stream` — so naming them would be a member added for a
3207 /// case nobody has.
3208 ///
3209 /// It is the answer to "which disclosure", not a validation rule.
3210 /// [`Field::accept`] is what a host filters on.
3211 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3212 #[non_exhaustive]
3213 pub enum Family {
3214 /// A still picture.
3215 Image,
3216 /// Sound.
3217 Audio,
3218 /// Moving pictures, with or without sound.
3219 Video,
3220 }
3221
3222 impl Family {
3223 /// The wildcard media type that means the whole family.
3224 ///
3225 /// `image/*` and its two siblings, which is what the measured sites write
3226 /// and what a webview puts in an `accept` attribute. Named here so the three
3227 /// renderers do not each spell the star.
3228 #[must_use]
3229 pub const fn wildcard(self) -> &'static str {
3230 match self {
3231 Self::Image => "image/*",
3232 Self::Audio => "audio/*",
3233 Self::Video => "video/*",
3234 }
3235 }
3236
3237 /// The family a media type's first segment names, if it is one of these.
3238 ///
3239 /// Case-insensitive on the segment, because a media type is
3240 /// case-insensitive and half the tree writes them lowercase by habit rather
3241 /// than by rule.
3242 #[must_use]
3243 pub fn of_type(media_type: &str) -> Option<Self> {
3244 let (top, _) = media_type.split_once('/')?;
3245 if top.eq_ignore_ascii_case("image") {
3246 Some(Self::Image)
3247 } else if top.eq_ignore_ascii_case("audio") {
3248 Some(Self::Audio)
3249 } else if top.eq_ignore_ascii_case("video") {
3250 Some(Self::Video)
3251 } else {
3252 None
3253 }
3254 }
3255 }
3256
3257 /// One entry in a file field's accept list.
3258 ///
3259 /// Three shapes rather than a string, and all three are in the measured sites:
3260 /// the MNW server writes `image/*`, `image/jpeg,image/png,image/webp`,
3261 /// `.zip,.dmg,.exe,.appimage,.deb,.tar.gz,.clap,.vst3` and, in one place,
3262 /// `.csv,text/csv`. A single string would carry all of them and answer nothing
3263 /// about any of them.
3264 ///
3265 /// # Why the list is not just a filter
3266 ///
3267 /// It is read twice. Once to decide what the picker offers, which any of the
3268 /// three shapes serves, and once to decide **which disclosure** the field gets:
3269 /// a preview for a picture, a duration or a waveform for a sound. There is one
3270 /// upload shape and a media upload is that shape with more of it shown, so the
3271 /// accept list is what says which more. [`family`](Self::family) is that
3272 /// question answered once here instead of a media-type parser in each renderer.
3273 ///
3274 /// # A suffix names no family, on purpose
3275 ///
3276 /// `.mp3` is audio in fact, and nothing here says so. A suffix-to-family table
3277 /// in a published crate is a mapping that goes stale, disagrees with the host's
3278 /// own idea of what a file is, and is wrong the first time somebody hands it a
3279 /// container. A call site that wants a picture's preview writes
3280 /// [`Family::Image`] or `image/jpeg`; a call site listing installer suffixes
3281 /// wants no disclosure anyway, which is the measured case.
3282 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3283 #[non_exhaustive]
3284 pub enum Accepted<'a> {
3285 /// Every file of a family: `image/*` and its siblings.
3286 Family(Family),
3287 /// One media type, written the way a media type is written:
3288 /// `image/jpeg`, `text/csv`.
3289 Type(&'a str),
3290 /// One file-name suffix, written with its leading dot: `.zip`, `.tar.gz`.
3291 ///
3292 /// A suffix and not an extension, because `.tar.gz` is a measured site and
3293 /// is two dots.
3294 Suffix(&'a str),
3295 }
3296
3297 impl<'a> Accepted<'a> {
3298 /// The family this entry belongs to, when it names one.
3299 ///
3300 /// [`None`] for a [`Suffix`](Self::Suffix) and for any media type outside
3301 /// the three families, which is the honest answer rather than a missing
3302 /// one: the description did not say.
3303 #[must_use]
3304 pub fn family(self) -> Option<Family> {
3305 match self {
3306 Self::Family(family) => Some(family),
3307 Self::Type(media_type) => Family::of_type(media_type),
3308 Self::Suffix(_) => None,
3309 }
3310 }
3311
3312 /// How a host that wants one string writes this entry.
3313 ///
3314 /// A webview's `accept` attribute takes exactly these spellings, and a
3315 /// terminal listing what it will take reads the same words.
3316 #[must_use]
3317 pub const fn as_str(self) -> &'a str {
3318 match self {
3319 Self::Family(family) => family.wildcard(),
3320 Self::Type(text) | Self::Suffix(text) => text,
3321 }
3322 }
3323 }
3324
3325 /// One option offered by a field [`FieldKind::offers_options`] accepts.
3326 ///
3327 /// Two strings, because the submitted value and the read label are different
3328 /// facts and every renderer that has tried to collapse them has had to
3329 /// un-collapse them later. `makeover-webview` invented this shape writing its
3330 /// form emitter and it is taken here unchanged; moving it down rather than
3331 /// re-deriving it is the point, since the second and third renderers were each
3332 /// going to arrive at a near-miss of it.
3333 /// `#[non_exhaustive]`, which every type here that a renderer matches or builds
3334 /// carries. Without it a new member is a breaking change at every literal site
3335 /// in the tree.
3336 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3337 #[non_exhaustive]
3338 pub struct Choice<'a> {
3339 /// What is submitted.
3340 pub value: &'a str,
3341 /// What is read.
3342 pub label: &'a str,
3343 /// Why it cannot be picked right now, when it cannot.
3344 ///
3345 /// One member rather than an `available: bool` beside a reason, and the
3346 /// conflation is the point: an option greyed out with no explanation is a
3347 /// dead end the user cannot act on, and it is exactly the state the app
3348 /// that found this gap had to patch by hand with a line of prose under the
3349 /// control. Making the reason mandatory means the description cannot say
3350 /// the useless half.
3351 ///
3352 /// The option stays in the list. Dropping it is what an app does today, and
3353 /// it costs the user the knowledge that the thing exists at all —
3354 /// audiofiles' multi-sample mode appears on its own once a second sample is
3355 /// dropped, so a user who never sees it never learns what to drop.
3356 ///
3357 /// **Not [`Field::error`], and not [`Field::hint`].** An error is about the
3358 /// answer and a hint is standing help for the whole question; this is about
3359 /// one option among several, which is the level neither of those reaches.
3360 ///
3361 /// **Not disabled-the-state.** `State::Disabled` is about a whole field
3362 /// refusing to answer. This says the field is live and one of its answers
3363 /// is not available yet, which is a different sentence and the reason the
3364 /// tone rule matters here: the *other* options are still usable.
3365 pub unavailable: Option<&'a str>,
3366 /// The line under the label that says what picking this means.
3367 ///
3368 /// A choice between three plans is a choice nobody can make from three
3369 /// names, and until this existed the description had nowhere to put the
3370 /// sentence that made it makeable. What the corpus did instead is the
3371 /// tell: four of the six measured sites fold it into the label —
3372 /// `<strong>Public</strong>: Anyone can see this repository` in MNW's git
3373 /// settings, the same shape in its project-basics AI tier and its cart's
3374 /// currency conversion, and `Mislabeled (wrong AI tier or category)` in
3375 /// its report modal. The described screens do it too, in miniature: `Every
3376 /// 15 minutes (recommended)`, `Reference samples in place (loose-files
3377 /// mode)`. One fact, six spellings, no member.
3378 ///
3379 /// # Where it goes is the host's, and the rule already exists
3380 ///
3381 /// This is [`unavailable`](Self::unavailable)'s question met a third time
3382 /// and it takes the same answer, which is the strongest evidence one member
3383 /// is right rather than two. A radio group has room and gives the line its
3384 /// own element beside the label. A `<select>`'s option takes no elements,
3385 /// no second line and no title a keyboard reaches, so the line runs into
3386 /// the option's own text — exactly as a precondition does, and as a theme's
3387 /// contrast badge does in brackets. A terminal has rows and puts it on one
3388 /// under the option.
3389 ///
3390 /// # Not a price, and that is a measurement rather than a preference
3391 ///
3392 /// The site that asked for this is MNW's fee calculator, whose tier cards
3393 /// carry a name, a price *and* a description, so a second member for the
3394 /// price was on the table. It loses on the count: the tree's other three
3395 /// priced tier lists — `project.html`, `project_paywall.html`,
3396 /// `index.html` — are not option lists at all. Each card carries its own
3397 /// submit, which makes it a region with a heading, a fact and an act, and
3398 /// it is sayable already. So a price member would have exactly one
3399 /// consumer, and it would mean this crate growing a money type it does not
3400 /// have: [`Unit`] is a time axis, and every amount in the described tree is
3401 /// text.
3402 ///
3403 /// The price therefore leads the line: `$24/mo. 2GB/file, 100GB total.
3404 /// Fits audio, plugins, binaries.` What would reopen it is a **second**
3405 /// priced option list, not a judgement about how that reads.
3406 ///
3407 /// # What it is not
3408 ///
3409 /// Not [`unavailable`](Self::unavailable), which says the option cannot be
3410 /// picked. This says what it means to pick it, and the two are drawn
3411 /// together on an option that carries both: the description that says a
3412 /// tier is out of stock *and* what the tier is has said two things.
3413 ///
3414 /// Not [`Field::hint`], which is standing help for the whole question, and
3415 /// not markup. One line of plain text, for [`Candidate::detail`]'s reason:
3416 /// an option list is a place a renderer lays out, and a description that
3417 /// put a block in one would be handing every host a layout problem for the
3418 /// benefit of one.
3419 pub detail: Option<&'a str>,
3420 }
3421
3422 impl<'a> Choice<'a> {
3423 /// An option whose submitted value is also its label.
3424 #[must_use]
3425 pub const fn plain(value: &'a str) -> Self {
3426 Self::new(value, value)
3427 }
3428
3429 /// An option that submits one string and reads as another.
3430 ///
3431 /// A constructor rather than a literal, which is what `#[non_exhaustive]`
3432 /// costs and buys: outside this crate the struct cannot be built by naming
3433 /// its members, so every call site goes through here and the next member
3434 /// added breaks none of them.
3435 #[must_use]
3436 pub const fn new(value: &'a str, label: &'a str) -> Self {
3437 Self {
3438 value,
3439 label,
3440 unavailable: None,
3441 detail: None,
3442 }
3443 }
3444
3445 /// The same option, not pickable yet, and why.
3446 ///
3447 /// Builder-shaped because the reason is the rare case: 39 of the 40 option
3448 /// sites measured across the tree do not have one.
3449 #[must_use]
3450 pub const fn unless(mut self, reason: &'a str) -> Self {
3451 self.unavailable = Some(reason);
3452 self
3453 }
3454
3455 /// The same option, with the line that says what picking it means.
3456 ///
3457 /// Builder-shaped for [`unless`](Self::unless)'s reason, and it is the
3458 /// commoner of the two: six measured sites want this and one wants a
3459 /// precondition. See [`detail`](Self::detail).
3460 #[must_use]
3461 pub const fn detailing(mut self, detail: &'a str) -> Self {
3462 self.detail = Some(detail);
3463 self
3464 }
3465
3466 /// Whether the option can be picked right now.
3467 ///
3468 /// The predicate a renderer branches on, so that "unavailable" is read as
3469 /// one condition in one place rather than as `unavailable.is_some()` at
3470 /// three renderers, one of which will invert it.
3471 #[must_use]
3472 pub const fn available(&self) -> bool {
3473 self.unavailable.is_none()
3474 }
3475 }
3476
3477 /// One entry in a field's suggestion list.
3478 ///
3479 /// A suggestion-only type rather than a fourth member on [`Choice`], ruled by
3480 /// Max. The two are near-identical and that is the accepted drift risk, so the
3481 /// mitigation is written here: **an
3482 /// option and a candidate are submitted the same way and read differently.**
3483 /// An option is a thing you pick from a known set, and the set is the whole of
3484 /// what there is. A candidate is a thing you are being *oriented* toward out of
3485 /// a set nobody can see, which is why it carries [`detail`](Self::detail) and
3486 /// an option does not.
3487 ///
3488 /// This reverses a position quasi-router stated in its own doc, that a
3489 /// candidate is [`Choice`] "because a candidate is submitted under one string
3490 /// and read under another, which is what an option is". True and not
3491 /// sufficient: how a thing is submitted was never the half that differed.
3492 ///
3493 /// # Why the second string is not folded into the label
3494 ///
3495 /// Because every renderer wants it separately, and the two measured sites both
3496 /// draw it by hand today. The MNW server's tag box computes its context as the
3497 /// parent path -- "the parent path orients an otherwise ambiguous leaf:
3498 /// 'Format' appears under audio, software, writing, and video" -- and a list of
3499 /// four identical rows reading "Format" is not a usable list. In a webview the
3500 /// second string is styled differently, in a terminal it wants the remaining
3501 /// columns rather than a dash, and in neither is it part of what the typed
3502 /// value matches against. `Choice::new(slug, format!("{label} - {context}"))`
3503 /// loses all three of those facts, which is the condition this type exists to
3504 /// end.
3505 ///
3506 /// # No `unavailable`
3507 ///
3508 /// [`Choice::unavailable`] has no counterpart here, and the omission is the
3509 /// implementer's call recorded rather than an oversight. A suggestion that
3510 /// cannot be picked is arguably not a suggestion: an option list is a fixed set
3511 /// a user is owed an explanation about, and a candidate list is whatever a
3512 /// route decided to offer, so a route with nothing to say simply does not offer
3513 /// the row. Add it if a measured site ever wants it.
3514 ///
3515 /// # What it does not carry, and where that lives
3516 ///
3517 /// What *happens* when a candidate is picked. Picking is local by default -- it
3518 /// writes [`value`](Self::value) into the field that owns the list -- and a
3519 /// candidate that does something else says so with an action. An action is not
3520 /// a word this crate has, exactly as [`Field`] here has no `suggests` member,
3521 /// so both live on the router's owned mirror of this type.
3522 ///
3523 /// `#[non_exhaustive]` from birth. Non-negotiable: adding it later means a
3524 /// breaking change at every literal site in the tree.
3525 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3526 #[non_exhaustive]
3527 pub struct Candidate<'a> {
3528 /// What is submitted, and what picking writes into the field.
3529 pub value: &'a str,
3530 /// What is read.
3531 pub label: &'a str,
3532 /// The second line: what orients this candidate among rows that read alike.
3533 ///
3534 /// Optional because a candidate list whose labels are already distinct
3535 /// wants nothing here, and a renderer given [`None`] draws one line rather
3536 /// than an empty second one.
3537 pub detail: Option<&'a str>,
3538 }
3539
3540 impl<'a> Candidate<'a> {
3541 /// A candidate whose submitted value is also its label.
3542 #[must_use]
3543 pub const fn plain(value: &'a str) -> Self {
3544 Self::new(value, value)
3545 }
3546
3547 /// A candidate that submits one string and reads as another.
3548 ///
3549 /// A constructor rather than a literal, which is what `#[non_exhaustive]`
3550 /// costs and buys: outside this crate the struct cannot be built by naming
3551 /// its members, so every call site goes through here and the next member
3552 /// added breaks none of them.
3553 #[must_use]
3554 pub const fn new(value: &'a str, label: &'a str) -> Self {
3555 Self {
3556 value,
3557 label,
3558 detail: None,
3559 }
3560 }
3561
3562 /// The same candidate, with the line that tells it from its neighbours.
3563 #[must_use]
3564 pub const fn detailed(mut self, detail: &'a str) -> Self {
3565 self.detail = Some(detail);
3566 self
3567 }
3568 }
3569
3570 /// Which ambient mode a theme is written for.
3571 ///
3572 /// The vocabulary's own spelling of what `makeover` calls a theme's variant,
3573 /// and the duplication is deliberate rather than an oversight. This crate has
3574 /// no dependencies by charter — it emits nothing, reads nothing and resolves
3575 /// nothing — so it cannot take the crate that owns the file format, and a
3576 /// renderer that must group a picker needs the three groups as values.
3577 ///
3578 /// The two are kept in step by the app that converts between them, which is a
3579 /// three-arm `match` at each adopter and the price of the layering. If a fourth
3580 /// mode is ever authored, this enum and `makeover::Variant` move together.
3581 ///
3582 /// Three, not two: one shipped theme is high contrast, and an app matching on
3583 /// light-or-dark alone files it under the wrong one.
3584 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3585 #[non_exhaustive]
3586 pub enum ThemeVariant {
3587 /// Written for a light ambient mode.
3588 Light,
3589 /// Written for a dark ambient mode.
3590 Dark,
3591 /// Written to be legible before it is pretty.
3592 HighContrast,
3593 }
3594
3595 impl ThemeVariant {
3596 /// The machine spelling, matching the theme file's own `meta.variant`.
3597 ///
3598 /// A data attribute, a stored value, a test assertion. Not a heading: what
3599 /// a group is *called* on screen is [`heading`](Self::heading).
3600 #[must_use]
3601 pub const fn as_str(self) -> &'static str {
3602 match self {
3603 ThemeVariant::Light => "light",
3604 ThemeVariant::Dark => "dark",
3605 ThemeVariant::HighContrast => "high-contrast",
3606 }
3607 }
3608
3609 /// What the group of themes in this variant is called on screen.
3610 ///
3611 /// Here rather than at each renderer, which is the whole argument for the
3612 /// member existing: three renderers picking their own headings is one
3613 /// picker reading three ways, and the spellings below are the ones
3614 /// goingson's shipped picker used before it was described.
3615 #[must_use]
3616 pub const fn heading(self) -> &'static str {
3617 match self {
3618 ThemeVariant::Light => "Light",
3619 ThemeVariant::Dark => "Dark",
3620 ThemeVariant::HighContrast => "High Contrast",
3621 }
3622 }
3623 }
3624
3625 impl std::fmt::Display for ThemeVariant {
3626 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3627 f.write_str(self.as_str())
3628 }
3629 }
3630
3631 /// How legible a theme measured, as a picker reports it.
3632 ///
3633 /// A measurement carried into the description, which is unusual here and is the
3634 /// one case that earns it: the number comes off the theme's resolved colours,
3635 /// so the layer that loaded the theme is the only party that has it, and an app
3636 /// re-deriving it would be parsing every theme file a second time to learn what
3637 /// was already known. What a renderer does with it is a badge beside the name.
3638 ///
3639 /// Ordered worst-first, matching `makeover::ContrastTier`, so the two sort the
3640 /// same way and an adopter's `match` cannot invert an ordering by accident.
3641 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3642 #[non_exhaustive]
3643 pub enum Contrast {
3644 /// Muted text below the 3:1 floor for large text and UI parts.
3645 Low,
3646 /// Muted text clears 3:1 but not the 4.5:1 bar for normal text.
3647 Standard,
3648 /// Muted text meets WCAG AA on every panel ground.
3649 High,
3650 }
3651
3652 impl Contrast {
3653 /// The machine spelling, for a data attribute or a test.
3654 #[must_use]
3655 pub const fn as_str(self) -> &'static str {
3656 match self {
3657 Contrast::Low => "low",
3658 Contrast::Standard => "standard",
3659 Contrast::High => "high",
3660 }
3661 }
3662
3663 /// The short mark shown beside a theme's name.
3664 ///
3665 /// One spelling for the tree, for [`ThemeVariant::heading`]'s reason. These
3666 /// are the marks audiofiles shipped before its picker was described, which
3667 /// is the only implementation that ever drew them.
3668 ///
3669 /// [`Standard`](Self::Standard) is not the absence of a mark: a reader
3670 /// scanning a column of badges learns more from three marks than from two
3671 /// and a gap, and "OK" is the honest reading of a theme that clears the UI
3672 /// floor and misses the text one.
3673 #[must_use]
3674 pub const fn badge(self) -> &'static str {
3675 match self {
3676 Contrast::Low => "low",
3677 Contrast::Standard => "OK",
3678 Contrast::High => "AA",
3679 }
3680 }
3681 }
3682
3683 impl std::fmt::Display for Contrast {
3684 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3685 f.write_str(self.as_str())
3686 }
3687 }
3688
3689 /// One theme, as a picker offers it.
3690 ///
3691 /// Four facts where a [`Choice`] has two, and the two extra ones are why this
3692 /// is its own type rather than options with the variant folded into the label.
3693 /// Both are facts the theme layer resolved and neither survives being written
3694 /// into a string: a group is structure and a badge is a second column.
3695 ///
3696 /// # No `unavailable`
3697 ///
3698 /// [`Choice::unavailable`]'s counterpart is absent for its own sibling's
3699 /// reason. A theme that is installed can be picked, and a theme that is not
3700 /// installed is not in the list. There is no third state for a reason to
3701 /// explain.
3702 ///
3703 /// `#[non_exhaustive]` from birth, so a new member costs no call site.
3704 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3705 #[non_exhaustive]
3706 pub struct ThemeChoice<'a> {
3707 /// What is submitted, and what the app stores.
3708 pub id: &'a str,
3709 /// What is read.
3710 pub name: &'a str,
3711 /// Which group it belongs to.
3712 pub variant: ThemeVariant,
3713 /// How legible its muted text measured.
3714 pub contrast: Contrast,
3715 }
3716
3717 impl<'a> ThemeChoice<'a> {
3718 /// A theme, with everything a picker needs to place and mark it.
3719 ///
3720 /// Every fact is an argument and none is a builder, which is the opposite
3721 /// of [`Choice`]'s arrangement and is deliberate: a theme missing its
3722 /// variant has no group to sit in and a theme missing its tier has no badge
3723 /// to draw, so both are the control rather than embellishments on it. The
3724 /// same reasoning [`Field::range`] applies to its bounds.
3725 #[must_use]
3726 pub const fn new(
3727 id: &'a str,
3728 name: &'a str,
3729 variant: ThemeVariant,
3730 contrast: Contrast,
3731 ) -> Self {
3732 Self {
3733 id,
3734 name,
3735 variant,
3736 contrast,
3737 }
3738 }
3739 }
3740
3741 /// One field of a form.
3742 ///
3743 /// Borrowed rather than owned: a description is built, read once by a renderer,
3744 /// and dropped. Nothing here outlives the screen it describes.
3745 ///
3746 /// # What it carries, and what it does not
3747 ///
3748 /// Stated here so the next renderer does not re-ask, which is what the first
3749 /// two both did. It carries everything a renderer needs to *draw* the field:
3750 /// its kind, what it is called, what it is asked for, its standing help, what
3751 /// is wrong with it now, whether it is compulsory, whether it hides behind a
3752 /// disclosure, its ghost text, and the options it offers.
3753 ///
3754 /// It does not carry the **current value**, and it is not going to. That is the
3755 /// one thing here that is genuinely renderer state: a webview reads it back out
3756 /// of the DOM, an immediate-mode renderer holds a `&mut` to the app's own field
3757 /// and writes through it, and a terminal keeps an edit buffer. A description
3758 /// that carried the value would have to carry a way to write it back, at which
3759 /// point it is a form model and no longer a description.
3760 ///
3761 /// **Constraints** are here and enforcement is not, which is one line rather
3762 /// than two. [`required`], [`max_length`], [`min`] and [`max`] are facts about
3763 /// the *question*, so a renderer can emit its host's idiom for each — an HTML
3764 /// attribute, a marked label, a clamped spinner — and the platform helps the
3765 /// user before anything is submitted. Deciding that a value is wrong stays with
3766 /// whoever validated, and [`error`] is that decision arriving back.
3767 ///
3768 /// The set stops before `pattern`, and stops there on both tests at once. A
3769 /// regex has an honest answer in a webview and none anywhere else: egui would
3770 /// have to run it per keystroke and decide what a half-typed value means,
3771 /// which is enforcement wearing description's clothes. And it is one site in
3772 /// goingson and none in Balanced Breakfast, against 8 and 1 for `maxlength`.
3773 ///
3774 /// [`error`]: Field::error
3775 /// [`required`]: Field::required
3776 /// [`max_length`]: Field::max_length
3777 /// [`min`]: Field::min
3778 /// [`max`]: Field::max
3779 /// How a slider's position becomes its value, and how finely it moves.
3780 ///
3781 /// **The data of a slider is a fraction and a function taking numbers to
3782 /// numbers.** Stated by Max, and it is what [`min`](Field::min) and
3783 /// [`max`](Field::max) are not: they were never the control's extent.
3784 /// A slider's extent is always 0 to 1 — a thumb at 40% of a track — and the
3785 /// bounds are `f(0)` and `f(1)`. Linear is the constant-slope case, which is
3786 /// exactly why nobody noticed the function was there: when `f` is
3787 /// `min + t * (max - min)` the extent and the bounds coincide numerically and
3788 /// the mapping is invisible.
3789 ///
3790 /// So this is not a scale flag bolted onto a range. Every range described
3791 /// before it had a mapping, and four renderers each hard-coded the same one.
3792 ///
3793 /// # Why a closed family and not a function
3794 ///
3795 /// `fn(f64) -> f64` is the literal reading and it does not survive the
3796 /// description boundary. A fn pointer cannot be emitted into a browser, and it
3797 /// cannot be compared or hashed in a way that means anything, which this struct
3798 /// needs. A named family is the same semantics with arbitrary closures given
3799 /// up, and nothing measured wants one: the tree has a single non-linear shape
3800 /// across five controls and no second shape at all.
3801 ///
3802 /// # Why the step is here
3803 ///
3804 /// Max, in the same breath: if the family is prescriptive anyway, the step
3805 /// spacing belongs in it. On a slider the granularity and the mapping are one
3806 /// decision — a curve chosen without saying how finely it moves is half an
3807 /// answer — and holding them apart is what let a 0-to-1 threshold ship as a
3808 /// two-position control, since the host default of 1 was applied to a mapping
3809 /// nobody had named. It also un-overloads [`Field::step`], which stays as it
3810 /// was for a *typed* value, where there is no mapping and the granularity is a
3811 /// plain fact about the number.
3812 ///
3813 /// A future curve carrying a fact of its own — an exponent, an inflection —
3814 /// puts it in its own variant rather than on the struct, which is the second
3815 /// reason this shape is right.
3816 ///
3817 /// **The step is in the value's own units under every curve.** What a curve
3818 /// changes is the mapping, not the units the granularity is measured in: a step
3819 /// of `0.001` on an envelope time is three decimals whether the track is
3820 /// logarithmic or not, and a renderer that reads the step for display precision
3821 /// keeps reading it the same way.
3822 #[non_exhaustive]
3823 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3824 pub enum Curve<'a> {
3825 /// Constant slope: `f(t) = min + t * (max - min)`.
3826 ///
3827 /// What every described range meant before this enum existed, and the
3828 /// default, so a site that says nothing is correct unchanged.
3829 Linear {
3830 /// The granularity, in the value's own units. `None` is the host's own.
3831 step: Option<&'a str>,
3832 },
3833 /// Constant ratio: `f(t) = min * (max / min).powf(t)`.
3834 ///
3835 /// The mapping for a question whose extent spans orders of magnitude and
3836 /// whose interesting half is the small end. audiofiles' envelope times run
3837 /// 0.001 to 5 seconds, where a 5 ms attack and a 50 ms attack are audibly
3838 /// different instruments and a linear track puts both inside its first one
3839 /// percent.
3840 ///
3841 /// # It needs positive bounds
3842 ///
3843 /// A constant ratio is undefined across zero, so this asks for `min > 0`.
3844 /// A range that does not have that is mapped [`Linear`](Self::Linear)ly
3845 /// instead — see [`value_at`](Self::value_at). Stated rather than enforced,
3846 /// the way every other constraint in this crate is, and it is not a
3847 /// hypothetical: an envelope's sustain is a 0-to-1 level and is linear for
3848 /// this reason rather than by oversight.
3849 Logarithmic {
3850 /// The granularity, in the value's own units. `None` is the host's own.
3851 step: Option<&'a str>,
3852 },
3853 }
3854
3855 impl Default for Curve<'_> {
3856 fn default() -> Self {
3857 Self::Linear { step: None }
3858 }
3859 }
3860
3861 impl<'a> Curve<'a> {
3862 /// The granularity this curve moves in, whichever curve it is.
3863 ///
3864 /// Every variant carries one, so reading it does not need a match at each
3865 /// of the four renderers.
3866 #[must_use]
3867 pub const fn step(self) -> Option<&'a str> {
3868 // No wildcard: `#[non_exhaustive]` binds downstream, not here, so a
3869 // curve added later has to answer this rather than fall through to a
3870 // granularity nobody chose.
3871 match self {
3872 Self::Linear { step } | Self::Logarithmic { step } => step,
3873 }
3874 }
3875
3876 /// Whether this curve maps as a constant ratio *given these bounds*.
3877 ///
3878 /// The bounds are the argument because [`Logarithmic`](Self::Logarithmic)
3879 /// is a request rather than a guarantee: it needs `0 < min < max`, and a
3880 /// range that does not have that is drawn linearly. A renderer asks this
3881 /// instead of matching on the variant, so the fallback is decided in one
3882 /// place rather than four.
3883 #[must_use]
3884 pub fn is_ratio(self, min: f64, max: f64) -> bool {
3885 matches!(self, Self::Logarithmic { .. }) && min > 0.0 && max > min
3886 }
3887
3888 /// The value at a position along the track, where `position` is 0 to 1.
3889 ///
3890 /// `f`. The whole point of the type, and it lives here rather than in each
3891 /// renderer so that a terminal's bar, an egui slider and a browser's input
3892 /// cannot disagree about where a value sits.
3893 ///
3894 /// A position outside 0 to 1 is clamped, and bounds that are equal or
3895 /// inverted give `min` back: a track with no extent has one value on it.
3896 #[must_use]
3897 pub fn value_at(self, position: f64, min: f64, max: f64) -> f64 {
3898 let position = position.clamp(0.0, 1.0);
3899 // NaN named rather than fallen through: `max <= min` is false for a NaN
3900 // bound, so without it a track with no numbers on it would be mapped as
3901 // if it had two.
3902 if max <= min || min.is_nan() || max.is_nan() {
3903 return min;
3904 }
3905 if self.is_ratio(min, max) {
3906 min * (max / min).powf(position)
3907 } else {
3908 position.mul_add(max - min, min)
3909 }
3910 }
3911
3912 /// The position a value sits at, where the answer is 0 to 1.
3913 ///
3914 /// `f` inverted, which is what a renderer needs to *draw* a value it was
3915 /// handed. Same clamping and the same degenerate answer as
3916 /// [`value_at`](Self::value_at).
3917 #[must_use]
3918 pub fn position_of(self, value: f64, min: f64, max: f64) -> f64 {
3919 if max <= min || min.is_nan() || max.is_nan() {
3920 return 0.0;
3921 }
3922 let value = value.clamp(min, max);
3923 let position = if self.is_ratio(min, max) {
3924 (value / min).ln() / (max / min).ln()
3925 } else {
3926 (value - min) / (max - min)
3927 };
3928 position.clamp(0.0, 1.0)
3929 }
3930 }
3931
3932 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3933 pub struct Field<'a> {
3934 /// What kind of value it takes.
3935 pub kind: FieldKind,
3936 /// The name the value is submitted under.
3937 ///
3938 /// The *lower* end's name for a [`FieldKind::Interval`], whose upper end is
3939 /// [`upper_name`](Self::upper_name). Every other kind submits one value and
3940 /// this is the whole of it.
3941 pub name: &'a str,
3942 /// The name a [`FieldKind::Interval`]'s upper end is submitted under.
3943 ///
3944 /// [`None`] for every other kind, and sayable-and-ignored there the way
3945 /// [`options`](Self::options) is on a kind that offers none.
3946 ///
3947 /// Stated rather than derived from [`name`](Self::name), and
3948 /// [`FieldKind::Interval`] carries the measurement that decided it: the two
3949 /// sites in this tree disagree about affix order, so a derived rule would
3950 /// rename one of them. Which member a name sits in is also what says which
3951 /// end it is, so nothing separate carries the direction.
3952 ///
3953 /// An interval missing it is an interval with one end that can be submitted,
3954 /// which is a description a renderer may draw honestly and no better than
3955 /// that. [`Field::interval`] is what makes forgetting it unsayable, on the
3956 /// same footing as [`Field::range`] and its bounds.
3957 pub upper_name: Option<&'a str>,
3958 /// What the user is asked for.
3959 pub label: &'a str,
3960 /// Standing help, shown whether or not anything is wrong.
3961 pub hint: Option<&'a str>,
3962 /// What is currently wrong with the value.
3963 pub error: Option<&'a str>,
3964 /// A consequence of the answer the user has given, carrying its own tone.
3965 ///
3966 /// The third message channel, between [`hint`](Self::hint) and
3967 /// [`error`](Self::error) and overlapping neither. A hint is standing help
3968 /// that does not depend on the value; an error says the value is not
3969 /// acceptable. A note is the case in the middle: the value is perfectly
3970 /// acceptable and choosing it costs something the user should know about.
3971 ///
3972 /// The first consumer is audiofiles' export Format field, where choosing
3973 /// WAV or AIFF over Original re-encodes and silently drops embedded BWF,
3974 /// iXML, loop points, cue markers and ID3. That is not a validation
3975 /// failure and it is not standing help — it is true of one answer to one
3976 /// question — and it was hand-drawn in the app's own draw callback for
3977 /// want of anywhere to say it.
3978 ///
3979 /// The tone is carried rather than fixed at [`Tone::Warning`] because the
3980 /// channel is not only for warnings: the same slot says "this is the
3981 /// recommended one" ([`Tone::Success`]) and "this is what that setting
3982 /// implies" ([`Tone::Info`]). A renderer gets the announcement behaviour
3983 /// off the tone for free — makeover-webview emits `data-tone` and treats
3984 /// Warning and Danger as assertive for `aria-live`.
3985 ///
3986 /// It does **not** make the field invalid. [`invalid`](Self::invalid) stays
3987 /// `error.is_some()`, so a note never marks the group as a problem.
3988 ///
3989 /// # Precedence, for a renderer with room for one
3990 ///
3991 /// Error, then note, then hint. A renderer that shows every message shows
3992 /// them in that order too. makeover-tui is the one with room for exactly
3993 /// one line, and it is why the order is decided here rather than three
3994 /// times: what is wrong outranks what it costs, which outranks how it
3995 /// works.
3996 pub note: Option<(Tone, &'a str)>,
3997 /// Ghost text shown while the field is empty.
3998 ///
3999 /// User-facing text, and it sits with `label` and `hint` rather than with
4000 /// the value because it is a property of the *question* and not of the
4001 /// answer.
4002 ///
4003 /// Not a substitute for a label. A field labelled only by its placeholder
4004 /// loses its label the moment anything is typed, and no renderer here can
4005 /// make that not happen, so the description keeps both.
4006 pub placeholder: Option<&'a str>,
4007 /// The options offered, in the order they are offered.
4008 ///
4009 /// Empty for every kind [`FieldKind::offers_options`] rejects. A field
4010 /// described with no options is sayable on purpose: it is what an app with
4011 /// an unfinished-loading option list actually has, and a renderer showing
4012 /// an empty control says so on screen rather than in a log.
4013 ///
4014 /// Which option is *current* is not here. That is the value, and the value
4015 /// is renderer state.
4016 pub options: &'a [Choice<'a>],
4017 /// The themes offered, in the order they are offered.
4018 ///
4019 /// Empty for every kind [`FieldKind::offers_themes`] rejects, and sayable
4020 /// as empty for the one that accepts it: an app whose theme directories
4021 /// hold nothing has a picker offering only [`follows`](Self::follows),
4022 /// which is a true description of that machine.
4023 ///
4024 /// **The order is the grouping.** Entries arrive sorted by
4025 /// [`ThemeVariant`] and then by [`Contrast`] within each variant, so a
4026 /// renderer that draws headings walks the run of one variant and a renderer
4027 /// that cannot still gets the useful order. Handing back groups would force
4028 /// the second renderer to flatten what the first wanted.
4029 ///
4030 /// Nothing here sorts. The description carries the order it was given, and
4031 /// the sort belongs with whoever measured the tiers — `makeover::theme_options`
4032 /// is what produces it, and re-sorting here would be this crate deciding a
4033 /// question it cannot see the inputs to.
4034 ///
4035 /// Which theme is *current* is not here. That is the value, and the value
4036 /// is renderer state, exactly as it is for [`options`](Self::options).
4037 pub themes: &'a [ThemeChoice<'a>],
4038 /// The entry that follows the ambient mode instead of naming a theme.
4039 ///
4040 /// [`None`] for a picker that does not offer one, which is a real answer:
4041 /// an app whose host has no ambient mode to follow should not offer a row
4042 /// that does nothing.
4043 ///
4044 /// A [`Choice`] rather than a bare label, because the *value* is the app's.
4045 /// Every store in the family spells it `system` today and none of them is
4046 /// obliged to; a description that hardcoded the spelling would be this
4047 /// crate holding a fact about somebody else's config table.
4048 ///
4049 /// It is not a [`ThemeChoice`] with an absent variant. Following is a
4050 /// standing instruction that resolves differently as the desktop flips, and
4051 /// a theme id is an answer that does not — which is the distinction
4052 /// `makeover::ThemeSelection` exists to hold, carried here rather than
4053 /// blurred.
4054 pub follows: Option<Choice<'a>>,
4055 /// What a file field takes, in the order a host offering the list shows it.
4056 ///
4057 /// Empty for every kind [`FieldKind::takes_files`] rejects, and empty is
4058 /// also a real answer for one that accepts it: a field that takes any file
4059 /// says so by listing nothing, which is what an `<input type="file">` with
4060 /// no `accept` does and what most of the measured sites are.
4061 ///
4062 /// It is a filter and it is the disclosure cue, and [`Accepted`]'s doc
4063 /// carries which reading is which. Nothing here validates: a host may hand
4064 /// back a file the list does not cover, exactly as a browser does when the
4065 /// user switches the picker to "All Files", and deciding a value is wrong
4066 /// stays with whoever validated.
4067 pub accept: &'a [Accepted<'a>],
4068 /// Whether more than one file may be picked at once.
4069 ///
4070 /// Only [`FieldKind::takes_files`] reads it. A multi-valued answer to any
4071 /// other question is a different shape — a set of options, a repeated
4072 /// group — and neither is this flag with a different kind beside it.
4073 ///
4074 /// False is the common case: 4 of the MNW server's 16 file inputs carry it.
4075 pub multiple: bool,
4076 /// Whether the form refuses to submit without it.
4077 pub required: bool,
4078 /// The longest the value may be, in characters.
4079 pub max_length: Option<u32>,
4080 /// The lowest value accepted, as the host would write it.
4081 ///
4082 /// Text rather than a number, because the bound is only a number for some
4083 /// of the kinds that take one. goingson's own sites are `min="1"` on a
4084 /// duration and `min="2026-08-09T14:30"` on a datetime, and a numeric member
4085 /// could say the first and not the second. The [`kind`](Self::kind) already
4086 /// says how to read it, the same way it does for the value.
4087 pub min: Option<&'a str>,
4088 /// The highest value accepted, as the host would write it. See
4089 /// [`min`](Self::min).
4090 pub max: Option<&'a str>,
4091 /// The granularity the value moves in, as the host would write it.
4092 ///
4093 /// Text for [`min`](Self::min)'s reason, and it earns it twice over: the
4094 /// step of a date is a day and the step of a threshold is 0.01, and a
4095 /// numeric member could say one of them.
4096 ///
4097 /// Absent means the host's own granularity, which is the honest default
4098 /// rather than a missing value: a webview's `<input>` steps by 1 unless told
4099 /// otherwise, and that is the browser's rule and not this crate's to
4100 /// restate.
4101 ///
4102 /// # It is the granularity of a *typed* value
4103 ///
4104 /// [`FieldKind::Range`] reads its own from [`curve`](Self::curve) and
4105 /// ignores this. On a slider the granularity and the mapping are one
4106 /// decision, and on a typed number there is no mapping to decide with. See
4107 /// [`Curve`], "Why the step is here".
4108 pub step: Option<&'a str>,
4109 /// How a slider's position becomes its value, and how finely it moves.
4110 ///
4111 /// [`FieldKind::Range`]'s, and nothing else reads it: a typed number has a
4112 /// granularity but no mapping, and takes [`step`](Self::step) instead.
4113 ///
4114 /// Defaults to [`Curve::Linear`] with no step, which is what an
4115 /// undescribed range means.
4116 pub curve: Curve<'a>,
4117 /// What the number is measured in: `s`, `ms`, `dB`, `GiB`.
4118 ///
4119 /// A fact about the value, not part of the question's name, and that
4120 /// distinction is the whole reason it is a member. The two readings come
4121 /// apart the moment anything reads a field back rather than drawing it: a
4122 /// [`max`](Self::max) of `-96` and a bound of `-96 dBFS` are the same number
4123 /// and not the same answer, and under the convention this replaces the unit
4124 /// could only be recovered by parsing it back out of a label.
4125 ///
4126 /// # Where a renderer draws it
4127 ///
4128 /// Beside the value, wherever that host puts a value. Not in the label: a
4129 /// label is the sentence above the control, so unit-in-label reads the same
4130 /// on every host and is wrong on any host with somewhere better. egui puts
4131 /// it inside
4132 /// the slider where the readout already is, a terminal appends it to the
4133 /// value in the edit line, a webview sets it adjacent to the input.
4134 ///
4135 /// # Which kinds read it
4136 ///
4137 /// [`FieldKind::measurable`] answers, and it is
4138 /// [`takes_files`](FieldKind::takes_files)'s footing: three renderers ask
4139 /// before they can decide whether to draw this, and a `matches!` per
4140 /// renderer is where the next measurable kind goes missing. A unit on a kind
4141 /// that rejects it is sayable and ignored, the same way
4142 /// [`options`](Self::options) is on a kind that offers none.
4143 ///
4144 /// # Why a string
4145 ///
4146 /// The measured sites are `GiB`, `dBFS`, `s` and `ms`. An enum would have to
4147 /// grow a member for every unit any consumer ever wants, and this crate does
4148 /// not know them; it knows that a number has one.
4149 ///
4150 /// Written as the symbol alone, with no brackets and no leading space. The
4151 /// spacing is the renderer's, because a slider's readout and a sentence want
4152 /// different answers.
4153 pub unit: Option<&'a str>,
4154 /// Whether the field lives behind a "more options" disclosure.
4155 pub extended: bool,
4156 /// Whether this local wall-clock value is submitted as an absolute instant.
4157 ///
4158 /// [`FieldKind::DateTime`] asks for a time the way a person says one --
4159 /// "the 14th at half past two" -- and that names a different moment in
4160 /// Denver than it does in Berlin. A route that stores an instant needs the
4161 /// moment, so somebody has to convert. This member says the description
4162 /// wants that conversion; it does not say how.
4163 ///
4164 /// # The conversion belongs to the renderer
4165 ///
4166 /// Because the renderer is the only party that knows what "your computer's
4167 /// time zone" means for its host. A browser has one and the user is sitting
4168 /// in it; a TUI reads the host clock; an egui app reads the same clock a
4169 /// different way. Nothing above the renderer can answer it, and the
4170 /// alternatives all try: a hidden IANA-zone field needs a host capability
4171 /// for reading the zone that three hosts answer differently, plus a kind
4172 /// that does not exist, plus a wire-contract change; a timezone on the
4173 /// user's profile is a product decision wearing a bug's clothes. Say it
4174 /// here, and the next reader does not propose them again.
4175 ///
4176 /// # What a renderer does
4177 ///
4178 /// Draws the same control it always did -- the flag changes what is
4179 /// *submitted*, not what is shown -- and converts the local value to an
4180 /// absolute instant on the way out. A renderer that cannot convert submits
4181 /// the local value unchanged, which is what every renderer did before this
4182 /// existed.
4183 ///
4184 /// No wire contract moves when a site adopts it: the route was already
4185 /// receiving an instant. What changes is who computed it.
4186 ///
4187 /// # Which kinds read it
4188 ///
4189 /// [`FieldKind::DateTime`]'s. `Date` and `Time` are each half a moment and
4190 /// cannot name one on their own, so the flag is sayable and ignored there,
4191 /// the way [`options`](Self::options) is on a kind that offers none.
4192 pub as_instant: bool,
4193 }
4194
4195 impl<'a> Field<'a> {
4196 /// A plain required-nothing field of the given kind.
4197 #[must_use]
4198 pub const fn new(kind: FieldKind, name: &'a str, label: &'a str) -> Self {
4199 Self {
4200 kind,
4201 name,
4202 upper_name: None,
4203 label,
4204 hint: None,
4205 error: None,
4206 note: None,
4207 placeholder: None,
4208 options: &[],
4209 themes: &[],
4210 follows: None,
4211 accept: &[],
4212 multiple: false,
4213 required: false,
4214 max_length: None,
4215 min: None,
4216 max: None,
4217 step: None,
4218 curve: Curve::Linear { step: None },
4219 unit: None,
4220 extended: false,
4221 as_instant: false,
4222 }
4223 }
4224
4225 /// A bounded number the user drags across its whole extent.
4226 ///
4227 /// The third under-described kind, and it gets a constructor for
4228 /// [`select`](Self::select)'s reason: a range is the one kind whose bounds
4229 /// are not a rule but the control itself, so a call site that forgot them
4230 /// has a slider with nothing to slide across. Taking them as arguments is
4231 /// what makes that unsayable.
4232 ///
4233 /// The granularity stays a field rather than a fourth argument, and it is
4234 /// [`curve`](Self::curve)'s: it is genuinely optional, since the host's own
4235 /// is a real answer, and the two bounds are not.
4236 #[must_use]
4237 pub const fn range(name: &'a str, label: &'a str, min: &'a str, max: &'a str) -> Self {
4238 Self {
4239 min: Some(min),
4240 max: Some(max),
4241 ..Self::new(FieldKind::Range, name, label)
4242 }
4243 }
4244
4245 /// One question with two ends, taking the name each end submits under.
4246 ///
4247 /// A constructor for [`range`](Self::range)'s reason inverted: a range's
4248 /// bounds are what a call site cannot forget, and an interval's second name
4249 /// is. An interval built through [`new`](Self::new) has an upper end with
4250 /// nowhere to be submitted, and nothing downstream can invent one, so taking
4251 /// it as an argument is what makes that unsayable.
4252 ///
4253 /// The extent, the granularity and the unit stay members. They describe the
4254 /// axis rather than either end and they are genuinely optional, which is
4255 /// [`FieldKind::Number`]'s arrangement and the one an interval takes.
4256 #[must_use]
4257 pub const fn interval(name: &'a str, upper_name: &'a str, label: &'a str) -> Self {
4258 Self {
4259 upper_name: Some(upper_name),
4260 ..Self::new(FieldKind::Interval, name, label)
4261 }
4262 }
4263
4264 /// A file field, taking the given accept list.
4265 ///
4266 /// The fourth under-described kind and it gets a constructor for
4267 /// [`range`](Self::range)'s reason rather than [`select`](Self::select)'s:
4268 /// a file field with no accept list is not broken, it is a field that takes
4269 /// anything, and the hazard is the opposite one. A call site that meant to
4270 /// restrict and forgot has a picker offering every file on the machine and
4271 /// a server refusing the upload afterwards, which is the failure the list
4272 /// exists to move forward. Taking it as an argument is what makes an
4273 /// accidental omission a deliberate `&[]`.
4274 ///
4275 /// [`multiple`](Self::multiple) stays a field. One file is the common case
4276 /// and the honest default; several is the thing worth saying.
4277 #[must_use]
4278 pub const fn upload(name: &'a str, label: &'a str, accept: &'a [Accepted<'a>]) -> Self {
4279 Self {
4280 accept,
4281 ..Self::new(FieldKind::File, name, label)
4282 }
4283 }
4284
4285 /// A select offering the given options.
4286 ///
4287 /// One of the two kinds under-described by [`Field::new`], so it gets a
4288 /// constructor rather than leaving every call site to remember that a
4289 /// select with an empty `options` renders as an empty select.
4290 #[must_use]
4291 pub const fn select(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
4292 Self::offering(FieldKind::Select, name, label, options)
4293 }
4294
4295 /// A radio group offering the given options.
4296 ///
4297 /// The other. Same hazard as [`select`](Self::select) and a worse one: a
4298 /// radio group with no options draws nothing at all, so a call site that
4299 /// forgot them has an empty rectangle rather than a visibly empty control.
4300 #[must_use]
4301 pub const fn radio(name: &'a str, label: &'a str, options: &'a [Choice<'a>]) -> Self {
4302 Self::offering(FieldKind::Radio, name, label, options)
4303 }
4304
4305 /// A theme picker over the themes the host resolved.
4306 ///
4307 /// A constructor for [`select`](Self::select)'s reason and one of its own.
4308 /// The shared reason: a theme picker built through [`new`](Self::new) has
4309 /// an empty [`themes`](Self::themes) list and draws an empty control. Its
4310 /// own: the list is the *only* thing this kind takes that a call site
4311 /// cannot get wrong by omission and can get wrong by substitution, since
4312 /// [`options`](Self::options) is right there and reads as if it would work.
4313 ///
4314 /// [`following`](Self::following) is the builder rather than a fourth
4315 /// argument, because a picker with no follow-the-system row is a real
4316 /// picker and every renderer draws it honestly.
4317 #[must_use]
4318 pub const fn theme(name: &'a str, label: &'a str, themes: &'a [ThemeChoice<'a>]) -> Self {
4319 Self {
4320 themes,
4321 ..Self::new(FieldKind::Theme, name, label)
4322 }
4323 }
4324
4325 /// The same picker, offering a row that tracks the ambient mode.
4326 ///
4327 /// The [`Choice`] carries the value the app's own store spells it with.
4328 #[must_use]
4329 pub const fn following(mut self, follow: Choice<'a>) -> Self {
4330 self.follows = Some(follow);
4331 self
4332 }
4333
4334 /// The shared body of the two constructors that take options.
4335 ///
4336 /// Private, and keyed on the kind rather than exposed, because the two
4337 /// public names are the point: a call site says which question it is
4338 /// asking, not which flag it is setting.
4339 const fn offering(
4340 kind: FieldKind,
4341 name: &'a str,
4342 label: &'a str,
4343 options: &'a [Choice<'a>],
4344 ) -> Self {
4345 Self {
4346 options,
4347 ..Self::new(kind, name, label)
4348 }
4349 }
4350
4351 /// Whether the field is currently reporting a problem.
4352 ///
4353 /// Read this rather than testing `error.is_some()` at each renderer: the
4354 /// error state has to mark the field's whole group and not only the
4355 /// message, because a renderer with no descendant selectors (egui, a
4356 /// terminal) cannot find the group from the message. goingson already marks
4357 /// the group and Balanced Breakfast does not, so goingson's shape is the
4358 /// one taken here.
4359 ///
4360 /// [`note`](Self::note) is deliberately not consulted. A note says the
4361 /// answer costs something, not that it is unacceptable, and a field the
4362 /// user may submit as it stands is not invalid.
4363 #[must_use]
4364 pub const fn invalid(&self) -> bool {
4365 self.error.is_some()
4366 }
4367
4368 /// Whether the field carries both ends of its extent.
4369 ///
4370 /// Only [`FieldKind::Range`] owes them, and it owes them absolutely: a
4371 /// slider with one end missing has no extent to draw. Named here rather
4372 /// than left to each renderer to test `min.is_some() && max.is_some()`,
4373 /// which is three renderers arriving at the same condition and one of them
4374 /// getting it wrong, and named as a question about the *field* rather than
4375 /// about the kind because the kind cannot see the bounds.
4376 ///
4377 /// It is a check and not a guarantee. Nothing here refuses to build an
4378 /// unbounded range — [`Field::range`] is what makes the bounded one easy —
4379 /// so a renderer asks this and falls back to whatever its host does
4380 /// honestly with a number.
4381 #[must_use]
4382 pub const fn bounded(&self) -> bool {
4383 self.min.is_some() && self.max.is_some()
4384 }
4385
4386 /// Whether anything in [`accept`](Self::accept) names a media family.
4387 ///
4388 /// The question a renderer asks before it decides to keep room for a
4389 /// preview, and it is deliberately the *whole list* rather than one entry:
4390 /// the media dropzone this was measured against takes `image/*,video/*`, so
4391 /// there is no single family to return and there is still a disclosure to
4392 /// offer. Which one it turns out to be is known once a file is picked, which
4393 /// is renderer-side and after the description is gone.
4394 ///
4395 /// False for an empty list, for a list of suffixes, and for `text/csv`. A
4396 /// renderer that wants the family of a particular entry reads
4397 /// [`Accepted::family`].
4398 #[must_use]
4399 pub fn accepts_media(&self) -> bool {
4400 self.accept.iter().any(|one| one.family().is_some())
4401 }
4402 }
4403
4404 /// How much room a placement asks for.
4405 ///
4406 /// A column says it, and so does a [`Field`]. An intent, so the actual floor
4407 /// stays with `makeover-geometry`. goingson's task table spells these as
4408 /// `minmax(200px, 1fr)`, `140px` and content-sized; only the first three words
4409 /// of that survive deferral.
4410 /// `#[non_exhaustive]`, for the reason [`Fill`] and [`FieldKind`] are: a
4411 /// renderer matches on this and a vocabulary that grows must not break every
4412 /// renderer when it does.
4413 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4414 #[non_exhaustive]
4415 pub enum Width {
4416 /// Takes what it needs and no more.
4417 Content,
4418 /// A fixed share, the same at every width.
4419 Fixed,
4420 /// Absorbs whatever is left over.
4421 ///
4422 /// **Several fills divide what is left equally.** Stated because it would
4423 /// otherwise be undefined and each renderer would invent something, and
4424 /// stated this way because equal division is the only sharing rule that
4425 /// answers to "Any width, one answer" without a tiebreak: allocating in
4426 /// declaration order makes the result depend on the order the description
4427 /// was written in, which is a fact about the source file and not about the
4428 /// screen. It documents what both renderers already do — CSS grid gives
4429 /// `1fr 1fr`, ratatui gives each a `Constraint::Fill(1)` — rather than
4430 /// changing anything.
4431 ///
4432 /// So a row of fills is a legal thing to describe, and there is no rule
4433 /// against it.
4434 Fill,
4435 }
4436
4437 /// What a member is worth when there is not room for all of them.
4438 ///
4439 /// Written for table columns and no longer only theirs. Three shapes ask the
4440 /// same question and this answers all three: a table too narrow for its
4441 /// columns, a row too narrow for its parts (see [`RowPart::priority`]), and a
4442 /// group of regions sharing one run of room -- goingson's tab strip and the
4443 /// [`Region::Band`] beside it, which is the case wiki `layout-room-and-fallback`
4444 /// was ruled on. It is what any member of a group is worth, not a table
4445 /// concept, and [`Fallback::Shed`] is what reads it.
4446 ///
4447 /// The doc below is the column argument, which is where the type was measured;
4448 /// the sentence that gave it away is [`Priority::Essential`]'s, which was
4449 /// already written about a row.
4450 ///
4451 /// Ordered: [`Priority::Optional`] drops first, [`Priority::Essential`] never
4452 /// drops. This replaces addressing columns by position, which is what both
4453 /// webview apps do today and is a live bug rather than only verbosity. goingson
4454 /// hides mobile columns with `nth-child(n+5)` against a seven-column table, so
4455 /// inserting a column silently hides the wrong one.
4456 /// `#[non_exhaustive]`, same reasoning as [`Width`]. Note the ordering is the
4457 /// whole point of the type, so a new tier has to be declared in its place in
4458 /// the sequence rather than appended.
4459 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4460 #[non_exhaustive]
4461 pub enum Priority {
4462 /// Dropped first.
4463 Optional,
4464 /// Dropped once the optional members are gone.
4465 Secondary,
4466 /// Never dropped. Without it the group does not identify itself.
4467 Essential,
4468 }
4469
4470 /// What a group does when it runs out of room.
4471 ///
4472 /// Authored, and required: the field carrying this has no `Default` and a group
4473 /// cannot be described without saying what it does when it runs out of room.
4474 /// Max ruled on that: more intentionality from layout designers is
4475 /// acceptable so long as the constraints are solvable, because the goal is
4476 /// enabling good layouts rather than rescuing bad ones. A default here would be
4477 /// the crate guessing, and the guess would be silently wrong on the screens
4478 /// that matter.
4479 ///
4480 /// Relief resolves inside-out. A group asks its children to fall back before
4481 /// falling back itself, or an outer group collapses while an inner one still
4482 /// had slack.
4483 ///
4484 /// # No `Swap`
4485 ///
4486 /// An authored alternate group for the tight case is deliberately out of the
4487 /// first cut. It doubles the description for that group and the two halves can
4488 /// drift, which is the failure this vocabulary exists to end. Add it when a
4489 /// site proves it needs one.
4490 ///
4491 /// `#[non_exhaustive]`, [`Width`]'s reasoning. Unlike [`Priority`] there is no
4492 /// order to preserve, so a member can be appended.
4493 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4494 #[non_exhaustive]
4495 pub enum Fallback {
4496 /// One row becomes two. Every member stays, in the order described.
4497 Wrap,
4498 /// A row becomes a column. Every member stays, full width.
4499 Stack,
4500 /// Members drop by [`Priority`], down to [`Priority::Essential`].
4501 ///
4502 /// What a narrow table already does with its columns, applied to a group.
4503 /// What drops is gone from the screen, so this is right when the dropped
4504 /// members are facts the reader can do without and wrong when they are the
4505 /// only way to act.
4506 Shed,
4507 /// The members [`Shed`](Self::Shed) would drop move into one overflow
4508 /// control instead.
4509 ///
4510 /// The answer when a group holds actions. A control is not a fact: dropping
4511 /// it does not cost the reader a detail, it costs them the only way to act,
4512 /// which is [`RowPart::priority`]'s argument one level up.
4513 Menu,
4514 }
4515
4516 /// One column of a table.
4517 ///
4518 /// Described once. The grid track, the cell order and the drop behaviour are
4519 /// all derived from this, rather than being three hand-written encodings that
4520 /// must agree and are never checked against each other.
4521 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4522 pub struct Column<'a> {
4523 /// The heading, and the name the cell is addressed by.
4524 pub name: &'a str,
4525 /// How much room it asks for.
4526 pub width: Width,
4527 /// What it is worth when room runs out.
4528 pub priority: Priority,
4529 /// Whether the user can reorder the table by this column.
4530 ///
4531 /// What reordering *calls* is not here — that is an address, and this
4532 /// crate names none — so a host pairs this with the route the way it pairs
4533 /// a row's parts with the row's activation. This says the affordance
4534 /// exists, which is what a renderer needs to draw a header a user can
4535 /// press rather than a heading they cannot.
4536 pub sortable: bool,
4537 /// Which way the table is ordered by this column, if it is.
4538 ///
4539 /// `None` on every column but the one in force. A renderer draws the caret
4540 /// from this and a webview sets `aria-sort`, which is why it is per column
4541 /// rather than a single fact on the table: the host idiom is a property of
4542 /// the header cell.
4543 ///
4544 /// Independent of [`sortable`](Self::sortable) rather than implied by it,
4545 /// because both combinations mean something. A column sorted and not
4546 /// sortable is a list ordered by a key the user cannot change, which is a
4547 /// real thing to describe and a caret worth drawing.
4548 pub sorted: Option<Sort>,
4549 }
4550
4551 /// Which way a column is ordered.
4552 ///
4553 /// Two, because there is no third. "Unsorted" is [`Column::sorted`] being
4554 /// `None`, and folding it in here would be the same absence said twice.
4555 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4556 pub enum Sort {
4557 /// Smallest, earliest or first alphabetically at the top.
4558 Ascending,
4559 /// The other way.
4560 Descending,
4561 }
4562
4563 impl Sort {
4564 /// The other direction, for a header that flips when pressed.
4565 #[must_use]
4566 pub const fn reversed(self) -> Self {
4567 match self {
4568 Self::Ascending => Self::Descending,
4569 Self::Descending => Self::Ascending,
4570 }
4571 }
4572
4573 /// What a webview writes into `aria-sort`.
4574 ///
4575 /// Named here rather than in the webview renderer because a terminal and an
4576 /// immediate-mode painter both want the same two words for a caret's label,
4577 /// and three renderers picking their own is the drift this crate ends.
4578 #[must_use]
4579 pub const fn as_str(self) -> &'static str {
4580 match self {
4581 Self::Ascending => "ascending",
4582 Self::Descending => "descending",
4583 }
4584 }
4585
4586 /// The caret a renderer draws for this direction.
4587 ///
4588 /// Here for [`as_str`](Self::as_str)'s reason, said about a glyph rather
4589 /// than a word: three renderers picking their own is the drift this crate
4590 /// ends. They had picked their own — two on the solid triangles and
4591 /// `makeover-webview` on the arrows U+2191/U+2193 — and agreeing by
4592 /// coincidence in three files is not agreement.
4593 ///
4594 /// The reason generalizes past this pair and is the house rule now —
4595 /// prefer the bolder, simpler glyph over the thinner or more complicated
4596 /// one. A third spelling is not open for re-argument.
4597 ///
4598 /// **Bare, with no spacing.** Where the gap goes is each renderer's
4599 /// business: `makeover-tui` and `makeover-immediate` carry a leading space
4600 /// inside their `TableStyle` string and a webview emits its own in
4601 /// `content`, so folding a space in here would make one of the two wrong.
4602 ///
4603 /// Neither face the web apps self-host carries these — IBM Plex Mono has one
4604 /// glyph in the whole geometric-shapes block and Lato has none — so a
4605 /// browser falls back per glyph until the in-house face ships with them
4606 /// drawn in (wiki `typography-standard`). Cosmetic
4607 /// drift in one renderer, not a reason to spell it three ways.
4608 #[must_use]
4609 pub const fn glyph(self) -> &'static str {
4610 match self {
4611 Self::Ascending => "\u{25B2}",
4612 Self::Descending => "\u{25BC}",
4613 }
4614 }
4615 }
4616
4617 impl<'a> Column<'a> {
4618 /// A column that absorbs slack and drops after the optional ones.
4619 #[must_use]
4620 pub const fn new(name: &'a str) -> Self {
4621 Self {
4622 name,
4623 width: Width::Fill,
4624 priority: Priority::Secondary,
4625 sortable: false,
4626 sorted: None,
4627 }
4628 }
4629
4630 /// Whether this column survives at the given cutoff.
4631 ///
4632 /// A renderer narrows by raising the cutoff, and never by counting
4633 /// positions.
4634 #[must_use]
4635 pub const fn kept_at(&self, cutoff: Priority) -> bool {
4636 (self.priority as u8) >= (cutoff as u8)
4637 }
4638 }
4639
4640 /// What a table cell holds.
4641 ///
4642 /// [`RowPart`] for tables, and it exists for the same reason: a part that
4643 /// carries a control is not text, and a renderer with one class for the whole
4644 /// cell paints it as though it were: a button in a cell inherits the cell's
4645 /// content colour, which is the drift [`RowPart::intent`] prevents for rows.
4646 ///
4647 /// Four members, and the count is what quasi's `Cell` was measured to carry: a
4648 /// value, tokens, actions and a link. Nothing was added past what something
4649 /// holds.
4650 ///
4651 /// `#[non_exhaustive]` for [`RowPart`]'s reason: growth here must not be a
4652 /// lockstep event across three renderers.
4653 ///
4654 /// # No hover-reveal
4655 ///
4656 /// This enum never gets one. A cell's actions are shown at rest in every
4657 /// consumer measured, and a member nothing uses is one three renderers owe an
4658 /// answer for.
4659 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4660 #[non_exhaustive]
4661 pub enum CellPart {
4662 /// The cell's own text.
4663 Value,
4664 /// Small labelled things in the cell: a status badge, a chip.
4665 Tokens,
4666 /// Controls that act on what the row is about.
4667 Actions,
4668 /// The cell's value, where the value is itself a link.
4669 Link,
4670 }
4671
4672 impl CellPart {
4673 /// The content intent the part takes.
4674 ///
4675 /// One part is text and three are not, so three answer with the intent
4676 /// inheriting already gives. That is [`RowPart::intent`]'s shape with the
4677 /// text side narrower: a cell's secondary and muted readings are the
4678 /// column's business, not the cell's.
4679 #[must_use]
4680 pub const fn intent(self) -> &'static str {
4681 match self {
4682 Self::Value => "content",
4683 // A token carries its own tone, and a part-level intent underneath
4684 // it would fight the token sitting on it.
4685 Self::Tokens => "content",
4686 // Actions carry controls rather than text.
4687 Self::Actions => "content",
4688 // A link takes the action colour from the control it is, rather
4689 // than the cell's text colour from the cell it sits in.
4690 Self::Link => "content",
4691 }
4692 }
4693 }
4694
4695 /// A named dimension a set can be narrowed by.
4696 ///
4697 /// One word for six things that were six mechanisms. MNW's discover page filters
4698 /// by free text, a flat any-of over item types, a tree of tags, a numeric range
4699 /// over price, a nested one-of over AI tier, and a browse position in the tag
4700 /// tree held separately from the tag selection — and the last two being separate
4701 /// is the whole reason a filter row there needs a tick box *and* a chevron. The
4702 /// panel is a mixed bag of hand-written controls because nothing named the thing
4703 /// they all are.
4704 ///
4705 /// Deliberately wider than that one page. audiofiles' library browser and
4706 /// goingson's filters are the same shape, and a word that only fitted discover
4707 /// would be discover's markup with a neutral name on it.
4708 ///
4709 /// # What it does not say
4710 ///
4711 /// **What picking a value calls.** This crate names no address, so a facet is
4712 /// paired with routes the way a column's [`sortable`](Column::sortable) flag is
4713 /// paired with what reordering calls.
4714 ///
4715 /// **How a tree is drawn.** Indented rows, a column of panes, a breadcrumb and a
4716 /// list: all four are honest renderings of the same described facet, and a
4717 /// terminal will not pick the same one a browser does. [`FacetValue::depth`] is
4718 /// what a renderer needs to draw any of them; the choice is not described.
4719 ///
4720 /// **Which values to show.** A tag tree has thousands of nodes and a panel shows
4721 /// a handful. Deciding which handful is the app's — it is the same question as
4722 /// which rows go in a table, and no table member answers it either.
4723 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4724 #[non_exhaustive]
4725 pub struct Facet<'a> {
4726 /// What the dimension is called, as the user reads it.
4727 pub name: &'a str,
4728 /// How many of its values may be in force, and in what shape.
4729 pub mode: Selecting,
4730 /// The values on offer, in the order they are drawn.
4731 ///
4732 /// A [`Selecting::Text`] facet has none: the value is whatever was typed,
4733 /// and a description that listed the possible strings would be listing the
4734 /// corpus. A [`Selecting::Range`] facet has none either, for the reason
4735 /// [`FieldKind::Range`] takes bounds rather than options — the ends are the
4736 /// question and the values between them are not enumerable.
4737 pub values: &'a [FacetValue<'a>],
4738 }
4739
4740 impl<'a> Facet<'a> {
4741 /// A dimension with values to pick from.
4742 #[must_use]
4743 pub const fn new(name: &'a str, mode: Selecting, values: &'a [FacetValue<'a>]) -> Self {
4744 Self { name, mode, values }
4745 }
4746
4747 /// Whether the facet is narrowing the set right now.
4748 ///
4749 /// The question a renderer asks to decide whether to offer a way out of it,
4750 /// and the reason it is derived rather than carried: a facet with nothing
4751 /// standing is unengaged by construction, so a member saying so could
4752 /// disagree with the values beside it. [`Standing::Inherited`] does not
4753 /// count — something further up is what is doing the narrowing, and clearing
4754 /// a child that was never picked clears nothing.
4755 ///
4756 /// Always false for [`Selecting::Text`] and [`Selecting::Range`], which
4757 /// carry no values. A host that wants a clear affordance on those knows
4758 /// whether its own box is empty; the description does not hold the typed
4759 /// string.
4760 #[must_use]
4761 pub fn engaged(&self) -> bool {
4762 self.values.iter().any(|value| value.standing.is_picked())
4763 }
4764
4765 /// The deepest value in the facet, or zero when it is flat.
4766 ///
4767 /// What an indenting renderer needs to reserve a gutter before it draws the
4768 /// first row, which is "First paint is final paint" applied to a tree: a
4769 /// gutter widened as deeper values arrive is the reflow that rule forbids.
4770 #[must_use]
4771 pub fn reach(&self) -> u8 {
4772 self.values
4773 .iter()
4774 .map(|value| value.depth.level)
4775 .max()
4776 .unwrap_or(0)
4777 }
4778 }
4779
4780 /// How many of a [`Facet`]'s values may be in force, and in what shape.
4781 ///
4782 /// Five, and the fifth is what made this an enum rather than a bool. `one-of`,
4783 /// `any-of`, a range and free text are the four a form vocabulary already has in
4784 /// [`FieldKind`]; a tree's selection is none of them, and describing tags as
4785 /// any-of was what forced browsing to be a second mechanism beside filtering.
4786 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4787 #[non_exhaustive]
4788 pub enum Selecting {
4789 /// Exactly one value, and picking another replaces it.
4790 ///
4791 /// MNW's AI tier, whose three options are nested ranges rather than
4792 /// independent values, so two of them at once means nothing.
4793 OneOf,
4794 /// Any number of values, each independent of the others.
4795 AnyOf,
4796 /// A low end, a high end, or both.
4797 ///
4798 /// Carries no values for [`FieldKind::Range`]'s reason: the ends are the
4799 /// question.
4800 Range,
4801 /// Whatever the user types.
4802 Text,
4803 /// A position in a tree, edited by taking branches in and pruning branches
4804 /// out.
4805 ///
4806 /// The one mode that is not reducible to the others, and the one gesture
4807 /// that replaced two. Picking a value narrows the set to it *and* reveals
4808 /// its children, so browsing a tree and filtering by it stop being separate
4809 /// mechanisms with separate state. What a selection then is: a set of
4810 /// branches taken and a set pruned, resolved nearest-ancestor-first, so
4811 /// `music` in and `music/synths` out is sayable and no flat mode can say it.
4812 ///
4813 /// Resolution happens in the app, and what reaches a renderer is the
4814 /// [`Standing`] each drawn value ended up with. A renderer walking ancestors
4815 /// itself would be a renderer that can disagree with the results beside it.
4816 Subtree,
4817 }
4818
4819 impl Selecting {
4820 /// Whether the mode picks from values the description lists.
4821 ///
4822 /// False for [`Text`](Self::Text) and [`Range`](Self::Range), which are the
4823 /// two whose answer is not one of a set. A renderer asks this before it
4824 /// looks at [`Facet::values`], the way it asks
4825 /// [`FieldKind::offers_options`] before it looks at [`Field::options`].
4826 #[must_use]
4827 pub const fn offers_values(self) -> bool {
4828 matches!(self, Self::OneOf | Self::AnyOf | Self::Subtree)
4829 }
4830
4831 /// Whether a value can be pruned as well as picked.
4832 ///
4833 /// [`Subtree`](Self::Subtree) alone. Excluding a value from a flat facet is
4834 /// the same fact as not picking it, so an exclude affordance there would be
4835 /// a second control for a state the first one already holds.
4836 #[must_use]
4837 pub const fn prunes(self) -> bool {
4838 matches!(self, Self::Subtree)
4839 }
4840
4841 /// Whether picking a second value keeps the first.
4842 #[must_use]
4843 pub const fn accumulates(self) -> bool {
4844 matches!(self, Self::AnyOf | Self::Subtree)
4845 }
4846 }
4847
4848 /// One value a [`Facet`] offers, as it currently stands.
4849 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4850 #[non_exhaustive]
4851 pub struct FacetValue<'a> {
4852 /// What identifies it, and what a host keys its route on.
4853 ///
4854 /// [`Choice::value`]'s split, and a tree is why it is not optional: two
4855 /// leaves under different parents are legitimately both called "Ambient",
4856 /// and the path is the only thing telling them apart. It is also what
4857 /// nearest-ancestor-wins resolves over, so an app that carried only labels
4858 /// could not compute the [`standing`](Self::standing) it hands back here.
4859 pub value: &'a str,
4860 /// What it is called, as the user reads it.
4861 ///
4862 /// The leaf's own name rather than its path: a facet drawn as an indented
4863 /// tree repeats every ancestor on every line otherwise, and one drawn as a
4864 /// breadcrumb has the ancestors already.
4865 pub label: &'a str,
4866 /// How many members of the set carry it.
4867 ///
4868 /// Optional, and settled that way rather than made mandatory: a count is a
4869 /// measured fact the app may not have. Counting a tag subtree under an
4870 /// active text search is a second query, and an app that will not pay for it
4871 /// should be able to describe the facet anyway rather than write a zero that
4872 /// reads as "none of them". That is [`Awaiting::amount`]'s rule in a second
4873 /// place — state a number when it was measured, and nothing when it was not.
4874 pub count: Option<u64>,
4875 /// Whether it is narrowing the set, and how it came to be.
4876 pub standing: Standing,
4877 /// How far down the tree it sits, counting from zero at the root.
4878 ///
4879 /// Always zero for a flat facet, which is what makes an indenting renderer
4880 /// one code path rather than two. A renderer that draws no tree at all still
4881 /// reads this, since a value's depth is what distinguishes two same-named
4882 /// leaves under different parents.
4883 pub depth: Nesting,
4884 /// Whether taking it reveals values under it.
4885 ///
4886 /// Distinct from having a nonzero [`depth`](Self::depth): a leaf deep in the
4887 /// tree branches no further, and a root with children does. Both facts are
4888 /// needed and neither implies the other, which is why the pair is two
4889 /// members rather than one count.
4890 pub branching: bool,
4891 }
4892
4893 impl<'a> FacetValue<'a> {
4894 /// An unpicked value at the root of the facet.
4895 #[must_use]
4896 pub const fn new(value: &'a str, label: &'a str) -> Self {
4897 Self {
4898 value,
4899 label,
4900 count: None,
4901 standing: Standing::Open,
4902 depth: Nesting::top(),
4903 branching: false,
4904 }
4905 }
4906
4907 /// A value whose identifier is also what the user reads.
4908 ///
4909 /// [`Choice::of`]'s convenience, and it is the flat case: a type or a tier
4910 /// is its own name, and only a tree needs a path that is not one.
4911 #[must_use]
4912 pub const fn of(value: &'a str) -> Self {
4913 Self::new(value, value)
4914 }
4915
4916 /// How many members carry it, when that was measured.
4917 #[must_use]
4918 pub const fn counted(mut self, count: u64) -> Self {
4919 self.count = Some(count);
4920 self
4921 }
4922
4923 /// How it stands in the current selection.
4924 #[must_use]
4925 pub const fn standing(mut self, standing: Standing) -> Self {
4926 self.standing = standing;
4927 self
4928 }
4929
4930 /// Where it sits in the tree, and whether anything hangs off it.
4931 #[must_use]
4932 pub const fn at(mut self, depth: Nesting, branching: bool) -> Self {
4933 self.depth = depth;
4934 self.branching = branching;
4935 self
4936 }
4937 }
4938
4939 /// Whether a [`FacetValue`] is narrowing the set, and how it came to be.
4940 ///
4941 /// Four rather than a bool, and the two extra members are what a tree costs. A
4942 /// pruned branch and an untaken one are not the same state — one was decided
4943 /// against and the other was never reached — and a child under a taken parent is
4944 /// in force without anybody having picked it. A renderer given a bool either
4945 /// marks every descendant of a taken branch, which reads as forty deliberate
4946 /// choices, or marks none of them, which reads as unfiltered.
4947 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4948 #[non_exhaustive]
4949 pub enum Standing {
4950 /// Not picked, and nothing above it is either.
4951 #[default]
4952 Open,
4953 /// Picked here. The set is narrowed to it and whatever hangs off it.
4954 Taken,
4955 /// In force because something above it was taken.
4956 Inherited,
4957 /// Pruned out, though something above it was taken.
4958 ///
4959 /// The state that only [`Selecting::Subtree`] can reach, and the reason
4960 /// exclusion is drawn as a visible affordance beside each label rather than
4961 /// as a modifier on the ordinary one: a gesture a terminal cannot express is
4962 /// a gesture half the renderers would have to leave out, and an affordance
4963 /// nothing teaches is one users do not find.
4964 Pruned,
4965 }
4966
4967 impl Standing {
4968 /// Whether the user decided this value, either way.
4969 ///
4970 /// True for [`Taken`](Self::Taken) and [`Pruned`](Self::Pruned) — both are
4971 /// choices, and both are things a "clear this" affordance has to clear.
4972 /// [`Inherited`](Self::Inherited) is not: clearing it clears nothing,
4973 /// because the decision is further up.
4974 #[must_use]
4975 pub const fn is_picked(self) -> bool {
4976 matches!(self, Self::Taken | Self::Pruned)
4977 }
4978
4979 /// Whether the value narrows the set in.
4980 ///
4981 /// [`Taken`](Self::Taken) and [`Inherited`](Self::Inherited): one was picked
4982 /// and one came down from above, and to the set they mean the same thing.
4983 /// The pair is named here so a renderer colouring in-force values does not
4984 /// have to know which is which.
4985 #[must_use]
4986 pub const fn in_force(self) -> bool {
4987 matches!(self, Self::Taken | Self::Inherited)
4988 }
4989
4990 /// The content intent the value takes.
4991 ///
4992 /// [`Pruned`](Self::Pruned) reads back a step, which is the three-tone rule
4993 /// above rather than a new decision: a pruned branch is still a live control
4994 /// — pressing it takes the prune off — so it may not wear `content-muted`,
4995 /// and it is not the thing itself either.
4996 #[must_use]
4997 pub const fn intent(self) -> &'static str {
4998 match self {
4999 Self::Taken | Self::Inherited | Self::Open => "content",
5000 Self::Pruned => "content-secondary",
5001 }
5002 }
5003 }
5004
5005 #[cfg(test)]
5006 mod tests {
5007 /// The concept is named here and its magnitude is not, which is
5008 /// `Awaiting`'s split and is why a renderer can disagree with another
5009 /// about what a level is worth without either of them being wrong.
5010 #[test]
5011 fn nesting_says_how_deep_and_not_how_wide() {
5012 assert_eq!(Nesting::default(), Nesting::top());
5013 assert_eq!(Nesting::top().level, 0);
5014 assert!(!Nesting::top().is_nested());
5015
5016 let under = Nesting::at(2);
5017 assert_eq!(under.level, 2);
5018 assert!(under.is_nested());
5019
5020 // Ordered, so a renderer walking a flat list of rows can compare two
5021 // levels rather than reaching into the field.
5022 assert!(Nesting::top() < under);
5023 }
5024
5025 use super::*;
5026
5027 #[test]
5028 fn a_markdown_field_is_multiline_and_offers_nothing() {
5029 // The editing counterpart of markdown prose is still text: every host
5030 // can draw it, which is the whole reason the kind was addable.
5031 assert!(FieldKind::Rich.multiline());
5032 assert!(FieldKind::Textarea.multiline());
5033 assert!(!FieldKind::Text.multiline());
5034 // It is not a chooser and not a moment.
5035 assert!(!FieldKind::Rich.offers_options());
5036 assert!(!FieldKind::Rich.temporal());
5037 assert!(FieldKind::Rich.visible());
5038 }
5039
5040 #[test]
5041 fn only_the_numeric_kinds_are_measurable() {
5042 assert!(FieldKind::Number.measurable());
5043 assert!(FieldKind::Range.measurable());
5044 // An axis is measured in something and both its ends are in it, so the
5045 // unit is read once for the pair rather than per end.
5046 assert!(FieldKind::Interval.measurable());
5047 // A date is ordered and is not a quantity with a unit to choose: its
5048 // unit is fixed by the kind, so saying one would restate `kind`.
5049 for kind in [
5050 FieldKind::Text,
5051 FieldKind::Date,
5052 FieldKind::DateTime,
5053 FieldKind::Select,
5054 FieldKind::Checkbox,
5055 FieldKind::File,
5056 ] {
5057 assert!(!kind.measurable(), "{kind:?}");
5058 }
5059 }
5060
5061 #[test]
5062 fn a_field_carries_no_unit_until_one_is_given() {
5063 // Additive: absent is what every field described before 0.33.0 meant.
5064 let plain = Field::new(FieldKind::Number, "attack", "Attack");
5065 assert_eq!(plain.unit, None);
5066 let measured = Field {
5067 unit: Some("s"),
5068 ..Field::range("attack", "Attack", "0.001", "5")
5069 };
5070 assert_eq!(measured.unit, Some("s"));
5071 assert!(measured.kind.measurable());
5072 }
5073
5074 #[test]
5075 fn an_interval_states_both_ends_names() {
5076 // Stated rather than derived: the two measured sites disagree about
5077 // affix order, so a rule here would rename one of them.
5078 let suffixed = Field::interval("bpm_min", "bpm_max", "BPM");
5079 assert_eq!(suffixed.name, "bpm_min");
5080 assert_eq!(suffixed.upper_name, Some("bpm_max"));
5081 let prefixed = Field::interval("min_price", "max_price", "Price");
5082 assert_eq!(prefixed.name, "min_price");
5083 assert_eq!(prefixed.upper_name, Some("max_price"));
5084 assert_eq!(suffixed.kind, FieldKind::Interval);
5085 }
5086
5087 #[test]
5088 fn every_other_kind_has_no_upper_end() {
5089 // Additive: absent is what every field described before 0.34.0 meant.
5090 for kind in [FieldKind::Text, FieldKind::Number, FieldKind::Range] {
5091 assert_eq!(Field::new(kind, "n", "N").upper_name, None, "{kind:?}");
5092 }
5093 assert_eq!(Field::range("t", "T", "0", "1").upper_name, None);
5094 }
5095
5096 #[test]
5097 fn an_interval_owes_no_bounds_and_takes_the_axis_facts_once() {
5098 // A range's bounds are the control's extent and are owed; an interval's
5099 // are a rule on each end, which is Number's arrangement.
5100 let plain = Field::interval("bpm_min", "bpm_max", "BPM");
5101 assert!(!plain.bounded());
5102 let axis = Field {
5103 min: Some("0"),
5104 max: Some("300"),
5105 step: Some("1"),
5106 unit: Some("BPM"),
5107 ..Field::interval("bpm_min", "bpm_max", "BPM")
5108 };
5109 assert!(axis.bounded());
5110 assert_eq!(axis.unit, Some("BPM"));
5111 // Nothing here checks the crossing rule, exactly as nothing checks
5112 // `min` for a number: the description carries constraints and whoever
5113 // validated decides a value is wrong.
5114 assert!(axis.error.is_none());
5115 }
5116
5117 #[test]
5118 fn only_a_subtree_prunes_and_only_the_listing_modes_offer_values() {
5119 // Excluding a value from a flat facet is the same fact as not picking
5120 // it, so the affordance exists in exactly one mode.
5121 assert!(Selecting::Subtree.prunes());
5122 for mode in [
5123 Selecting::OneOf,
5124 Selecting::AnyOf,
5125 Selecting::Range,
5126 Selecting::Text,
5127 ] {
5128 assert!(!mode.prunes(), "{mode:?}");
5129 }
5130 // Text and Range answer with something that is not one of a set.
5131 assert!(!Selecting::Text.offers_values());
5132 assert!(!Selecting::Range.offers_values());
5133 assert!(Selecting::OneOf.offers_values());
5134 assert!(Selecting::AnyOf.accumulates());
5135 assert!(!Selecting::OneOf.accumulates());
5136 }
5137
5138 #[test]
5139 fn an_inherited_value_is_in_force_without_having_been_picked() {
5140 // The distinction a bool cannot hold, and the reason Standing has four
5141 // members: a child under a taken parent narrows the set, and clearing
5142 // it clears nothing.
5143 assert!(Standing::Inherited.in_force());
5144 assert!(!Standing::Inherited.is_picked());
5145 assert!(Standing::Taken.in_force());
5146 assert!(Standing::Taken.is_picked());
5147 // A prune is a decision that takes the value out.
5148 assert!(Standing::Pruned.is_picked());
5149 assert!(!Standing::Pruned.in_force());
5150 assert!(!Standing::Open.is_picked());
5151 assert!(!Standing::Open.in_force());
5152 // A pruned branch still answers a press, so it may not read as inert.
5153 assert_ne!(Standing::Pruned.intent(), "content-muted");
5154 }
5155
5156 #[test]
5157 fn a_facet_is_engaged_by_a_decision_and_not_by_an_inherited_value() {
5158 let inherited = [
5159 FacetValue::of("music")
5160 .standing(Standing::Taken)
5161 .at(Nesting::at(0), true),
5162 FacetValue::new("music/synths", "synths")
5163 .standing(Standing::Inherited)
5164 .at(Nesting::at(1), false),
5165 ];
5166 let facet = Facet::new("Tag", Selecting::Subtree, &inherited);
5167 assert!(facet.engaged());
5168 // The gutter an indenting renderer reserves before its first paint.
5169 assert_eq!(facet.reach(), 1);
5170
5171 let untouched = [
5172 FacetValue::of("music").at(Nesting::at(0), true),
5173 FacetValue::new("music/synths", "synths")
5174 .standing(Standing::Inherited)
5175 .at(Nesting::at(1), false),
5176 ];
5177 // Inherited alone is something further up doing the narrowing, and
5178 // there is nothing further up here.
5179 assert!(!Facet::new("Tag", Selecting::Subtree, &untouched).engaged());
5180
5181 // A text facet lists nothing, so it is flat and never reads as engaged
5182 // from its values: the typed string is not held here.
5183 let typed = Facet::new("Search", Selecting::Text, &[]);
5184 assert!(!typed.engaged());
5185 assert_eq!(typed.reach(), 0);
5186 }
5187
5188 #[test]
5189 fn a_count_is_absent_rather_than_zero_when_it_was_not_measured() {
5190 // Awaiting::amount's rule in a second place: a written zero reads as
5191 // "none of them", which is a different claim from "not counted".
5192 assert_eq!(FacetValue::of("Ambient").count, None);
5193 assert_eq!(FacetValue::of("Ambient").counted(0).count, Some(0));
5194 }
5195
5196 #[test]
5197 fn one_kind_takes_files_and_the_two_file_members_are_its_alone() {
5198 assert!(FieldKind::File.takes_files());
5199 for kind in [
5200 FieldKind::Text,
5201 FieldKind::Textarea,
5202 FieldKind::Rich,
5203 FieldKind::Select,
5204 FieldKind::Checkbox,
5205 FieldKind::Hidden,
5206 ] {
5207 assert!(!kind.takes_files());
5208 }
5209 // The default is a field that takes any one file, which is what an
5210 // input with no accept and no multiple already is.
5211 let plain = Field::new(FieldKind::File, "cover", "Cover");
5212 assert!(plain.accept.is_empty());
5213 assert!(!plain.multiple);
5214 }
5215
5216 #[test]
5217 fn an_accept_list_says_which_disclosure_and_a_suffix_says_none() {
5218 // The three shapes are the MNW server's own three, and the family is
5219 // the question a renderer asks before it keeps room for a preview.
5220 assert_eq!(
5221 Accepted::Family(Family::Image).family(),
5222 Some(Family::Image)
5223 );
5224 assert_eq!(Accepted::Type("image/jpeg").family(), Some(Family::Image));
5225 assert_eq!(Accepted::Type("audio/flac").family(), Some(Family::Audio));
5226 assert_eq!(
5227 Accepted::Type("video/quicktime").family(),
5228 Some(Family::Video)
5229 );
5230 // A media type outside the three families names none, and neither does
5231 // a suffix. `.mp3` is audio in fact and this crate will not infer it:
5232 // the table that said so would rot.
5233 assert_eq!(Accepted::Type("text/csv").family(), None);
5234 assert_eq!(Accepted::Suffix(".mp3").family(), None);
5235 assert_eq!(Accepted::Suffix(".tar.gz").family(), None);
5236 // Media types are case-insensitive and half the tree writes them
5237 // lowercase by habit rather than by rule.
5238 assert_eq!(Accepted::Type("IMAGE/PNG").family(), Some(Family::Image));
5239 }
5240
5241 #[test]
5242 fn every_accepted_entry_has_one_spelling_a_host_can_write() {
5243 assert_eq!(Accepted::Family(Family::Image).as_str(), "image/*");
5244 assert_eq!(Accepted::Family(Family::Audio).as_str(), "audio/*");
5245 assert_eq!(Accepted::Family(Family::Video).as_str(), "video/*");
5246 assert_eq!(Accepted::Type("text/csv").as_str(), "text/csv");
5247 assert_eq!(Accepted::Suffix(".tar.gz").as_str(), ".tar.gz");
5248 }
5249
5250 #[test]
5251 fn a_list_accepting_two_families_still_has_a_disclosure_to_offer() {
5252 // The measured dropzone: `accept="image/*,video/*"`. There is no single
5253 // family to return and there is still a preview to keep room for, which
5254 // is why the question is asked of the list rather than of one entry.
5255 const MEDIA: &[Accepted<'_>] = &[
5256 Accepted::Family(Family::Image),
5257 Accepted::Family(Family::Video),
5258 ];
5259 assert!(Field::upload("media", "Media", MEDIA).accepts_media());
5260 // An installer's suffix list wants no disclosure, which is the measured
5261 // case rather than a hypothetical one.
5262 const BUILDS: &[Accepted<'_>] = &[Accepted::Suffix(".zip"), Accepted::Suffix(".dmg")];
5263 assert!(!Field::upload("build", "Build", BUILDS).accepts_media());
5264 // And a field that takes anything says so by listing nothing.
5265 assert!(!Field::upload("any", "File", &[]).accepts_media());
5266 }
5267
5268 #[test]
5269 fn an_upload_carries_its_list_and_takes_one_file_until_it_says_otherwise() {
5270 const IMAGES: &[Accepted<'_>] = &[
5271 Accepted::Type("image/jpeg"),
5272 Accepted::Type("image/png"),
5273 Accepted::Type("image/webp"),
5274 ];
5275 let avatar = Field::upload("avatar", "Avatar", IMAGES);
5276 assert_eq!(avatar.kind, FieldKind::File);
5277 assert_eq!(avatar.accept, IMAGES);
5278 assert!(!avatar.multiple);
5279 let several = Field {
5280 multiple: true,
5281 ..avatar
5282 };
5283 assert!(several.multiple);
5284 }
5285
5286 #[test]
5287 fn the_four_readiness_states_are_one_axis_and_only_one_shows_content() {
5288 // Mutually exclusive is the test for one enum against several fields: a
5289 // region shows its content, or that it is coming, or that there is none,
5290 // or that it broke. Never two.
5291 assert!(Readiness::Ready.shows_content());
5292 for state in [Readiness::Pending, Readiness::Empty, Readiness::Failed] {
5293 assert!(!state.shows_content());
5294 }
5295 }
5296
5297 #[test]
5298 fn a_region_shows_all_of_its_children_unless_it_says_otherwise() {
5299 // The default is the behaviour every region had before this member
5300 // existed, which is what keeps it additive: a description written
5301 // against 0.22.0 says the same thing under 0.23.0.
5302 assert_eq!(Showing::default(), Showing::All);
5303 assert!(!Showing::All.selective());
5304 }
5305
5306 #[test]
5307 fn only_a_disclosure_can_show_nothing() {
5308 // The two derived idioms differ in one respect and this is it. A
5309 // carousel's row moves between frames and never reaches empty; a
5310 // disclosure's summary line is the same control wearing its closed
5311 // state, so a renderer has to know which it is drawing.
5312 assert!(Showing::AtMostOne.dismissible());
5313 assert!(!Showing::One.dismissible());
5314 assert!(!Showing::All.dismissible());
5315
5316 // Both are selective, though. Deriving chrome is one question and
5317 // whether that chrome closes is another.
5318 assert!(Showing::One.selective());
5319 assert!(Showing::AtMostOne.selective());
5320 }
5321
5322 #[test]
5323 fn an_empty_region_is_not_a_broken_one() {
5324 // An empty list is the normal state of a new install. Drawing it in a
5325 // danger tone reports a fault where there is none, and this is the one
5326 // place the distinction is carried.
5327 assert_eq!(Readiness::Empty.tone(), Tone::Neutral);
5328 assert_eq!(Readiness::Failed.tone(), Tone::Danger);
5329 assert_eq!(Readiness::Pending.tone(), Tone::Neutral);
5330 }
5331
5332 #[test]
5333 fn a_column_can_be_sorted_without_being_sortable() {
5334 // Both combinations mean something, which is why the two fields are
5335 // independent rather than one implying the other. A list ordered by a
5336 // key the user cannot change is a real thing with a caret worth drawing.
5337 let fixed = Column {
5338 sorted: Some(Sort::Descending),
5339 ..Column::new("Created")
5340 };
5341
5342 assert!(!fixed.sortable);
5343 assert_eq!(fixed.sorted.map(Sort::as_str), Some("descending"));
5344
5345 let offered = Column {
5346 sortable: true,
5347 ..Column::new("Name")
5348 };
5349 assert_eq!(offered.sorted, None);
5350 }
5351
5352 #[test]
5353 fn a_direction_flips_and_says_what_it_is() {
5354 assert_eq!(Sort::Ascending.reversed(), Sort::Descending);
5355 assert_eq!(Sort::Descending.reversed().reversed(), Sort::Descending);
5356 assert_eq!(Sort::Ascending.as_str(), "ascending");
5357 }
5358
5359 #[test]
5360 fn a_direction_carries_its_caret_and_the_two_are_not_the_same_glyph() {
5361 // The spelling every renderer reads, so that agreeing is composition
5362 // rather than three files happening to hold the same literal.
5363 assert_eq!(Sort::Ascending.glyph(), "\u{25B2}");
5364 assert_eq!(Sort::Descending.glyph(), "\u{25BC}");
5365 assert_ne!(Sort::Ascending.glyph(), Sort::Descending.glyph());
5366 // Bare. The gap is the renderer's, and a space here would be a second
5367 // one wherever a renderer already carries its own.
5368 for d in [Sort::Ascending, Sort::Descending] {
5369 assert_eq!(d.glyph().trim(), d.glyph());
5370 }
5371 }
5372
5373 #[test]
5374 fn a_figure_carries_its_tone_because_no_renderer_can_derive_it() {
5375 // Three of goingson's five sites tone the figure by their own means, so
5376 // tone is carried at every site that needs it and derived at none. The
5377 // same reasoning `Meter` reached, from a different direction.
5378 let streak = Figure::new("0", "Current Streak").tone(Tone::Warning);
5379 assert_eq!(streak.tone, Tone::Warning);
5380 assert_eq!(Figure::new("17", "Total").tone, Tone::Neutral);
5381 }
5382
5383 #[test]
5384 fn a_figures_change_is_the_toned_part_and_is_absent_by_default() {
5385 // 0.13.0. The MNW server's stat card is a label, a value and a delta,
5386 // across four screens, and the delta is what reads as good or bad. Tone
5387 // had no consumer before this: the figure itself is an ordinary fact.
5388 let views = Figure::new("1,204", "Views")
5389 .change("+12.5%")
5390 .tone(Tone::Success);
5391 assert_eq!(views.change, Some("+12.5%"));
5392 assert_eq!(views.tone, Tone::Success);
5393
5394 // A figure with nothing to compare against says so by having no change,
5395 // rather than by carrying an empty string a renderer has to test for.
5396 assert_eq!(Figure::new("3.1%", "Conversion").change, None);
5397 }
5398
5399 #[test]
5400 fn a_figures_value_is_text_because_only_the_app_knows_what_it_is() {
5401 // "84%", "12/30", "3d". A figure is whatever the app computed, already
5402 // formatted, and that is the line between this and `Meter`: a meter is
5403 // a proportion a renderer draws, a figure is a fact it sets in type.
5404 for value in ["84%", "12/30", "3d"] {
5405 assert_eq!(Figure::new(value, "Rate").value, value);
5406 }
5407 }
5408
5409 #[test]
5410 fn a_proportion_is_a_row_part_and_takes_no_intent_of_its_own() {
5411 // The meter carries the tone, so a part-level intent underneath would
5412 // fight it. Same answer `Tokens` needed, for the same reason.
5413 assert_eq!(RowPart::Proportion.intent(), RowPart::Tokens.intent());
5414 }
5415
5416 #[test]
5417 fn a_file_field_is_drawn_and_offers_no_options() {
5418 // It is a control the user operates, unlike `Hidden`, and it does not
5419 // pick from a list the description carries, unlike `Select`.
5420 assert!(FieldKind::File.visible());
5421 assert!(!FieldKind::File.offers_options());
5422 assert!(!FieldKind::File.confidential());
5423 }
5424
5425 #[test]
5426 fn a_constraint_is_a_fact_about_the_question_and_not_a_verdict() {
5427 // The whole model: the description carries the rule, the renderer emits
5428 // its host's idiom, and `error` is what arrives back when someone
5429 // validated. Nothing here decides a value is wrong.
5430 let field = Field {
5431 max_length: Some(100),
5432 min: Some("1"),
5433 max: Some("240"),
5434 required: true,
5435 ..Field::new(FieldKind::Number, "minutes", "Minutes")
5436 };
5437 assert!(!field.invalid());
5438
5439 // A bound is text because it is only a number for some of the kinds
5440 // that take one. goingson has both shapes live.
5441 let when = Field {
5442 min: Some("2026-08-09T14:30"),
5443 ..Field::new(FieldKind::Text, "starts", "Starts")
5444 };
5445 assert_eq!(when.min, Some("2026-08-09T14:30"));
5446 }
5447
5448 #[test]
5449 fn a_meter_keeps_the_over_run_the_percentage_throws_away() {
5450 // The whole reason this is a pair. goingson's `Task::time_progress`
5451 // clamps to 100 and then carries `is_over_estimate` beside it to say
5452 // what the clamp dropped; a meter says both from one fact.
5453 let over = Meter::new(45, 30);
5454 assert_eq!(over.percent(), 100);
5455 assert!(over.overflowing());
5456
5457 let exact = Meter::new(30, 30);
5458 assert_eq!(exact.percent(), over.percent());
5459 assert!(!exact.overflowing());
5460 }
5461
5462 #[test]
5463 fn an_empty_set_does_not_divide_by_zero() {
5464 // Sayable on purpose, so it has to be answerable. A meter over an
5465 // unloaded count is what an app actually has for a frame.
5466 let none = Meter::new(0, 0);
5467 assert_eq!(none.percent(), 0);
5468 assert!(none.is_empty());
5469 assert!(!none.overflowing());
5470 }
5471
5472 #[test]
5473 fn the_ratio_survives_where_a_percentage_would_not() {
5474 // Given 43 nothing can recover "3 of 7", which is why the numbers are
5475 // carried and the label names only the noun.
5476 let m = Meter::new(3, 7).label("subtasks");
5477 assert_eq!(m.percent(), 42);
5478 assert_eq!((m.done, m.total), (3, 7));
5479 assert_eq!(m.label, Some("subtasks"));
5480 }
5481
5482 #[test]
5483 fn tone_is_carried_because_no_renderer_can_derive_it() {
5484 // The same fullness means opposite things on two of goingson's bars,
5485 // and only the app knows which.
5486 let subtasks = Meter::new(9, 10).tone(Tone::Success);
5487 let estimate = Meter::new(9, 10).tone(Tone::Danger);
5488 assert_eq!(subtasks.percent(), estimate.percent());
5489 assert_ne!(subtasks.tone, estimate.tone);
5490 // Untoned by default: a bar says nothing about status until something
5491 // says so, the same way a row is not selectable until told.
5492 assert_eq!(Meter::new(9, 10).tone, Tone::Neutral);
5493 }
5494
5495 #[test]
5496 fn an_act_is_reachable_until_it_is_disabled() {
5497 // The one member a renderer must branch on, and since 0.19.0 the only
5498 // member there is. A stated state is not by itself a reason to stop
5499 // answering, which is the distinction `State` makes and every
5500 // hand-rolled button in the tree had to remember.
5501 assert!(!Act::new("Save").disabled());
5502 assert!(Act::new("Save").state(State::Disabled).disabled());
5503 }
5504
5505 #[test]
5506 fn an_act_carries_its_key_because_a_terminal_has_nothing_else() {
5507 // No key is the ordinary case, and the webview hosts that ignore it
5508 // are why it stayed optional.
5509 assert_eq!(Act::new("Delete").key, None);
5510 let quit = Act::new("Quit").key("q").tone(Tone::Danger);
5511 assert_eq!(quit.key, Some("q"));
5512 assert_eq!(quit.tone, Tone::Danger);
5513 }
5514
5515 #[test]
5516 fn a_meter_does_not_overflow_on_large_counts() {
5517 // done * 100 in u32 would wrap somewhere past 42 million. Counts that
5518 // size are not tasks, but a description layer that silently reports 3%
5519 // for a full bar is worse than one that is slow.
5520 let big = Meter::new(u32::MAX, u32::MAX);
5521 assert_eq!(big.percent(), 100);
5522 assert!(!big.overflowing());
5523 }
5524
5525 #[test]
5526 fn inset_is_raised_with_the_light_moved() {
5527 let (rl, rd) = Bevel::Raised.edges();
5528 let (il, id) = Bevel::Inset.edges();
5529 assert_eq!((rl, rd), (Edge::Light, Edge::Dark));
5530 assert_eq!((il, id), (rd, rl));
5531 }
5532
5533 #[test]
5534 fn pressing_twice_is_a_no_op() {
5535 for b in [Bevel::Raised, Bevel::Inset] {
5536 assert_eq!(b.pressed().pressed(), b);
5537 }
5538 }
5539
5540 #[test]
5541 fn a_raised_region_is_never_filled_with_a_recessed_surface() {
5542 // The bug this vocabulary exists to make unrepresentable.
5543 assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
5544 assert_eq!(Depth::Raised.bevel(), Some(Bevel::Raised));
5545 assert_eq!(Depth::Well.bevel(), Some(Bevel::Inset));
5546 assert_ne!(Depth::Well.fill(), Depth::Raised.fill());
5547 }
5548
5549 #[test]
5550 fn state_is_orthogonal_to_depth() {
5551 // The reason State is its own axis and not a Depth member: a disabled
5552 // button and a disabled field are both disabled and are not the same
5553 // shape, which one shared variant could not have said.
5554 assert_eq!(Depth::Raised.fill(), Some(Fill::Raised));
5555 assert_eq!(Depth::Well.fill(), Some(Fill::Well));
5556 assert!(State::Disabled.suppresses_interaction());
5557 }
5558
5559 #[test]
5560 fn only_disabled_stops_answering() {
5561 // Kept in spirit from the version where `Focus` was the counter-example:
5562 // suppressing interaction is `Disabled`'s alone, so a member added here
5563 // later does not get to inherit it by being a state.
5564 assert!(State::Disabled.suppresses_interaction());
5565 }
5566
5567 #[test]
5568 fn disabled_resolves_against_an_intent_makeover_already_derives() {
5569 // No new token, so this costs no `makeover` release.
5570 assert_eq!(State::Disabled.token(), "content-muted");
5571 }
5572
5573 #[test]
5574 fn flat_has_neither_edge_nor_fill() {
5575 assert_eq!(Depth::Flat.bevel(), None);
5576 assert_eq!(Depth::Flat.fill(), None);
5577 }
5578
5579 #[test]
5580 fn sunken_is_recessed_by_colour_with_no_edge() {
5581 // The one member carrying a fill without a bevel. A renderer that
5582 // assumes the two arrive together drops the fill silently, which is
5583 // exactly what makeover-webview did before 0.3.0.
5584 assert_eq!(Depth::Sunken.fill(), Some(Fill::Sunken));
5585 assert_eq!(Depth::Sunken.bevel(), None);
5586 }
5587
5588 #[test]
5589 fn sunken_and_flat_are_different_claims() {
5590 // Both edgeless, and only one of them needs a colour. Collapsing them
5591 // is what left an unchosen tab unsayable.
5592 assert_eq!(Depth::Flat.bevel(), Depth::Sunken.bevel());
5593 assert_ne!(Depth::Flat.fill(), Depth::Sunken.fill());
5594 }
5595
5596 #[test]
5597 fn a_sunken_surface_is_not_a_well() {
5598 // Authored in opposite directions: makeover derives surface-well by
5599 // inverting against the theme's content colour, while surface-sunken is
5600 // authored and may sit darker than raised.
5601 assert_ne!(Fill::Sunken, Fill::Well);
5602 assert_eq!(Fill::Sunken.token(), "surface-sunken");
5603 assert_eq!(Fill::Well.token(), "surface-well");
5604 }
5605
5606 #[test]
5607 fn every_selector_describes_both_of_its_states() {
5608 // The gap 0.3.0 closed. Before it, only `chosen` existed and the
5609 // unchosen option fell through to Flat at every renderer.
5610 for s in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
5611 assert_ne!(
5612 s.chosen(),
5613 s.unchosen(),
5614 "{s:?} cannot tell picked from unpicked"
5615 );
5616 }
5617 }
5618
5619 #[test]
5620 fn only_a_tab_inverts_the_other_way() {
5621 // Tabs recede so the chosen one comes forward; a segment and a toggle
5622 // stand up so the chosen one is held in. That inversion is the whole
5623 // content of "picked" once colour is deferred, and it is why the three
5624 // are not one member with a flag.
5625 assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
5626 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
5627
5628 for s in [Selector::Segmented, Selector::Toggle] {
5629 assert_eq!(s.unchosen(), Depth::Raised);
5630 assert_eq!(s.chosen(), Depth::Well);
5631 // Held in is what pressing produces: one appearance, two reasons.
5632 assert_eq!(s.unchosen().pressed(), s.chosen());
5633 }
5634 }
5635
5636 #[test]
5637 fn pressing_a_card_makes_a_well() {
5638 assert_eq!(Depth::Raised.pressed(), Depth::Well);
5639 assert_eq!(
5640 Depth::Raised.pressed().bevel(),
5641 Depth::Raised.bevel().map(Bevel::pressed)
5642 );
5643 // Only raised regions respond to being pressed.
5644 assert_eq!(Depth::Flat.pressed(), Depth::Flat);
5645 assert_eq!(Depth::Well.pressed(), Depth::Well);
5646 // An overlay is a surface, not a control.
5647 assert_eq!(Depth::Overlay.pressed(), Depth::Overlay);
5648 }
5649
5650 #[test]
5651 fn an_overlay_is_lifted_rather_than_edged() {
5652 // The wave-2 rule: a surface over the page takes elevation, a surface
5653 // in the page takes a bevel. Both halves come off the one Depth, so
5654 // they cannot disagree.
5655 assert_eq!(Depth::Overlay.fill(), Some(Fill::Overlay));
5656 assert_eq!(Depth::Overlay.bevel(), None);
5657
5658 // Three depths have no bevel and they are not the same claim. Flat has
5659 // nothing to separate from, Sunken's colour is doing the separating,
5660 // and an overlay is separated by the lift.
5661 assert_ne!(Depth::Overlay.fill(), Depth::Sunken.fill());
5662 assert_ne!(Depth::Overlay.fill(), Depth::Flat.fill());
5663 }
5664
5665 #[test]
5666 fn a_note_is_neither_a_hint_nor_an_error() {
5667 // audiofiles' export Format field: choosing WAV over Original
5668 // re-encodes and drops the embedded metadata. Perfectly valid, and it
5669 // costs something.
5670 let format = Field {
5671 note: Some((Tone::Warning, "Re-encoding drops embedded BWF and iXML")),
5672 ..Field::select("format", "Format", &[])
5673 };
5674 assert!(!format.invalid(), "a note is not a validation failure");
5675 assert!(format.hint.is_none());
5676 assert!(format.error.is_none());
5677 assert_eq!(format.note.unwrap().0, Tone::Warning);
5678
5679 // The default is no note, so the 15 in-tree `..Field::new(..)`
5680 // literals absorb the member with no call-site edit.
5681 assert!(Field::new(FieldKind::Text, "title", "Title").note.is_none());
5682 }
5683
5684 #[test]
5685 fn neutral_is_content_not_muted_content() {
5686 // Neutral means "no status", and that is all it means. It answered
5687 // `content-muted` until 2026-08-27, which muted a figure's headline
5688 // number to the colour of its own caption. What makes a badge quiet
5689 // is `Token::Badge` answering no click, which lives on the renderer.
5690 assert_eq!(Tone::Neutral.token(), "content");
5691 assert!(!Token::Badge.interactive());
5692 assert_eq!(State::Disabled.token(), "content-muted");
5693 }
5694
5695 #[test]
5696 fn intents_name_makeover_tokens_and_nothing_else() {
5697 assert_eq!(Edge::Light.token(), "bevel-light");
5698 assert_eq!(Edge::Dark.token(), "bevel-dark");
5699 assert_eq!(Fill::Raised.token(), "surface-raised");
5700 assert_eq!(Fill::Well.token(), "surface-well");
5701 // No value ever leaves this crate.
5702 for t in [
5703 Edge::Light.token(),
5704 Edge::Dark.token(),
5705 Tone::Danger.token(),
5706 Tone::Neutral.token(),
5707 State::Disabled.token(),
5708 ] {
5709 assert!(!t.starts_with('#'), "{t} looks like a value");
5710 assert!(
5711 !t.chars().next().unwrap().is_ascii_digit(),
5712 "{t} is a value"
5713 );
5714 }
5715 }
5716
5717 #[test]
5718 fn a_badge_cannot_be_pressed_and_a_chip_latches() {
5719 // The one line that runs through all three apps' taxonomies.
5720 assert!(!Token::Badge.interactive());
5721 assert!(Token::Chip { removable: false }.interactive());
5722 assert!(Token::Chip { removable: true }.interactive());
5723
5724 // A badge is a label, so giving it an edge would lie about it.
5725 assert_eq!(Token::Badge.depth(false), Depth::Flat);
5726 assert_eq!(Token::Badge.depth(true), Depth::Flat);
5727
5728 // A latched chip wears the same shape a pressed one does.
5729 let chip = Token::Chip { removable: false };
5730 assert_eq!(chip.depth(false), Depth::Raised);
5731 assert_eq!(chip.depth(true), Depth::Raised.pressed());
5732 }
5733
5734 #[test]
5735 fn a_toast_and_a_banner_differ_in_more_than_placement() {
5736 assert!(Notice::Toast.transient());
5737 assert!(!Notice::Banner.transient());
5738 // A toast floats above the page; a banner rests in the flow.
5739 assert_eq!(Notice::Toast.fill(), Fill::Overlay);
5740 assert_eq!(Notice::Banner.fill(), Fill::Raised);
5741 }
5742
5743 #[test]
5744 fn emphasis_falls_off_down_the_row() {
5745 // `revealed_on_hover` was asserted here until 0.13.0 retired it. It said
5746 // a row's actions stay hidden until hover, which stopped being true when
5747 // makeover-webview 0.23.0 showed them at rest, and nothing had consumed
5748 // it for a release either way.
5749 assert_eq!(RowPart::Primary.intent(), "content");
5750 assert_eq!(RowPart::Secondary.intent(), "content-secondary");
5751 assert_eq!(RowPart::Meta.intent(), "content-muted");
5752 }
5753
5754 #[test]
5755 fn a_token_part_carries_no_intent_of_its_own() {
5756 // Each token carries its own tone, so a part-level intent underneath
5757 // would fight the thing sitting on it. Same reasoning as actions, which
5758 // is why they answer alike.
5759 assert_eq!(RowPart::Tokens.intent(), RowPart::Actions.intent());
5760 assert_eq!(RowPart::Tokens.intent(), "content");
5761 }
5762
5763 #[test]
5764 fn the_two_temporal_kinds_are_the_two_that_name_a_moment() {
5765 // The pair is named once so a host with parsing to do asks here rather
5766 // than spelling it out, which is `offers_options`' reason.
5767 assert!(FieldKind::Date.temporal());
5768 assert!(FieldKind::DateTime.temporal());
5769
5770 for kind in [
5771 FieldKind::Text,
5772 FieldKind::Secret,
5773 FieldKind::Number,
5774 FieldKind::Email,
5775 FieldKind::Url,
5776 FieldKind::Tel,
5777 FieldKind::Range,
5778 FieldKind::Textarea,
5779 FieldKind::Rich,
5780 FieldKind::Select,
5781 FieldKind::Radio,
5782 FieldKind::Checkbox,
5783 FieldKind::File,
5784 FieldKind::Hidden,
5785 ] {
5786 assert!(!kind.temporal(), "{kind:?}");
5787 }
5788 }
5789
5790 #[test]
5791 fn a_date_carries_no_time_and_a_datetime_carries_no_zone() {
5792 // The formats are the whole reason the members are worth naming apart
5793 // from text, so the doc comments and the constants have to agree. A
5794 // host reading one and meeting the other is the silent failure.
5795 assert_eq!(DATE_FORMAT, "%Y-%m-%d");
5796 assert!(!DATE_FORMAT.contains("%H"), "a day carries no hour");
5797
5798 assert_eq!(DATETIME_FORMAT, "%Y-%m-%dT%H:%M");
5799 assert!(
5800 DATETIME_FORMAT.starts_with(DATE_FORMAT),
5801 "a moment starts with the day it is on"
5802 );
5803 // Local, and that is a property of the value rather than an omission.
5804 assert!(!DATETIME_FORMAT.contains("%Z"), "no zone name");
5805 assert!(!DATETIME_FORMAT.ends_with('Z'), "not UTC-stamped");
5806 assert!(!DATETIME_FORMAT.contains("%S"), "no seconds by default");
5807 }
5808
5809 #[test]
5810 fn a_temporal_kind_takes_a_label_above_it_and_offers_no_options() {
5811 // Neither is a checkbox and neither is a fixed set, so both fall where
5812 // text does. Asserted because a new kind lands in three predicates and
5813 // only one of them is the interesting one.
5814 for kind in [FieldKind::Date, FieldKind::DateTime] {
5815 assert!(kind.visible(), "{kind:?}");
5816 assert!(!kind.confidential(), "{kind:?}");
5817 assert!(!kind.labels_itself(), "{kind:?}");
5818 assert!(!kind.offers_options(), "{kind:?}");
5819 }
5820 }
5821
5822 #[test]
5823 fn a_cell_part_names_an_intent_and_only_the_value_is_text() {
5824 // The table half of what RowPart::intent does for rows. A cell holding
5825 // a control and a cell holding text answered alike until 0.14.0, and a
5826 // control in a cell took the cell's text colour.
5827 assert_eq!(CellPart::Value.intent(), "content");
5828
5829 for part in [CellPart::Tokens, CellPart::Actions, CellPart::Link] {
5830 // Each for its own reason -- a token carries its tone, an action is
5831 // a control, a link takes the action colour -- and all three reach
5832 // the intent inheriting already gives.
5833 assert_eq!(part.intent(), CellPart::Value.intent(), "{part:?}");
5834 }
5835 }
5836
5837 #[test]
5838 fn every_cell_part_answers_with_a_token_and_never_a_value() {
5839 for part in [
5840 CellPart::Value,
5841 CellPart::Tokens,
5842 CellPart::Actions,
5843 CellPart::Link,
5844 ] {
5845 let intent = part.intent();
5846 assert!(!intent.is_empty(), "{part:?} names nothing");
5847 assert!(!intent.starts_with('#'), "{part:?} looks like a value");
5848 }
5849 }
5850
5851 #[test]
5852 fn a_separator_is_what_tells_a_section_from_a_subsection() {
5853 assert!(Heading::Section.separated());
5854 assert!(!Heading::Subsection.separated());
5855 assert!(!Heading::Page.separated());
5856 }
5857
5858 #[test]
5859 fn a_chosen_segment_is_held_in_and_a_chosen_tab_comes_forward() {
5860 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
5861 assert_eq!(Selector::Toggle.chosen(), Depth::Well);
5862 // The exception, and the whole folder semantic: the open tab joins its
5863 // pane rather than sinking away from it.
5864 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
5865
5866 // A held-in segment is indistinguishable from a pressed raised one,
5867 // which is the economy the light model buys over a colour swap.
5868 assert_eq!(Selector::Segmented.chosen(), Depth::Raised.pressed());
5869
5870 // A toggle stands alone; the other two are built out of parts that
5871 // touch.
5872 assert!(Selector::Segmented.abutting());
5873 assert!(Selector::Tabs.abutting());
5874 assert!(!Selector::Toggle.abutting());
5875 }
5876
5877 #[test]
5878 fn columns_are_peers_and_a_split_is_not() {
5879 // The distinction the member exists for. A split's two panes stand in a
5880 // master-detail relationship; columns choose nothing about each other.
5881 // Both are flat, so depth cannot tell them apart and the doc has to.
5882 assert_eq!(Region::Columns.depth(), Depth::Flat);
5883 assert_eq!(Region::Split.depth(), Depth::Flat);
5884 assert_ne!(Region::Columns, Region::Split);
5885 }
5886
5887 #[test]
5888 fn columns_carry_no_count_and_no_share() {
5889 // The two things a board is always asked to carry and must not. How
5890 // many is what the children say; how wide is settled by "peers are
5891 // equal".
5892 //
5893 // The guard is the binding itself and it is a compile-time one: adding
5894 // a field to `Columns` stops this line compiling, which is a better
5895 // failure than any assertion about it. Written out rather than inlined
5896 // for exactly that reason.
5897 let columns: Region<'_> = Region::Columns;
5898 assert_eq!(columns.name(), None);
5899 }
5900
5901 #[test]
5902 fn columns_are_described_and_the_escape_hatch_is_still_one_member() {
5903 // A board's contents are ordinary description all the way down, so a
5904 // renderer that does not lay them across still draws every column.
5905 // Stacking them vertically is honouring this member, not degrading it.
5906 assert!(Region::Columns.described());
5907 assert!(!Region::Handover { name: "timeline" }.described());
5908 }
5909
5910 #[test]
5911 fn a_span_never_has_zero_minutes_however_it_is_asked_for() {
5912 // Every renderer divides by this. A caller passing a backwards or empty
5913 // span is a bug, but it is not a bug worth a panic three renderers deep.
5914 assert_eq!(Span::new(600, 600).length(), 1);
5915 assert_eq!(Span::new(600, 300).length(), 1);
5916 assert_eq!(Span::DAY.length(), 1440);
5917 }
5918
5919 #[test]
5920 fn a_span_can_run_past_midnight_without_a_second_date() {
5921 // 22:00 to 02:00. The alternative was carrying a date, which drags a
5922 // timezone into the vocabulary for the sake of one night shift.
5923 let overnight = Span::new(1320, 1560);
5924 assert_eq!(overnight.length(), 240);
5925 assert!(overnight.holds(1500));
5926 assert!(!overnight.holds(1200));
5927 }
5928
5929 #[test]
5930 fn overlap_is_computed_rather_than_declared() {
5931 // The reason Placement carries no `conflicts` flag: the times already
5932 // say it, and a second source for one fact is how a stale conflict
5933 // badge outlives the conflict.
5934 let morning = Placement::new(540, 60); // 09:00-10:00
5935 let overlapping = Placement::new(570, 60); // 09:30-10:30
5936 let after = Placement::new(600, 60); // 10:00-11:00
5937
5938 assert!(morning.overlaps(overlapping));
5939 assert!(overlapping.overlaps(morning), "overlap is symmetric");
5940 // Touching end to end is not overlapping: `to` is exclusive, so a
5941 // 10:00 start does not collide with a 10:00 end.
5942 assert!(!morning.overlaps(after));
5943 assert!(!after.overlaps(morning));
5944 }
5945
5946 #[test]
5947 fn a_placement_is_always_drawable() {
5948 assert_eq!(Placement::new(540, 0).length(), 1);
5949 assert_eq!(Placement::new(540, 30).end(), 570);
5950 }
5951
5952 #[test]
5953 fn a_track_places_the_fraction_every_renderer_would_otherwise_compute() {
5954 let day = Track::DAY;
5955 assert!((day.fraction(0) - 0.0).abs() < f32::EPSILON);
5956 assert!((day.fraction(720) - 0.5).abs() < f32::EPSILON);
5957 // Clamped rather than off the end: an event running past the span's
5958 // close draws at the edge, which beats panicking or drawing nowhere.
5959 assert!((day.fraction(2000) - 1.0).abs() < f32::EPSILON);
5960 }
5961
5962 #[test]
5963 fn a_track_counts_its_slots_and_never_divides_by_zero() {
5964 assert_eq!(Track::DAY.slots(), 96);
5965 assert_eq!(Track::over(Span::new(540, 1020)).slots(), 32);
5966 // A span that does not divide evenly keeps a slot for its tail.
5967 assert_eq!(Track::over(Span::new(0, 50)).slots(), 4);
5968 // slot: 0 is a caller bug that reads as one slot, not a panic.
5969 let degenerate = Track {
5970 span: Span::DAY,
5971 slot: 0,
5972 tick: 60,
5973 unit: Unit::Minutes,
5974 };
5975 assert_eq!(degenerate.slots(), 1);
5976 }
5977
5978 #[test]
5979 fn a_track_carries_facts_and_no_presentation() {
5980 // The guard on the thing the withdrawn refusal was right about. If a
5981 // pixel measure, a scroll offset or a colour ever lands on Track, the
5982 // member has stopped being a fact about the data and the timeline
5983 // really has become a component library wearing a description's name.
5984 let day = Track::DAY;
5985 assert_eq!(day.span, Span::DAY);
5986 assert_eq!(day.slot, 15);
5987 assert_eq!(day.tick, 60);
5988 assert_eq!(day.unit, Unit::Minutes);
5989
5990 // Three fields when this was written, and the fourth came here to say
5991 // why, which is the whole point of the assertion. `unit` is what the
5992 // integers COUNT -- a fact about the data, unavailable from the numbers
5993 // themselves, and the absence of it is what let a month strip render
5994 // under a wall clock. A fifth field still has to argue, and "the
5995 // renderer would find it handy" is still not the argument.
5996 // Destructured rather than rebuilt: this is the form that names every
5997 // field and stops compiling when a fifth arrives, without binding
5998 // anything a lint has to forgive.
5999 let Track {
6000 span: _,
6001 slot: _,
6002 tick: _,
6003 unit: _,
6004 } = day;
6005 }
6006
6007 #[test]
6008 fn a_day_strip_is_the_same_arithmetic_under_a_different_unit() {
6009 // The probe that found the defect, kept as a test. Fifteen days from
6010 // day three, on a thirty-one day month: the geometry was always right
6011 // and only the label was wrong, which is why `unit` is a fact and not
6012 // presentation.
6013 let march = Track::days(Span::new(0, 31));
6014 assert_eq!(march.slots(), 31);
6015 assert_eq!(march.unit, Unit::Days);
6016
6017 let leave = Placement::new(2, 15);
6018 assert!((march.fraction(leave.at()) - 2.0 / 31.0).abs() < 0.0001);
6019 assert!((march.fraction(leave.end()) - 17.0 / 31.0).abs() < 0.0001);
6020 }
6021
6022 #[test]
6023 fn a_pane_is_looked_into_and_a_band_is_not() {
6024 assert_eq!(Region::Pane.depth(), Depth::Well);
6025 assert_eq!(Region::Modal.depth(), Depth::Raised);
6026 for r in [
6027 Region::Band,
6028 Region::Sidebar,
6029 Region::Group,
6030 Region::Split,
6031 Region::TabGroup,
6032 ] {
6033 assert_eq!(r.depth(), Depth::Flat, "{r:?} should carry no edge");
6034 }
6035 }
6036
6037 #[test]
6038 fn exactly_one_region_is_opaque() {
6039 // The escape hatch is one member and stays one member. If a second
6040 // undescribed region ever appears, the description has started
6041 // conceding rather than deferring.
6042 for r in [
6043 Region::Band,
6044 Region::Sidebar,
6045 Region::Pane,
6046 Region::Group,
6047 Region::Split,
6048 Region::TabGroup,
6049 Region::Modal,
6050 // A widget is described, and that is the whole of what separates it
6051 // from a bespoke here. Both carry a name this crate never reads;
6052 // only one of them has contents under it that a renderer which does
6053 // not know the name can still walk.
6054 Region::Widget { name: "carousel" },
6055 ] {
6056 assert!(r.described(), "{r:?} should be describable");
6057 }
6058 assert!(!Region::Handover { name: "day-plan" }.described());
6059 }
6060
6061 #[test]
6062 fn a_region_nobody_converted_yet_is_not_a_region_the_app_gave_up_on() {
6063 // The whole of why this is two members. Both are opaque and neither is
6064 // described, so the old single member made them one value; a renderer
6065 // with no fill drew both as an empty box and said nothing either way.
6066 assert!(Region::Handover { name: "day-plan" }.owed());
6067 assert!(
6068 !Region::Ceded {
6069 name: "revenue-chart"
6070 }
6071 .owed()
6072 );
6073
6074 // Everything that carries its own contents owes nothing, which is the
6075 // reading a renderer needs for the members it already draws.
6076 assert!(!Region::Pane.owed());
6077 assert!(!Region::Widget { name: "carousel" }.owed());
6078
6079 // Opaqueness is the axis they still share.
6080 assert!(!Region::Ceded { name: "waveform" }.described());
6081 assert_eq!(Region::Ceded { name: "waveform" }.name(), Some("waveform"));
6082 assert_eq!(Region::Ceded { name: "waveform" }.depth(), Depth::Flat);
6083 }
6084
6085 #[test]
6086 fn a_group_contains_a_section_without_claiming_to_be_a_pane() {
6087 // The whole of why this is a member rather than a `Pane`. A pane is
6088 // looked into and scrolls; a group is neither, and four groups inside a
6089 // settings pane described as panes are four wells inside a well.
6090 assert_eq!(Region::Pane.depth(), Depth::Well);
6091 assert_eq!(Region::Group.depth(), Depth::Flat);
6092 assert_ne!(Region::Group, Region::Pane);
6093
6094 // Described, and it carries no name: a group is a primitive every
6095 // renderer draws from scratch, which is what separates it from the two
6096 // members that do carry one.
6097 assert!(Region::Group.described());
6098 assert_eq!(Region::Group.name(), None);
6099 }
6100
6101 #[test]
6102 fn a_section_heading_names_a_block_that_now_exists() {
6103 // `Heading::Section` has said "names a block within the screen" since
6104 // 0.2.0 and there was no block. The pairing is the point, and it is the
6105 // reason a group carries no heading of its own: the heading is an
6106 // ordinary node in the body, and a group without one is legal.
6107 assert!(Heading::Section.separated());
6108 assert_eq!(Region::Group.depth(), Depth::Flat);
6109 }
6110
6111 #[test]
6112 fn a_widget_inherits_its_depth_the_way_a_bespoke_does() {
6113 // Stronger than the bespoke case: a widget is drawn by whichever
6114 // renderer recognises the name, so a depth chosen here would be this
6115 // crate deciding a carousel is raised on every host.
6116 assert_eq!(Region::Widget { name: "carousel" }.depth(), Depth::Flat);
6117 assert_eq!(Region::Widget { name: "pager" }.depth(), Depth::Flat);
6118 }
6119
6120 #[test]
6121 fn a_name_is_readable_without_asking_which_member_carried_it() {
6122 // A renderer dispatching on a name wants the string, not the member.
6123 // Writing that `matches!` at each renderer is how the two drift apart.
6124 assert_eq!(Region::Widget { name: "carousel" }.name(), Some("carousel"));
6125 assert_eq!(
6126 Region::Handover { name: "day-plan" }.name(),
6127 Some("day-plan")
6128 );
6129
6130 for r in [
6131 Region::Band,
6132 Region::Sidebar,
6133 Region::Pane,
6134 Region::Group,
6135 Region::Split,
6136 Region::TabGroup,
6137 Region::Modal,
6138 ] {
6139 assert_eq!(r.name(), None, "{r:?} names nothing an app chose");
6140 }
6141 }
6142
6143 #[test]
6144 fn a_bespoke_region_inherits_its_depth_rather_than_choosing_one() {
6145 // The app owns the contents, not the placement. An app that wants its
6146 // timeline in a well frames it in a Pane.
6147 assert_eq!(Region::Handover { name: "day-plan" }.depth(), Depth::Flat);
6148 assert_eq!(Region::Handover { name: "kanban" }.depth(), Depth::Flat);
6149 }
6150
6151 #[test]
6152 fn a_screen_with_a_bespoke_region_is_still_a_whole_screen() {
6153 // The argument the member exists for: goingson's day-plan has to be
6154 // routable, or the description covers only the boring screens and the
6155 // interesting four need a second path beside the router.
6156 let day_plan = [
6157 Region::Band,
6158 Region::Handover { name: "day-plan" },
6159 Region::Sidebar,
6160 ];
6161 assert_eq!(day_plan.iter().filter(|r| r.described()).count(), 2);
6162 assert_eq!(day_plan.iter().filter(|r| !r.described()).count(), 1);
6163 }
6164
6165 #[test]
6166 fn a_secret_field_is_marked_as_one_and_a_hidden_field_is_not_drawn() {
6167 let secret = Field::new(FieldKind::Secret, "password", "Password");
6168 assert!(secret.kind.confidential());
6169 assert!(secret.kind.visible());
6170
6171 assert!(!FieldKind::Hidden.visible());
6172 // Nothing else is confidential, or the marker means nothing.
6173 for k in [
6174 FieldKind::Text,
6175 FieldKind::Number,
6176 FieldKind::Textarea,
6177 FieldKind::Rich,
6178 FieldKind::Select,
6179 FieldKind::Checkbox,
6180 FieldKind::Hidden,
6181 ] {
6182 assert!(!k.confidential(), "{k:?} should not be confidential");
6183 }
6184
6185 // Only a checkbox carries its own label.
6186 assert!(FieldKind::Checkbox.labels_itself());
6187 assert!(!FieldKind::Text.labels_itself());
6188 }
6189
6190 #[test]
6191 fn a_plain_field_offers_nothing_and_a_select_offers_its_options() {
6192 let text = Field::new(FieldKind::Text, "title", "Title");
6193 assert!(text.options.is_empty());
6194 assert_eq!(text.placeholder, None);
6195
6196 let sizes = [Choice::plain("small"), Choice::plain("large")];
6197 let select = Field::select("size", "Size", &sizes);
6198 assert_eq!(select.kind, FieldKind::Select);
6199 assert_eq!(select.options.len(), 2);
6200 }
6201
6202 #[test]
6203 fn a_choice_says_what_submits_and_what_is_read_apart() {
6204 // The whole reason it is two strings. `plain` is the case where they
6205 // coincide, and it is a shorthand rather than the general shape.
6206 let plain = Choice::plain("7");
6207 assert_eq!((plain.value, plain.label), ("7", "7"));
6208
6209 let spelled = Choice::new("7", "One week");
6210 assert_ne!(spelled.value, spelled.label);
6211 assert!(
6212 spelled.available(),
6213 "an option is pickable until it says not"
6214 );
6215 }
6216
6217 #[test]
6218 fn a_candidate_carries_the_line_that_tells_it_from_its_neighbours() {
6219 // The gap this type was born for: two candidates whose labels read
6220 // alike, told apart by the second string and by nothing else. The
6221 // measured site is the MNW tag box, where "Format" is a leaf under
6222 // audio, software, writing and video.
6223 let audio = Candidate::new("audio/format", "Format").detailed("Audio");
6224 let writing = Candidate::new("writing/format", "Format").detailed("Writing");
6225
6226 assert_eq!(audio.label, writing.label);
6227 assert_ne!(audio.detail, writing.detail);
6228 assert_ne!(
6229 audio, writing,
6230 "two rows a user cannot tell apart are two rows the type can"
6231 );
6232 }
6233
6234 #[test]
6235 fn a_candidate_is_read_differently_from_an_option_and_written_the_same() {
6236 // The ruling's own distinction, held as a test so the two types do not
6237 // drift back together. Submitting is identical; the second line is the
6238 // whole of what differs, and it is absent by default because a list of
6239 // distinct labels wants nothing there.
6240 let candidate = Candidate::plain("rust");
6241 assert_eq!((candidate.value, candidate.label), ("rust", "rust"));
6242 assert_eq!(
6243 candidate.detail, None,
6244 "one line unless the route says otherwise"
6245 );
6246
6247 let option = Choice::plain("rust");
6248 assert_eq!(
6249 (candidate.value, candidate.label),
6250 (option.value, option.label)
6251 );
6252 }
6253
6254 #[test]
6255 fn a_radio_asks_the_same_question_as_a_select_and_is_not_the_same_kind() {
6256 // Both offer a fixed set and both read `options`, so the two
6257 // constructors differ in exactly one thing. That one thing is the
6258 // point: a renderer decides whether the alternatives are readable
6259 // without opening anything, and it can only decide that if the
6260 // description said which question was asked.
6261 let styles = [
6262 Choice::new("copy", "Copy samples in"),
6263 Choice::new("reference", "Reference in place"),
6264 ];
6265 let radio = Field::radio("storage", "Storage style", &styles);
6266 let select = Field::select("storage", "Storage style", &styles);
6267
6268 assert_eq!(radio.kind, FieldKind::Radio);
6269 assert_ne!(radio.kind, select.kind);
6270 assert_eq!(radio.options, select.options);
6271 assert_eq!(
6272 Field {
6273 kind: select.kind,
6274 ..radio
6275 },
6276 select
6277 );
6278 }
6279
6280 #[test]
6281 fn an_unavailable_option_cannot_be_silent_about_it() {
6282 // The whole content of the one-member shape: saying an option is not
6283 // pickable and saying why are the same act, so the greyed-out-with-no-
6284 // reason state is unsayable rather than merely discouraged.
6285 let multi =
6286 Choice::new("multi", "Multi-sample").unless("Drop a second sample onto the keyboard.");
6287 assert!(!multi.available());
6288 assert_eq!(
6289 multi.unavailable,
6290 Some("Drop a second sample onto the keyboard.")
6291 );
6292
6293 // And the option is still in the list, carrying what it submits, so a
6294 // renderer draws it rather than the app dropping it.
6295 assert_eq!(multi.value, "multi");
6296 assert_eq!(multi.label, "Multi-sample");
6297 }
6298
6299 #[test]
6300 fn an_option_can_say_what_picking_it_means_and_why_it_cannot_be_picked() {
6301 // `5e21dcfc`. Two different sentences about one option, and an option
6302 // that has both has said two things: what the tier is, and that it is
6303 // not available yet. Folding them would be the label-folding this
6304 // member exists to end.
6305 let tier = Choice::new("24", "Small Files")
6306 .detailing("$24/mo. 2GB/file, 100GB total. Fits audio, plugins, binaries.")
6307 .unless("Sold out while the founder window is open.");
6308
6309 assert_eq!(
6310 tier.detail,
6311 Some("$24/mo. 2GB/file, 100GB total. Fits audio, plugins, binaries.")
6312 );
6313 assert_eq!(
6314 tier.unavailable,
6315 Some("Sold out while the founder window is open.")
6316 );
6317 assert!(!tier.available());
6318
6319 // Neither is implied by the other, which is what keeps a renderer from
6320 // reading a detail as a reason: an ordinary option with a second line
6321 // is still pickable.
6322 let plain = Choice::new("free", "Free").detailing("No charge. Available to everyone.");
6323 assert!(plain.available());
6324 assert_eq!(plain.detail, Some("No charge. Available to everyone."));
6325 assert_eq!(Choice::new("free", "Free").detail, None);
6326 }
6327
6328 #[test]
6329 fn a_range_carries_both_ends_and_a_validated_number_need_not() {
6330 // The distinction the kind exists for, asserted rather than only
6331 // written down: bounds are a rule for one and the control itself for
6332 // the other.
6333 let threshold = Field::range("review", "Review above", "0", "1");
6334 assert_eq!(threshold.kind, FieldKind::Range);
6335 assert!(threshold.bounded());
6336 assert_eq!(threshold.min, Some("0"));
6337 assert_eq!(threshold.max, Some("1"));
6338 // Granularity is the host's until an app says otherwise.
6339 assert_eq!(threshold.step, None);
6340
6341 // goingson's duration: a typed number with a floor, and it must not
6342 // read as a slider.
6343 let minutes = Field {
6344 min: Some("1"),
6345 ..Field::new(FieldKind::Number, "minutes", "Minutes")
6346 };
6347 assert_ne!(minutes.kind, FieldKind::Range);
6348 assert!(!minutes.bounded(), "one end is a rule, not an extent");
6349 }
6350
6351 #[test]
6352 fn a_range_described_with_one_end_says_so_rather_than_being_refused() {
6353 // Nothing here enforces the pair, for the reason nothing here enforces
6354 // `required`: the description states the constraint and the renderer
6355 // asks. What it must not do is look bounded.
6356 let half = Field {
6357 max: Some("1"),
6358 ..Field::new(FieldKind::Range, "review", "Review above")
6359 };
6360 assert!(!half.bounded());
6361 }
6362
6363 #[test]
6364 fn exactly_the_option_taking_kinds_say_so() {
6365 // The renderers branch on this rather than on a list of their own, so
6366 // a kind added without a decision here renders its options nowhere.
6367 assert!(FieldKind::Select.offers_options());
6368 assert!(FieldKind::Radio.offers_options());
6369 for kind in [
6370 FieldKind::Text,
6371 FieldKind::Secret,
6372 FieldKind::Number,
6373 FieldKind::Email,
6374 FieldKind::Url,
6375 FieldKind::Tel,
6376 FieldKind::Range,
6377 FieldKind::Textarea,
6378 FieldKind::Rich,
6379 FieldKind::Checkbox,
6380 FieldKind::Hidden,
6381 ] {
6382 assert!(!kind.offers_options(), "{kind:?} does not offer options");
6383 }
6384 }
6385
6386 #[test]
6387 fn a_radio_group_takes_a_label_even_though_its_options_carry_their_own() {
6388 // The near-miss: each option is labelled beside its own button, so a
6389 // renderer could plausibly read the group as self-labelling and drop
6390 // the question. Checkbox is the only kind that does that.
6391 assert!(!FieldKind::Radio.labels_itself());
6392 assert!(FieldKind::Checkbox.labels_itself());
6393 }
6394
6395 #[test]
6396 fn a_select_with_no_options_is_sayable() {
6397 // An app whose option list has not loaded has exactly this. Making it
6398 // unrepresentable would push the state somewhere less visible, and a
6399 // renderer drawing an empty select reports it on screen.
6400 let loading = Field::select("project", "Project", &[]);
6401 assert!(loading.options.is_empty());
6402 }
6403
6404 #[test]
6405 fn the_description_carries_the_question_and_never_the_answer() {
6406 // The line 0.8.0 drew. Placeholder and options are properties of what
6407 // is being asked; the current value is what came back, and no field
6408 // here holds one.
6409 let f = Field {
6410 placeholder: Some("yyyy-mm-dd"),
6411 ..Field::new(FieldKind::Text, "due", "Due")
6412 };
6413 assert_eq!(f.placeholder, Some("yyyy-mm-dd"));
6414 // A placeholder is not a label, and having one does not excuse the
6415 // field from carrying the other.
6416 assert_eq!(f.label, "Due");
6417 }
6418
6419 #[test]
6420 fn a_field_reports_its_own_error_state() {
6421 let mut f = Field::new(FieldKind::Text, "title", "Title");
6422 assert!(!f.invalid());
6423 f.error = Some("Required");
6424 assert!(f.invalid());
6425 }
6426
6427 #[test]
6428 fn columns_drop_by_priority_and_never_by_position() {
6429 let cols = [
6430 Column {
6431 width: Width::Fill,
6432 priority: Priority::Essential,
6433 ..Column::new("Title")
6434 },
6435 Column {
6436 width: Width::Fixed,
6437 priority: Priority::Secondary,
6438 ..Column::new("Due")
6439 },
6440 Column {
6441 width: Width::Fixed,
6442 priority: Priority::Optional,
6443 ..Column::new("Estimate")
6444 },
6445 ];
6446
6447 // Widest: everything survives.
6448 assert_eq!(
6449 cols.iter()
6450 .filter(|c| c.kept_at(Priority::Optional))
6451 .count(),
6452 3
6453 );
6454 // Narrower: the optional column goes first.
6455 let kept: Vec<_> = cols
6456 .iter()
6457 .filter(|c| c.kept_at(Priority::Secondary))
6458 .map(|c| c.name)
6459 .collect();
6460 assert_eq!(kept, ["Title", "Due"]);
6461 // Narrowest: only what identifies the row.
6462 let kept: Vec<_> = cols
6463 .iter()
6464 .filter(|c| c.kept_at(Priority::Essential))
6465 .map(|c| c.name)
6466 .collect();
6467 assert_eq!(kept, ["Title"]);
6468 }
6469
6470 #[test]
6471 fn inserting_a_column_does_not_move_what_gets_dropped() {
6472 // The bug the ordinal form has and this form cannot: goingson hides
6473 // `nth-child(n+5)` against a seven-column table, so a column inserted
6474 // anywhere to the left silently hides a different one.
6475 let before = [
6476 Column::new("Title"),
6477 Column {
6478 width: Width::Fixed,
6479 priority: Priority::Optional,
6480 ..Column::new("Estimate")
6481 },
6482 ];
6483 let after = [
6484 Column::new("Title"),
6485 Column::new("Project"), // inserted
6486 Column {
6487 width: Width::Fixed,
6488 priority: Priority::Optional,
6489 ..Column::new("Estimate")
6490 },
6491 ];
6492
6493 fn dropped<'a>(cols: &[Column<'a>]) -> Vec<&'a str> {
6494 cols.iter()
6495 .filter(|c| !c.kept_at(Priority::Secondary))
6496 .map(|c| c.name)
6497 .collect()
6498 }
6499 assert_eq!(dropped(&before), ["Estimate"]);
6500 assert_eq!(dropped(&after), ["Estimate"]);
6501 }
6502
6503 #[test]
6504 fn an_arrangement_carries_the_tab_group_as_a_modifier() {
6505 // goingson uses the tab group inside the content region rather than
6506 // instead of one, so it is not a third arrangement.
6507 let go = Arrangement::list_detail(true);
6508 let plain = Arrangement::list_detail(false);
6509 assert_ne!(go, plain);
6510 assert_ne!(go, Arrangement::sidebar_content());
6511 }
6512
6513 #[test]
6514 fn a_share_is_a_proportion_and_resolves_the_same_way_everywhere() {
6515 // The point of the member: a terminal reading columns and a webview
6516 // reading a grid honour one fact, so two hosts showing one screen agree
6517 // about its proportions.
6518 assert_eq!(Share::LIST.as_percent(), 40);
6519 assert_eq!(Share::LIST.of(100), 40);
6520 assert_eq!(
6521 Share::SIDEBAR.of(96),
6522 24,
6523 "quasi-tui's 24 columns, said as a quarter"
6524 );
6525 }
6526
6527 #[test]
6528 fn a_region_never_resolves_to_nothing() {
6529 // A region the description named should be visible. A zero-width one
6530 // reads on screen as a region that vanished, which is the hardest kind
6531 // of bug to find from what is drawn.
6532 assert_eq!(Share::percent(5).of(1), 1);
6533 assert_eq!(Share::percent(5).of(0), 1);
6534 }
6535
6536 #[test]
6537 fn a_share_outside_the_range_is_clamped_rather_than_refused() {
6538 assert_eq!(Share::percent(0), Share::percent(5));
6539 assert_eq!(Share::percent(200), Share::percent(95));
6540 }
6541
6542 #[test]
6543 fn the_share_rides_on_the_arrangement_that_knows_which_question_it_is() {
6544 // How much a sidebar takes and how much a list side takes are different
6545 // questions, and this enum is the only thing that knows which is being
6546 // asked.
6547 assert_eq!(Arrangement::sidebar_content().share(), Some(Share::SIDEBAR));
6548 assert_eq!(Arrangement::list_detail(false).share(), Some(Share::LIST));
6549 // One region divides nothing, so there is no share to answer with.
6550 assert_eq!(Arrangement::Single.share(), None);
6551 assert_eq!(
6552 Arrangement::Single.with_share(Share::percent(20)),
6553 Arrangement::Single
6554 );
6555
6556 let narrow = Arrangement::sidebar_content().with_share(Share::percent(20));
6557 assert_eq!(narrow.share(), Some(Share::percent(20)));
6558 assert!(matches!(narrow, Arrangement::SidebarContent { .. }));
6559 }
6560
6561 #[test]
6562 fn a_measure_defaults_to_the_one_53_of_69_templates_asked_for() {
6563 // The default is meaningful: a screen nobody said anything about uses
6564 // the window it was given.
6565 assert_eq!(Measure::default(), Measure::Wide);
6566 assert_eq!(Measure::Reading.as_str(), "reading");
6567 }
6568
6569 #[test]
6570 fn readiness_names_the_state_and_not_the_shimmer() {
6571 // Two members and no third. If a skeleton ever appears in this enum,
6572 // the deferral rule has been broken.
6573 assert_ne!(Readiness::Ready, Readiness::Pending);
6574 }
6575
6576 #[test]
6577 fn a_window_with_no_length_still_answers_what_it_can() {
6578 // The uncounted case is the common one, not the degenerate one: a query
6579 // that asked for 51 to learn there were more than 50 knows there are,
6580 // and not how many.
6581 let uncounted = Window::new(100, 50);
6582 assert_eq!(uncounted.index(), Some(2));
6583 assert_eq!(uncounted.windows(), None);
6584 assert!(uncounted.has_before());
6585 // Unknown length cannot rule out more, and offering a way forward that
6586 // turns out empty is the cheaper mistake.
6587 assert!(uncounted.has_after());
6588 }
6589
6590 #[test]
6591 fn a_counted_window_knows_where_it_ends() {
6592 let last = Window::new(350, 50).of(400);
6593 assert_eq!(last.index(), Some(7));
6594 assert_eq!(last.windows(), Some(8));
6595 assert!(last.has_before());
6596 assert!(!last.has_after());
6597
6598 let first = Window::new(0, 50).of(400);
6599 assert!(!first.has_before());
6600 assert!(first.has_after());
6601 }
6602
6603 #[test]
6604 fn a_window_that_does_not_divide_evenly_rounds_up() {
6605 // 401 rows in pages of 50 is eight pages and a straggler, which is nine
6606 // pages. Rounding down would make the last one unreachable.
6607 assert_eq!(Window::new(0, 50).of(401).windows(), Some(9));
6608 }
6609
6610 #[test]
6611 fn a_zero_count_answers_none_rather_than_dividing() {
6612 let empty = Window::new(0, 0).of(400);
6613 assert_eq!(empty.index(), None);
6614 assert_eq!(empty.windows(), None);
6615 // And it still clamps rather than panicking.
6616 assert_eq!(Window::new(900, 0).of(400).clamped().from, 399);
6617 }
6618
6619 #[test]
6620 fn a_window_past_the_end_clamps_inside_rather_than_vanishing() {
6621 // `Slot::current`'s reasoning, one layer down: a description pointing
6622 // past the end is a host bug, and answering it by drawing nothing
6623 // reports a region that vanished.
6624 assert_eq!(Window::new(900, 50).of(400).clamped().from, 350);
6625 // Nothing to clamp against when the length is unknown.
6626 assert_eq!(Window::new(900, 50).clamped().from, 900);
6627 }
6628
6629 #[test]
6630 fn a_carousel_frame_is_a_window_of_one() {
6631 // The shape a carousel instantiates. Same code as a paged list, which is
6632 // the whole reason `Window` exists rather than two copies of it.
6633 let third = Window::frame(2, 5);
6634 assert_eq!(third.index(), Some(2));
6635 assert_eq!(third.windows(), Some(5));
6636 assert!(third.has_before());
6637 assert!(third.has_after());
6638
6639 let last = Window::frame(4, 5);
6640 assert!(!last.has_after());
6641 }
6642
6643 #[test]
6644 fn numbered_pages_read_from_one_and_load_more_has_no_page() {
6645 // The page number is read aloud, so it is one-based; `Window::index` is
6646 // the zero-based form for indexing.
6647 let third = Paging::pages(100, 50).of(400);
6648 assert_eq!(third.page(), Some(3));
6649 assert_eq!(third.pages_total(), Some(8));
6650 assert_eq!(third.total(), Some(400));
6651 assert!(third.has_previous());
6652 assert!(third.has_more());
6653
6654 // Load-more grew a window from the start, so "page 2" would name
6655 // nothing and the type says so rather than inventing one.
6656 let grown = Paging::more(150).of(400);
6657 assert_eq!(grown.page(), None);
6658 assert_eq!(grown.pages_total(), None);
6659 assert_eq!(grown.shown(), 150);
6660 assert!(!grown.has_previous());
6661 assert!(grown.has_more());
6662 }
6663
6664 #[test]
6665 fn an_uncounted_paging_offers_forward_and_admits_no_total() {
6666 // What a host that will not pay for a COUNT describes. `None` here is
6667 // permanent: a total arriving later would widen the text that prints it,
6668 // which is the reflow "first paint is final paint" forbids.
6669 let feed = Paging::more(50);
6670 assert_eq!(feed.total(), None);
6671 assert_eq!(feed.pages_total(), None);
6672 assert_eq!(feed.remaining(), None);
6673 assert!(feed.has_more());
6674 }
6675
6676 #[test]
6677 fn what_is_left_is_derived_and_never_underflows() {
6678 assert_eq!(Paging::more(150).of(400).remaining(), Some(250));
6679 assert_eq!(Paging::pages(350, 50).of(400).remaining(), Some(0));
6680 // A host that overshot its own total gets zero rather than a wrapped
6681 // usize, which would print as "18446744073709551516 remaining".
6682 assert_eq!(Paging::more(500).of(400).remaining(), Some(0));
6683 }
6684
6685 #[test]
6686 fn a_fallback_is_authored_and_a_group_cannot_omit_it() {
6687 // No `Default`. The compiler is what enforces rule 2, so the assertion
6688 // that matters is one this file cannot write; what it can say is that
6689 // the four authored answers are distinct and none is privileged.
6690 let all = [
6691 Fallback::Wrap,
6692 Fallback::Stack,
6693 Fallback::Shed,
6694 Fallback::Menu,
6695 ];
6696 for (i, a) in all.iter().enumerate() {
6697 for b in &all[i + 1..] {
6698 assert_ne!(a, b);
6699 }
6700 }
6701 }
6702
6703 #[test]
6704 fn shedding_stops_at_essential_whatever_the_group_holds() {
6705 // Priority is read the same way for a group member as for a column,
6706 // which is the whole claim of generalising it off `Column`.
6707 let members = [
6708 ("tabs", Priority::Essential),
6709 ("search", Priority::Secondary),
6710 ("count", Priority::Optional),
6711 ];
6712 let kept: Vec<_> = members
6713 .iter()
6714 .filter(|(_, p)| *p >= Priority::Essential)
6715 .map(|(n, _)| *n)
6716 .collect();
6717 assert_eq!(kept, ["tabs"]);
6718 }
6719
6720 #[test]
6721 fn a_role_says_what_a_part_is_worth_when_the_run_does_not_fit() {
6722 // The row still identifies itself after everything droppable has gone,
6723 // which is the property the ladder exists for.
6724 assert_eq!(RowPart::Primary.priority(), Priority::Essential);
6725 // A control is not a fact. Room comes out of what the row says, never
6726 // out of what it offers.
6727 assert_eq!(RowPart::Actions.priority(), Priority::Essential);
6728 assert_eq!(RowPart::Meta.priority(), Priority::Optional);
6729 assert_eq!(RowPart::Proportion.priority(), Priority::Optional);
6730 assert_eq!(RowPart::Secondary.priority(), Priority::Secondary);
6731 // Tokens sit in the middle deliberately: a toned badge is often the
6732 // most scannable thing in a row, so it does not go first.
6733 assert_eq!(RowPart::Tokens.priority(), Priority::Secondary);
6734 }
6735
6736 #[test]
6737 fn a_run_is_one_line_unless_the_description_says_two() {
6738 // The default is what every part did before flows existed, so a
6739 // description written against the old vocabulary keeps its rendering.
6740 assert_eq!(Flow::default(), Flow::Tight);
6741 assert_eq!(Flow::Tight.lines(), 1);
6742 assert_eq!(Flow::Relaxed.lines(), 2);
6743 }
6744
6745 #[test]
6746 fn an_unknown_flow_reads_as_one_line() {
6747 // `#[non_exhaustive]`'s cost, taken deliberately. A tier added upstream
6748 // reaches an old renderer as one line rather than as a build break, and
6749 // one line is the reading that cannot break a neighbour's layout. The
6750 // match in `lines` is what this holds; it fails if a new tier is given
6751 // an arm that returns something unbounded.
6752 for flow in [Flow::Tight, Flow::Relaxed] {
6753 assert!((1..=2).contains(&flow.lines()));
6754 }
6755 }
6756
6757 #[test]
6758 fn an_awaiting_mark_is_indeterminate_until_something_is_measured() {
6759 // The default is the common case: a call waits, and nothing about it is
6760 // countable. A determinate bar is the exception and says so.
6761 assert_eq!(Awaiting::default(), Awaiting::unmeasured());
6762 assert!(!Awaiting::unmeasured().is_determinate());
6763 assert!(Awaiting::of(40 * 1024 * 1024).is_determinate());
6764 assert_eq!(Awaiting::of(7).amount, Some(7));
6765 }
6766
6767 // A slider is a fraction and a mapping
6768 //
6769 // `Curve` is the one thing in this crate that computes rather than
6770 // describes, and it does so because four renderers would otherwise each
6771 // write these two formulas and drift. So the formulas are pinned here.
6772
6773 /// The bounds of audiofiles' envelope attack, the curve's first consumer.
6774 const ATTACK: (f64, f64) = (0.001, 5.0);
6775
6776 #[test]
6777 fn a_curve_is_linear_with_no_step_until_a_field_says_otherwise() {
6778 assert_eq!(Curve::default(), Curve::Linear { step: None });
6779 let plain = Field::range("t", "T", "0", "1");
6780 assert_eq!(plain.curve, Curve::Linear { step: None });
6781 assert_eq!(plain.curve.step(), None);
6782 }
6783
6784 #[test]
6785 fn every_curve_carries_its_own_granularity() {
6786 assert_eq!(Curve::Linear { step: Some("0.01") }.step(), Some("0.01"));
6787 assert_eq!(
6788 Curve::Logarithmic {
6789 step: Some("0.001")
6790 }
6791 .step(),
6792 Some("0.001")
6793 );
6794 }
6795
6796 #[test]
6797 fn both_ends_of_the_track_are_the_bounds_under_either_curve() {
6798 // `min` and `max` are `f(0)` and `f(1)`. That is the whole reframe, and
6799 // it has to hold for a mapping that is not the identity or the bounds
6800 // have stopped meaning what the field says they mean.
6801 let (min, max) = ATTACK;
6802 for curve in [
6803 Curve::Linear { step: None },
6804 Curve::Logarithmic { step: None },
6805 ] {
6806 assert!((curve.value_at(0.0, min, max) - min).abs() < 1e-12);
6807 assert!((curve.value_at(1.0, min, max) - max).abs() < 1e-12);
6808 }
6809 }
6810
6811 #[test]
6812 fn a_linear_midpoint_is_the_average_and_a_ratio_midpoint_is_the_geometric_mean() {
6813 let (min, max) = ATTACK;
6814 let linear = Curve::Linear { step: None }.value_at(0.5, min, max);
6815 assert!((linear - 2.5005).abs() < 1e-9);
6816
6817 // The reason the envelope is not linear: half way along a log track is
6818 // 70 ms, and half way along a linear one is 2.5 seconds. Every attack a
6819 // sampler is actually played with lives below the first.
6820 let ratio = Curve::Logarithmic { step: None }.value_at(0.5, min, max);
6821 assert!((ratio - (min * max).sqrt()).abs() < 1e-12);
6822 assert!(ratio < 0.08);
6823 }
6824
6825 #[test]
6826 fn a_position_and_a_value_round_trip_under_either_curve() {
6827 let (min, max) = ATTACK;
6828 for curve in [
6829 Curve::Linear { step: None },
6830 Curve::Logarithmic { step: None },
6831 ] {
6832 for position in [0.0, 0.1, 0.25, 0.5, 0.75, 0.99, 1.0] {
6833 let back = curve.position_of(curve.value_at(position, min, max), min, max);
6834 assert!(
6835 (back - position).abs() < 1e-9,
6836 "{curve:?} lost {position} (got {back})"
6837 );
6838 }
6839 }
6840 }
6841
6842 #[test]
6843 fn a_ratio_curve_across_zero_is_drawn_linearly_rather_than_refused() {
6844 // An envelope's sustain is a 0-to-1 level. A constant ratio is
6845 // undefined there, and the answer is the linear mapping rather than a
6846 // NaN reaching a renderer that would paint it.
6847 let curve = Curve::Logarithmic { step: None };
6848 assert!(!curve.is_ratio(0.0, 1.0));
6849 assert!((curve.value_at(0.5, 0.0, 1.0) - 0.5).abs() < 1e-12);
6850 assert!(curve.value_at(0.5, -96.0, -20.0).is_finite());
6851 assert!(curve.is_ratio(ATTACK.0, ATTACK.1));
6852 }
6853
6854 #[test]
6855 fn a_track_with_no_extent_has_one_value_on_it() {
6856 for curve in [
6857 Curve::Linear { step: None },
6858 Curve::Logarithmic { step: None },
6859 ] {
6860 assert!((curve.value_at(0.7, 4.0, 4.0) - 4.0).abs() < f64::EPSILON);
6861 assert!(curve.position_of(4.0, 4.0, 4.0).abs() < f64::EPSILON);
6862 // Inverted bounds are the same degenerate answer, not a negative
6863 // extent a renderer would draw backwards.
6864 assert!((curve.value_at(0.7, 9.0, 2.0) - 9.0).abs() < f64::EPSILON);
6865 }
6866 }
6867
6868 #[test]
6869 fn a_position_or_a_value_outside_the_track_is_clamped_to_it() {
6870 let (min, max) = ATTACK;
6871 let curve = Curve::Logarithmic { step: None };
6872 assert!((curve.value_at(-3.0, min, max) - min).abs() < 1e-12);
6873 assert!((curve.value_at(4.0, min, max) - max).abs() < 1e-12);
6874 assert!(curve.position_of(0.0, min, max).abs() < 1e-12);
6875 assert!((curve.position_of(500.0, min, max) - 1.0).abs() < 1e-12);
6876 }
6877
6878 #[test]
6879 fn a_typed_number_keeps_its_own_step_and_a_range_reads_its_curve() {
6880 // The split the 0.32.0 narrowing is: two granularities that were one
6881 // member, and the kinds that take them do not overlap.
6882 let typed = Field {
6883 step: Some("5"),
6884 ..Field::new(FieldKind::Number, "port", "Port")
6885 };
6886 assert_eq!(typed.step, Some("5"));
6887
6888 let slid = Field {
6889 curve: Curve::Logarithmic {
6890 step: Some("0.001"),
6891 },
6892 ..Field::range("attack", "Attack", "0.001", "5")
6893 };
6894 assert_eq!(slid.step, None);
6895 assert_eq!(slid.curve.step(), Some("0.001"));
6896 }
6897
6898 #[test]
6899 fn a_theme_picker_offers_themes_and_no_options() {
6900 // The substitution hazard the constructor exists against: `options` is
6901 // right there and reads as if it would work, and a renderer walking it
6902 // for a theme picker draws an empty control.
6903 let themes = [
6904 ThemeChoice::new("goingson", "GoingsOn", ThemeVariant::Light, Contrast::High),
6905 ThemeChoice::new("dracula", "Dracula", ThemeVariant::Dark, Contrast::Standard),
6906 ];
6907 let field = Field::theme("theme", "Theme", &themes);
6908
6909 assert_eq!(field.kind, FieldKind::Theme);
6910 assert!(field.kind.offers_themes());
6911 assert!(!field.kind.offers_options());
6912 assert_eq!(field.themes.len(), 2);
6913 assert!(field.options.is_empty());
6914 assert_eq!(field.follows, None);
6915 }
6916
6917 #[test]
6918 fn following_carries_the_store_s_own_spelling() {
6919 // Not hardcoded here: the value belongs to the app's config table, and
6920 // this crate holds no facts about somebody else's store.
6921 let field =
6922 Field::theme("theme", "Theme", &[]).following(Choice::new("system", "Follow System"));
6923 let follow = field.follows.expect("the row was offered");
6924 assert_eq!(follow.value, "system");
6925 assert_eq!(follow.label, "Follow System");
6926 }
6927
6928 #[test]
6929 fn a_picker_with_nothing_resolved_is_sayable() {
6930 // A machine whose theme directories hold nothing. The description is
6931 // true and a renderer says so on screen rather than in a log, which is
6932 // `Field::options`' own arrangement.
6933 let field = Field::theme("theme", "Theme", &[]);
6934 assert!(field.themes.is_empty());
6935 }
6936
6937 #[test]
6938 fn every_kind_but_theme_offers_no_themes() {
6939 for kind in [
6940 FieldKind::Text,
6941 FieldKind::Select,
6942 FieldKind::Radio,
6943 FieldKind::Checkbox,
6944 FieldKind::File,
6945 FieldKind::Hidden,
6946 ] {
6947 assert!(
6948 !kind.offers_themes(),
6949 "{kind:?} does not read Field::themes"
6950 );
6951 }
6952 }
6953
6954 #[test]
6955 fn a_contrast_tier_reads_worst_first() {
6956 // Matches `makeover::ContrastTier`, so an adopter's conversion cannot
6957 // invert an ordering by accident and a sort agrees across the seam.
6958 assert!(Contrast::Low < Contrast::Standard);
6959 assert!(Contrast::Standard < Contrast::High);
6960 }
6961
6962 #[test]
6963 fn the_groups_and_badges_have_one_spelling_each() {
6964 // The whole argument for these living here: three renderers picking
6965 // their own is one picker reading three ways.
6966 assert_eq!(ThemeVariant::Light.heading(), "Light");
6967 assert_eq!(ThemeVariant::Dark.heading(), "Dark");
6968 assert_eq!(ThemeVariant::HighContrast.heading(), "High Contrast");
6969
6970 assert_eq!(ThemeVariant::HighContrast.as_str(), "high-contrast");
6971
6972 assert_eq!(Contrast::High.badge(), "AA");
6973 assert_eq!(Contrast::Standard.badge(), "OK");
6974 assert_eq!(Contrast::Low.badge(), "low");
6975 }
6976
6977 #[test]
6978 fn the_variant_spelling_matches_the_theme_file_s_own() {
6979 // The seam this enum is duplicated across. `makeover::parse_meta` reads
6980 // `meta.variant` as one of these three strings; a rename on either side
6981 // that does not move together silently regroups every picker.
6982 for (variant, spelling) in [
6983 (ThemeVariant::Light, "light"),
6984 (ThemeVariant::Dark, "dark"),
6985 (ThemeVariant::HighContrast, "high-contrast"),
6986 ] {
6987 assert_eq!(variant.as_str(), spelling);
6988 assert_eq!(variant.to_string(), spelling);
6989 }
6990 }
6991 }
6992