Skip to main content

makeover_webview/
lib.rs

1//! The webview renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-webview -->
4//!
5//! # The renderer that needs no palette
6//!
7//! `makeover-immediate` and `makeover-tui` both take a `Palette`, because egui
8//! and a terminal need an actual colour before they can put anything on
9//! screen. A webview does not: `var(--surface-raised)` *is* the late binding,
10//! and the browser resolves it against whatever `themes.js` last wrote onto
11//! `:root`.
12//!
13//! So this crate emits text naming intents, and never learns a colour. It is
14//! the deferral rule with no adapter in the way, and it is why the webview was
15//! always the wrong renderer to derive a vocabulary from: it can express
16//! anything, so it never pushes back.
17//!
18//! # Phase A: the stylesheet
19//!
20//! This module emits component CSS and no markup, deliberately. GoingsOn has
21//! 145 `innerHTML` sites and Balanced Breakfast 175 `createElement` sites, so
22//! moving markup is a migration where adopting a generated stylesheet is not.
23//! The apps keep every line of their markup and gain the classes.
24//!
25//! It is not a deletion either, which this header claimed until the measurement
26//! came in. Adoption across goingson removed 49 declarations net and *added* 25
27//! lines: a rule loses its depth declarations and gains a variant selector next
28//! to it, so the file stays the same size. What phase A moves is where depth is
29//! defined, not how much CSS exists. Numbers and method in the wiki note under
30//! "The deletion test, run".
31//!
32//! The bevel properties are byte-identical to what both apps already
33//! hand-write, which is asserted below.
34//!
35//! # Phase B: the markup, one description at a time
36//!
37//! [`form`] renders [`makeover_layout::Field`], which is the half of phase B
38//! whose description is settled. It emits strings, because both apps
39//! interpolate their fields into larger string-built forms and returning nodes
40//! would rewrite those too. It owns its own escaping, on the reasoning in that
41//! module: a Rust encoder can cover element text and attribute values with one
42//! function, where the apps need four and have to choose correctly at every
43//! call site.
44//!
45//! [`facet`] renders `makeover_layout::Facet`: a dimension a set is narrowed by,
46//! and the one phase-B emitter whose markup an app is not keeping, because the
47//! markup it replaces was two mechanisms rather than one. A tag's selection and
48//! a tag's browse position were separate state on MNW's discover page, which is
49//! why every filter row there carries a tick box *and* a chevron; one gesture
50//! doing both is what lets the second one go.
51//!
52//! [`list`] is the other half: column tracks, the narrowing rules, and the cell
53//! containers a row is made of. It stops at the cell boundary and does not
54//! render what goes inside one, on the reasoning in that module. So phase B is
55//! now the frame around content in both directions, and what an app still owns
56//! is the content itself.
57//!
58//! # What phase A settled, and what it costs
59//!
60//! Decided 2026-07-29 against goingson's `styles.css` rather than against a
61//! component list. The useful finding there was that `.btn` (line 644),
62//! `.card` (768) and `.tag, .badge` (882) each hand-write the same
63//! composition, so three quarters of phase A is one rule with several names.
64//!
65//! Two of the four decisions change how goingson looks, and adoption should
66//! not be described as a pure deletion:
67//!
68//! - **Pressed carries its fill.** [`interactive_rules`] emits
69//!   [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
70//!   will press to `--surface-well`, and hovers to `--surface-overlay` today
71//!   and will hover to `--hover-surface`. Since `surface-well` inverts by theme
72//!   where `surface-sunken` does not, a dark theme presses *lighter* than it
73//!   hovers. That falls out of `makeover`'s own derivation, which says outright
74//!   that `surface-sunken` cannot serve as a well, so if it reads wrong the
75//!   answer is there and not here.
76//! - **Badges go flat.** See [`token_rules`].
77//!
78//! The other two: the progress trough is renderer-local and the scrollbar
79//! track was dropped ([`component_rules`]), and no class prefix ships by
80//! default, so adoption means deleting the app's hand-written rule in the same
81//! commit that adds the generated one. `.card`, `.badge` and the tab classes
82//! all already exist in goingson, and while both rules exist the cascade order
83//! decides which wins. That is the one real risk in adopting this, and it is
84//! why the migration lands per component rather than in one commit.
85//!
86//! # 0.10.0: the states this crate used to leave to its consumers
87//!
88//! [`interactive_rules`] emitted hover and pressed and stopped, because
89//! `makeover-layout` modelled no interaction state. Focus and disabled were
90//! therefore unsayable, and every app completed the primitive from outside the
91//! only way that works: by out-specifying a rule it does not own. goingson
92//! carries 19 such rules and the MNW server 21, and the three focus rings do
93//! not match each other.
94//!
95//! That also blocked the cascade-layer work outright. An app that declares
96//! `@layer` puts its own rules in a named layer, and unlayered declarations
97//! outrank every named layer regardless of specificity, so all of those
98//! overrides lose in the commit that adopts layers. They cannot simply be
99//! deleted, because they are the only thing supplying the missing states.
100//! Emitting the states here is what turns that adoption into a deletion.
101//!
102//! Four states now, in emission order, and the order is load-bearing: they are
103//! all specificity (0,2,0), so disabled beats hover by coming last and by
104//! nothing else. Nothing here reaches for `:not(:disabled)`, which would raise
105//! a selector this crate will shortly be wrapping in its own layer.
106//!
107//! Hover additionally sits inside a capability query now. `makeover-touch`
108//! answers whether a fingertip has hover and `makeover-geometry` spells the
109//! condition; this crate asks and does not decide. goingson's section 60 exists
110//! solely to take the hover state back on touch, which is a fight it should
111//! never have been handed.
112//!
113//! # 0.11.0: the layer contract
114//!
115//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
116//! lives in `makeover-geometry` because that is the one crate every CSS emitter
117//! in the family already depends on). `makeover-geometry` 0.6.0 does the same
118//! for `geometry.css`.
119//!
120//! The cascade resolves origin and importance, then layer, then specificity,
121//! then source order, and **unlayered normal declarations outrank every named
122//! layer**. So before this, an app that declared `@layer base, components,
123//! responsive` put every rule it owns into a named layer and lost all of them to
124//! this unlayered file, regardless of specificity and regardless of loading
125//! last. Nothing errors when that happens: the CSS is valid, the minifier is
126//! happy, and buttons and badges look subtly wrong.
127//!
128//! That is why the layer belongs here rather than in each app. An app cannot fix
129//! it from its own stylesheet, because the fix is to layer the file it does not
130//! own.
131//!
132//! **What it flips**, and the reason each app wants a look when it bumps the
133//! pin: a generated rule that currently beats an app rule by being more specific
134//! stops beating it. The direction is always "the app wins", which is what the
135//! apps already assume, but a hand-written rule an app thought was dead can come
136//! back to life.
137//!
138//! An app should declare the order once, or the layer's position is decided by
139//! whichever generated file the browser happens to see first:
140//!
141//! ```css
142//! @layer makeover, base, components, responsive;
143//! ```
144//!
145//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
146//! from this crate's pieces. goingson builds `tables.css` in its own `build.rs`
147//! out of [`list::narrowing_css`] and [`list::grid_template_columns`], and those
148//! rules are as generated as the ones here, so they belong in the same layer and
149//! this crate cannot put them there on the app's behalf.
150//!
151//! # 0.12.0: the ring gets its own width
152//!
153//! [`focus_rule`] reused [`Emit::border_width`] and emitted a 1px ring. That was
154//! an implementation convenience dressed as consistency with the invalid-field
155//! ring: a bevel and a focus indicator answer different questions, and only one
156//! of them has to be noticed from across a desk.
157//!
158//! Caught while adopting 0.11.0 into goingson, by the check the adoption tasks
159//! ask for. Every consumer had already written its own ring and all three chose
160//! at least 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
161//! goingson 2px on three rules and 3px on the one covering twelve selectors. The
162//! design system was the only thing in the tree saying 1px, so deleting the app
163//! rules in favour of it would have thinned the focus indicator everywhere.
164//!
165//! [`Emit::focus_width`] now carries it, defaulting to `2px`, and the offset is
166//! the same magnitude with its sign off the depth. Both values are the measured
167//! consensus rather than a new opinion.
168//!
169//! # 0.57.0: a suggestion's second line, in place of a reason it cannot be picked
170//!
171//! `1fcf2e9b`, ruled by Max 2026-08-21. `Outcome::Suggestions` now carries
172//! `Candidate` rather than `Choice`, and a candidate has no `unavailable`: a
173//! suggestion that cannot be picked is a row a route should not have offered.
174//! What it has instead is a `detail`, the line that tells it from a row reading
175//! the same -- "Format" under audio, software, writing and video.
176//!
177//! So `.form-suggestion-why` is gone and `.form-suggestion-detail` is here, and
178//! the difference is not only the name. `why` was drawn in the disabled token,
179//! which said the row was refusing. A detail orients rather than refuses, so it
180//! is `--content-muted`, which is what every other secondary line in this crate
181//! reads as.
182//!
183//! No consumer is affected: the only emitter is `quasi-webview`, which moves in
184//! the same cascade.
185//!
186//! # 0.56.0: an interval, as the group MNW already wrote by hand
187//!
188//! [`makeover_layout::FieldKind::Interval`] emits a `role="group"` named by the
189//! field's label, holding one `<input type="number">` per end. That is not a
190//! shape invented here: MNW's discover sidebar has a `role="group"` with
191//! `aria-labelledby` over `min_price` and `max_price` today, written by hand
192//! because nothing in the description could say the two boxes were one
193//! question. The markup is what the measurement found, and this emits it.
194//!
195//! - **The group carries the error and the descriptions**, on the split
196//!   [`makeover_layout::FieldKind::Radio`] already uses here: what is wrong is
197//!   the answer, and a crossed interval is not the fault of either end.
198//! - **Both boxes take the whole extent.** `min`, `max` and `step` describe the
199//!   axis, so they are written twice. The crossing rule is not emitted, because
200//!   HTML has no attribute for it and the description does not carry it: it
201//!   comes back as an error on the group, like every other refusal.
202//! - **Which end is which is `aria-label` and nothing more.** The description
203//!   states direction structurally, by which member holds which name, and never
204//!   in words. Visible Min and Max captions are a page's own and reach the
205//!   group through [`form::Filling::trailing`].
206//!
207//! [`form::Value::Between`] is the second value. A separator inside one string
208//! would have made this crate the owner of a delimiter that either end could
209//! contain.
210//!
211//! # 0.55.0: a number's unit, as adjacent text
212//!
213//! `makeover-layout` 0.33.0's `Field::unit`. HTML has no unit attribute and
214//! inventing one would be markup nothing reads, so it is a `<span>` after the
215//! control -- and it is named in `aria-describedby` rather than left as
216//! decoration, because a number and what it is measured in are one fact and
217//! reading the first without the second is reading it wrong.
218//!
219//! This is the renderer the member costs something. egui already had somewhere
220//! better than the label to put a unit; here the two placements are equally
221//! adjacent, and what is bought is that the unit is a value a consumer can read
222//! back rather than a suffix on a label it would have to parse.
223//!
224//! # 0.54.0: a curve this renderer can carry, and one it cannot
225//!
226//! `makeover-layout` 0.32.0's `Curve`. A range takes its granularity from the
227//! curve now (`Field::curve.step()`), every other kind keeps `Field::step`, and
228//! `Curve::Linear` emits exactly what it emitted before.
229//!
230//! **A constant-ratio curve still emits a linear track, and that is a
231//! shortfall rather than a decision.** HTML has no logarithmic range input, so
232//! honouring one here means either shipping JS that maps the thumb position to
233//! a value -- renderer-side app code, which is the thing this stack exists to
234//! delete -- or changing what the control submits from a value to a fraction,
235//! and then something has to map it on the way back in. That something is not
236//! this crate: the MNW server reads these forms with its own handlers, so a
237//! fraction arriving where a value is expected would be silent. Filed rather
238//! than guessed at.
239//!
240//! What is not lost: the extent, the granularity, and the value's own units.
241//! What is lost is resolution at the small end, which is exactly the reason an
242//! app asked for a ratio in the first place. No consumer is affected today --
243//! every described range on this path is linear.
244//!
245//! # 0.52.0: a markdown field gets the preview it was permitted
246//!
247//! 0.50.0 marked a [`makeover_layout::FieldKind::Rich`] field with
248//! `data-format="markdown"` and stopped there, and nothing read the mark: no
249//! rule, no markup, no selector anywhere in the tree. So a described editor was
250//! a plain textarea carrying an attribute, and MNW converting its four
251//! hand-written section editors onto the member would have *lost* the
252//! Write/Preview pair one of them already has. A permission taken and not spent
253//! turns every conversion into a regression.
254//!
255//! [`form::editor_rules`] and the chrome beside it are the spending. The pair is
256//! a segmented control, so it takes the depth, the focus ring and the chosen
257//! state from rules that already existed; the preview pane is a well, because it
258//! stands where the control stood. Both are gated on the attribute rather than
259//! on a class, which is what the attribute was for.
260//!
261//! **This crate still renders no markdown.** The pane arrives empty and is
262//! filled by whatever binds the editor, which is where the host's sanitiser
263//! already is. A converter here would have moved that guarantee into a crate
264//! with no view of the host's content-security posture.
265//!
266//! # 0.47.0: a range, a chooser's ghost text, and an option that cannot be
267//! picked yet
268//!
269//! `makeover-layout` 0.28.0's three form findings, all of them cheap here and
270//! none of them cheap in the app that found them.
271//!
272//! - `FieldKind::Range` emits `<input type="range">`, and `Field::step` emits
273//!   `step`. The step is emitted only when the description carries one: the
274//!   browser's own default is `step="1"`, which is what a description means by
275//!   saying nothing, and is also what turns a 0-to-1 threshold into a
276//!   two-position control.
277//! - A select with nothing chosen emits a disabled, selected, valueless first
278//!   option carrying `Field::placeholder`. HTML has no placeholder attribute on
279//!   `<select>`; this is the idiom, and `required` keeps working through it
280//!   because the option's value is empty.
281//! - `Choice::unavailable` emits `disabled` plus the reason. Where it goes
282//!   differs by control and the difference is forced: a radio group gets a
283//!   `.form-option-reason` span beside the label, and a `<select>` option has
284//!   room for no element at all, so the reason runs into its text.
285//!
286//! # 0.25.0: a cell says what it holds
287//!
288//! 0.23.0 gave a table its layout and left every cell the same. One `.cell`
289//! carried the whole thing, so a cell holding text and a cell holding a button
290//! were one class and one content colour, and a control in a cell was painted
291//! as text. That is the drift [`RowPart::intent`](makeover_layout::RowPart)
292//! has prevented for list rows since 0.2.0 and prevented for nothing here.
293//!
294//! makeover-layout 0.14.0's [`CellPart`](makeover_layout::CellPart) names the
295//! four things a cell holds, and [`table_rules`] turns them into
296//! `.cell-value`, `.cell-tokens`, `.cell-actions` and `.cell-link`. Only the
297//! first takes a colour: a token carries its own tone, an action is a control
298//! rather than text, and a link takes the action colour from the anchor it is.
299//!
300//! The colour going on `.cell-value` rather than on `.cell` is the fix rather
301//! than an implementation detail. On the container it cascades into the parts
302//! that are not text, which is the bug said in one rule.
303//!
304//! [`list::Cell::part`] is `Option<CellPart>` here, where it was
305//! `Option<RowPart>`. A table cell borrowing the list row's vocabulary was the
306//! drift with a type on it: the two answer different questions, and only one of
307//! them was ever about a cell.
308//!
309//! # 0.23.0: a table lays itself out, and a row shows its controls
310//!
311//! Three things a description could say and this renderer had no rule for,
312//! found together by rendering the MNW server's SSH-keys settings tab through
313//! `quasi` and preferring the hand-written Askama original.
314//!
315//! **A table had no layout at all.** [`list::narrowing_css`] emits the track
316//! list, and it has to be called with the columns, so it works where the
317//! columns are known at build time: goingson builds `tables.css` in its own
318//! `build.rs` and is untouched. A table a description produced knows its
319//! columns at render time, and the rules would have had to travel with the
320//! markup: a `<style>` element per table, which needs `style-src
321//! 'unsafe-inline'` that the MNW server is working to drop, or the head, which
322//! an htmx fragment swap does not carry. [`table_rules`] lays a table out with
323//! `display: table` instead, which aligns columns across rows knowing nothing
324//! about how many there are. [`Priority`](makeover_layout::Priority) hiding
325//! moves from a generated rule per dropped column to one rule per drop class,
326//! and [`list::column_classes`] is what puts those classes on a cell. A header
327//! row emitted by a renderer's own code should call it too, or the header and
328//! the body disagree about which column just dropped.
329//!
330//! **A destructive button had nowhere for its tone to land.** `.button` carried
331//! no tone, on the reading that a control's colour is its surface. Every
332//! consumer had written the danger rule itself. It joins the badge in taking
333//! the four tones as colour, off `data-tone`.
334//!
335//! **A list rendered as a bulleted list**, because nothing here reset the `ul`
336//! a renderer emits for one.
337//!
338//! `RowPart::revealed_on_hover` also stops being honoured, which its own doc
339//! sanctioned: a renderer decides. It was retired outright in makeover-layout
340//! 0.13.0, once this had been its only consumer for a release. The rule hid a
341//! row's actions until hover,
342//! and every escape it grew was a report that hiding was wrong for somebody:
343//! `focus-within` for the keyboard, the capability gate for a fingertip with no
344//! way to unhide. What survived hid the controls from pointer users alone, who
345//! are the ones scanning a list to learn what can be done to a row.
346//!
347//! # 0.17.0: the depth classes stop being controls
348//!
349//! [`depth_rules`] gave `.raised` the whole interactive set. A depth is a
350//! statement about shape, so that left the vocabulary with no raised surface
351//! that is merely an object, and an app wanting one had two moves: write its
352//! own class from tokens, or take a control class and cancel the control half.
353//! goingson took the second, in three variants over sixteen elements
354//! (`.card--static` at 14 call sites, `.card--muted` at 2, `.card--shell` at 1),
355//! each re-asserting the resting fill and bevel on `:hover` and `:active`.
356//!
357//! Measured before changing it: `.raised` is emitted into goingson, Balanced
358//! Breakfast and the MNW server, and none of the three has a single call site.
359//! The states were unasked-for everywhere at once, and dropping them costs no
360//! migration anywhere.
361//!
362//! `.card` and `.button` are unchanged. They are the same depth *and* controls,
363//! and they take their states from [`surface_rules`], which is where a state
364//! belongs: on the thing that claims to answer a pointer.
365//!
366//! # Substitution, three ways
367//!
368//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
369//! answers that differently, which is the evidence that dropping
370//! `Fill::fallback` from the description was right:
371//!
372//! - `makeover-immediate` substitutes the page in Rust.
373//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
374//!   terminal would quantise the two together.
375//! - here, CSS already has the mechanism: `var(--surface-well,
376//!   var(--surface-page))` falls back in the browser, and nothing in Rust
377//!   decides anything.
378
379#![forbid(unsafe_code)]
380
381pub mod facet;
382pub mod figure;
383pub mod form;
384pub mod list;
385pub mod meter;
386pub mod placeholder;
387pub mod vocabulary;
388
389/// A render of every emitter, scraped for the classes it wrote.
390///
391/// Test-only, and the guard behind [`vocabulary::names`]. See the module's own
392/// header for why the check renders rather than reads the source.
393#[cfg(test)]
394mod corpus;
395
396use crate::list::{cell_part_class, part_class};
397use makeover_geometry::{Density, SizeClass};
398// Re-exported rather than redefined. An app assembling its own stylesheet out
399// of this crate's pieces needs the same layer name, and most such apps depend
400// on this crate and not on `makeover-geometry` directly: goingson builds
401// `tables.css` in its own build.rs from [`list::narrowing_css`], and those
402// rules are as generated as the ones here.
403pub use makeover_geometry::{CSS_LAYER, in_css_layer};
404use makeover_layout::{
405    Bevel, CellPart, Depth, Fallback, Fill, Flow, Intent, RowPart, Selector, Sort, State, Token,
406    Tone,
407};
408use makeover_touch::Affordance;
409use std::fmt::Write as _;
410
411/// How the emitted CSS is shaped.
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
413pub struct Emit {
414    /// Bevel thickness, as a CSS length.
415    ///
416    /// A value, so it arrives from the caller: border widths belong to
417    /// `makeover-geometry` and will come from there once it carries them.
418    pub border_width: &'static str,
419    /// Focus ring thickness, as a CSS length.
420    ///
421    /// Separate from [`border_width`](Self::border_width), which it reused
422    /// until 0.12.0. That reuse was an implementation convenience dressed as
423    /// consistency, and it emitted a 1px ring: a bevel and a focus indicator
424    /// are answering different questions, and only one of them has to be
425    /// noticed from across a desk.
426    ///
427    /// The default is the measured consensus rather than a new opinion. Every
428    /// consumer had already written its own ring and all three chose at least
429    /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
430    /// goingson 2px on three rules and 3px on the one covering twelve
431    /// selectors. The design system was the only thing in the tree saying 1px.
432    pub focus_width: &'static str,
433    /// Prefix for emitted class names, without the leading dot.
434    pub class_prefix: &'static str,
435}
436
437impl Default for Emit {
438    fn default() -> Self {
439        Self {
440            border_width: "1px",
441            focus_width: "2px",
442            class_prefix: "",
443        }
444    }
445}
446
447/// A string as CSS escapes, for a `content` value.
448///
449/// `\u{25B2}` becomes `\25B2`. Emitted escaped rather than literally so the
450/// stylesheet is ASCII whatever the description spells: a `content` string is
451/// read by whatever encoding the consumer serves the file as, and a caret that
452/// depends on that is a caret that works on one machine.
453///
454/// Terminated by the closing quote at every site here. A CSS hex escape takes
455/// up to six digits and ends at the first character that cannot be one, so an
456/// escape followed by more text would need a space that these do not.
457fn css_escape(text: &str) -> String {
458    text.chars().fold(String::new(), |mut out, c| {
459        let _ = write!(out, "\\{:X}", c as u32);
460        out
461    })
462}
463
464/// The CSS custom property holding a bevel's composition.
465#[must_use]
466pub fn bevel_var(bevel: Bevel) -> &'static str {
467    match bevel {
468        Bevel::Raised => "--bevel-raised",
469        Bevel::Inset => "--bevel-inset",
470    }
471}
472
473/// A `var()` reference to a fill intent, with the browser's own fallback where
474/// the intent may be absent.
475///
476/// The fallback is CSS syntax, not a decision made here. That is the whole
477/// difference between this renderer and the other two.
478#[must_use]
479pub fn fill_var(fill: Fill) -> String {
480    match fill {
481        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
482        other => format!("var(--{})", other.token()),
483    }
484}
485
486/// The two-tone edge as a `box-shadow` value.
487///
488/// Two inset shadows, one per corner pair: the light one offset down and
489/// right so it lands on the top and left edges, the dark one the other way.
490/// The same assignment `makeover-immediate` draws with polylines and
491/// `makeover-tui` draws with box-drawing characters.
492#[must_use]
493pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
494    let (top_left, bottom_right) = bevel.edges();
495    let w = opts.border_width;
496    format!(
497        "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
498        top_left.token(),
499        bottom_right.token()
500    )
501}
502
503/// The custom properties both bevels resolve through.
504///
505/// Emitted as properties rather than inlined into every rule because that is
506/// what the apps already do, and because a consumer that wants the edge
507/// without the fill reads the property directly.
508#[must_use]
509pub fn bevel_properties(opts: &Emit) -> String {
510    let mut css = String::new();
511    for bevel in [Bevel::Raised, Bevel::Inset] {
512        let _ = writeln!(
513            css,
514            "    {}: {};",
515            bevel_var(bevel),
516            bevel_shadow(bevel, opts)
517        );
518    }
519    css.push_str(ELEVATION_PROPERTY);
520    css
521}
522
523/// The cast shadow of a surface that floats over the page.
524///
525/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
526/// this crate owns the geometry, and neither has to know the other's numbers.
527///
528/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
529/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
530/// that reaches for this on a card or a plate has renamed a literal rather than
531/// replaced it.
532///
533/// Two lengths rather than one, because a single blur reads as a smudge at
534/// plate size and as a halo at menu size. The offset is small and downward: a
535/// Platinum-era menu sits just off the page rather than hovering above it.
536const ELEVATION_PROPERTY: &str =
537    "    --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
538
539/// The class name for a depth.
540#[must_use]
541pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
542    let name = match depth {
543        Depth::Flat => return None,
544        Depth::Raised => "raised",
545        Depth::Well => "well",
546        Depth::Sunken => "sunken",
547        // A depth added to the description since this renderer was last
548        // built. No class, on the same footing as Flat: emitting a name
549        // whose rule body we cannot write would put a class in the markup
550        // that the stylesheet never defines.
551        _ => return None,
552    };
553    Some(format!("{}{name}", opts.class_prefix))
554}
555
556/// A prefixed class name.
557///
558/// Public since 0.27.0, for the renderers that emit markup this crate does not.
559/// A screen renderer writing `class="row"` has to prefix it the way the
560/// stylesheet half does or a prefixed app gets rules matching everything except
561/// the elements that renderer wrote, and the failure is invisible: the CSS
562/// stays valid and one element is unstyled. quasi-webview carried a byte
563/// identical copy of this function until it could call this one.
564#[must_use]
565pub fn class(name: &str, opts: &Emit) -> String {
566    let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
567    push_class(&mut out, name, opts);
568    out
569}
570
571/// A prefixed class name, written into a buffer the caller already has.
572///
573/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
574/// every class on every element went through a `format!` before 0.40.0,
575/// including the default case where the prefix is empty and the answer is the
576/// argument. A described table row carried roughly eighty transient
577/// allocations, and this and the escaper were most of them.
578///
579/// [`class`] stays for callers holding a name rather than a buffer.
580///
581/// [`escape_into`]: crate::form::escape_into
582pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
583    out.push_str(opts.class_prefix);
584    out.push_str(name);
585}
586
587/// The class an option of a selector carries, which is what the rules key off.
588///
589/// Named for the option and not for the group: [`selector_rules`] styles the
590/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
591/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
592/// and `option`, put `toggle` on the wrapping element rather than on the
593/// buttons inside it, and every described selector in that renderer came out
594/// with no depth, no focus ring and no chosen state, while the toggle group got
595/// a bevel meant for its buttons.
596///
597/// The chosen option additionally carries `chosen`, the same way a latched chip
598/// carries `latched`. That name is this crate's too; there is no reason for a
599/// caller to spell it, and [`selector_rules`] is where it is written down.
600#[must_use]
601pub fn option_class(selector: Selector) -> &'static str {
602    match selector {
603        Selector::Tabs => "tab",
604        Selector::Segmented => "segment",
605        Selector::Toggle => "toggle",
606    }
607}
608
609/// The fill and edge declarations for a depth, as a rule body.
610///
611/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
612/// Callers lean on the emptiness to skip the rule rather than emit a class that
613/// sets nothing: a class that sets no properties is a class that means "I
614/// thought about this", which is what comments are for.
615///
616/// The two halves are emitted independently because [`Depth::Sunken`] has a
617/// fill and no bevel. Requiring both, which this did before makeover-layout
618/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
619/// mean unpaired: both halves still come off one `Depth`, so they cannot
620/// disagree about what the region is.
621#[must_use]
622pub fn depth_declarations(depth: Depth) -> String {
623    let mut css = String::new();
624    if let Some(fill) = depth.fill() {
625        let _ = writeln!(css, "    background: {};", fill_var(fill));
626    }
627    if let Some(bevel) = depth.bevel() {
628        let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
629    }
630    css
631}
632
633/// One rule giving a selector a depth, or nothing when the depth declares
634/// nothing.
635#[must_use]
636pub fn depth_rule(selector: &str, depth: Depth) -> String {
637    let body = depth_declarations(depth);
638    if body.is_empty() {
639        return String::new();
640    }
641    format!(".{selector} {{\n{body}}}\n")
642}
643
644/// The media condition a hover rule has to sit inside, or `None` if hover is
645/// unconditional.
646///
647/// Two crates answer this and neither answer is made here. `makeover-touch`
648/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
649/// that capability is spelled as a media condition. Asking both is what stops
650/// this renderer minting a third opinion, which is what all three apps did:
651/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
652/// alone, and the MNW server had no gate at all.
653///
654/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
655/// member, which reports as much through `reads_size`. Passing Compact is not
656/// a claim about width; the test below pins that every class agrees.
657fn hover_condition() -> Option<&'static str> {
658    if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
659        // A fingertip grew a hover state. Nothing to gate, and this renderer
660        // should not invent a reason to gate anyway.
661        None
662    } else {
663        Some(Density::Pointer.media_condition())
664    }
665}
666
667/// Put a rule inside a media query, or leave it alone.
668fn gated(condition: Option<&str>, rule: &str) -> String {
669    let Some(condition) = condition else {
670        return rule.to_string();
671    };
672    let mut css = format!("@media {condition} {{\n");
673    for line in rule.lines() {
674        // Blank lines stay blank. Indenting one leaves trailing whitespace,
675        // which is the sort of thing a formatter later reverts and calls a diff.
676        if line.is_empty() {
677            css.push('\n');
678        } else {
679            let _ = writeln!(css, "    {line}");
680        }
681    }
682    css.push_str("}\n");
683    css
684}
685
686/// The keyboard focus ring, placed by the depth it lands on.
687///
688/// This is the webview's **focus ring** and nothing more. **Reach** and
689/// **focus** are both the browser's — the document decides what is reachable
690/// and `:focus-visible` decides which reached thing wears the ring — and no
691/// description states either. The three terms are defined once in
692/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
693///
694/// One ring for the whole system, because a focus ring's job is to be
695/// recognised and three apps having three of them is the failure. What varies
696/// is where it sits, and that comes off [`Depth`] rather than off a per-
697/// component choice: a well takes the ring inside its own edge, and anything
698/// standing proud of the page takes it outside.
699///
700/// `outline` rather than the composed `box-shadow` the invalid-field ring at
701/// [`field_rules`] uses, and deliberately the one place the two rings are built
702/// differently. A `box-shadow` ring has to restate the bevel beside it, because
703/// `box-shadow` is not additive and a lone ring silently drops the well out
704/// from under the element. That restatement is a second copy of the depth,
705/// living in a different function from the first, and it is exactly the
706/// duplication `Depth` exists to prevent. `outline` occupies its own property,
707/// so the bevel survives untouched and there is nothing to keep in agreement.
708/// They render the same: both are a flush ring one border-width wide.
709#[must_use]
710pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
711    let w = opts.focus_width;
712    // Same magnitude either way, and only the sign comes off the depth. Both
713    // values are what the consumers had already converged on independently:
714    // 2px out is what all three wrote, and 2px in is the MNW server's own
715    // answer for the one inset ring it had.
716    let offset = match depth.bevel() {
717        // Inside the well, clear of its edge rather than painted over it.
718        Some(Bevel::Inset) => format!("calc(-1 * {w})"),
719        // Raised, or no edge at all. Outside, standing off by its own width.
720        _ => w.to_string(),
721    };
722    // The token by name. It is `makeover`'s, derived from the action colour,
723    // and reaching it through a description member was a second path to the
724    // same variable for as long as one existed.
725    format!(
726        ".{selector}:focus-visible {{\n    outline: {w} solid var(--focus-ring);\n    outline-offset: {offset};\n}}\n"
727    )
728}
729
730/// Present, visible, and not answering.
731///
732/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
733/// only matches form elements and half the things this crate emits are not
734/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
735/// the accessible state is the pattern [`field_rules`] already establishes for
736/// `aria-invalid`, on the reasoning that one fact read by both the styling and
737/// the accessibility tree cannot drift from itself.
738///
739/// The rest depth is re-asserted rather than assumed, because this rule has to
740/// beat the hover and pressed rules above it. It does that on source order at
741/// equal specificity, not by out-specifying them: every rule this function's
742/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
743/// one of them and have to be unpicked when this output moves inside its own
744/// cascade layer.
745#[must_use]
746pub fn disabled_rule(selector: &str, depth: Depth) -> String {
747    format!(
748        ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{}    color: var(--{});\n    cursor: not-allowed;\n}}\n",
749        depth_declarations(depth),
750        State::Disabled.token()
751    )
752}
753
754/// Every state a selector that answers a click implies: hover, pressed, focus
755/// and disabled, in that order.
756///
757/// Order is the whole cascade mechanism here. All four selectors are
758/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
759/// and by nothing else.
760///
761/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
762/// only the edge is what left goingson hand-writing `background:
763/// var(--surface-sunken)` on three separate rules, and a fill that does not
764/// travel with its edge is precisely the disagreement `Depth` exists to make
765/// unrepresentable. So the pressed fill comes from the description
766/// (`--surface-well`) rather than from whatever each app reached for.
767///
768/// Hover has no member in the description and is renderer policy: a terminal
769/// and an immediate-mode painter have no hover to express. It resolves against
770/// `--hover-surface`, which `makeover` already derives and which nothing
771/// consumed until now. What it *is* gated on is capability, via
772/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
773/// goingson's section 60 exists solely to take back the hover state this
774/// function had just handed it, by out-specifying a rule it does not own.
775///
776/// `depth` is the selector's **rest** depth, used to place the focus ring and
777/// to restore the surface under a disabled control. The pressed rule keeps
778/// inverting from [`Depth::Raised`] regardless, which is what every caller got
779/// before this parameter existed: a tab's unchosen depth is
780/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
781/// from the rest depth would leave a tab with no press at all.
782#[must_use]
783pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
784    let mut css = gated(
785        hover_condition(),
786        &format!(".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n"),
787    );
788    css.push_str(&depth_rule(
789        &format!("{selector}:active"),
790        Depth::Raised.pressed(),
791    ));
792    css.push_str(&focus_rule(selector, depth, opts));
793    css.push_str(&disabled_rule(selector, depth));
794    css
795}
796
797/// One rule per depth: its fill and its edge, together.
798///
799/// A depth and nothing else. `.raised` says a surface sits on what is behind
800/// it, which is a statement about the shape and not about what happens when a
801/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
802/// named surfaces are where interaction lives: `.card` and `.button` are the
803/// same depth *and* controls, and they get their states from
804/// [`surface_rules`].
805///
806/// This class carried the interactive set until 0.17.0, which left the
807/// vocabulary with no raised surface that is merely an object. Consumers that
808/// needed one took a control class and cancelled half of it instead: sixteen
809/// elements in goingson across three `.card--*` variants, each re-asserting the
810/// resting fill and bevel on `:hover` and `:active`. Nothing anywhere used
811/// `.raised` itself, so the states were unasked-for in every consumer at once.
812#[must_use]
813pub fn depth_rules(opts: &Emit) -> String {
814    let mut css = String::new();
815    for depth in [Depth::Raised, Depth::Well] {
816        let Some(class) = depth_class(depth, opts) else {
817            continue;
818        };
819        css.push_str(&depth_rule(&class, depth));
820    }
821    css
822}
823
824/// The three surfaces that are a depth with a name.
825///
826/// `button` and `card` are both [`Depth::Raised`], and `field` is a
827/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
828/// gives a text field. Their bodies come out identical by construction rather
829/// than by hand: three hand-written copies in goingson's stylesheet is what
830/// phase A deletes, and generating them from one call is what stops them
831/// drifting apart again.
832fn surface_rules(opts: &Emit) -> String {
833    let mut css = String::new();
834    for name in ["button", "card"] {
835        let c = class(name, opts);
836        css.push_str(&depth_rule(&c, Depth::Raised));
837        css.push_str(&interactive_rules(&c, Depth::Raised, opts));
838    }
839
840    let field = class("field", opts);
841    css.push_str(&depth_rule(&field, Depth::Well));
842
843    // A field takes focus and refuses input like everything else here, and got
844    // neither until now, which is why all three apps hand-write a focus ring
845    // for it and no two of them match. No hover or pressed: a text field does
846    // not light up under the pointer and does not invert when clicked, so the
847    // two states `interactive_rules` would add are the two it does not have.
848    css.push_str(&focus_rule(&field, Depth::Well, opts));
849    css.push_str(&disabled_rule(&field, Depth::Well));
850
851    // Keyed on the ARIA attribute rather than on a class, so the visual state
852    // and the accessible state cannot drift apart: there is one fact and both
853    // read it. goingson already drove its invalid styling this way and was
854    // right to; the `.invalid` class this emitted before 0.5.0 was a second
855    // place to forget.
856    //
857    // The ring composes *after* the bevel rather than replacing it. box-shadow
858    // is not additive, so a lone ring silently dropped the well out from under
859    // an invalid field. Flat and unlit: this edge is saying "wrong", and
860    // lighting one side would have it say "raised" at the same time.
861    let _ = writeln!(
862        css,
863        ".{field}[aria-invalid=\"true\"] {{\n    box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
864        bevel_var(Bevel::Inset),
865        opts.border_width
866    );
867    css
868}
869
870/// Badges and chips.
871///
872/// The one place phase A changes how goingson looks rather than only where its
873/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
874/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
875/// carrying the raised bevel. Splitting that means reading every call site to
876/// decide which of the two it always was.
877///
878/// What a badge does carry is a [`Tone`], the intent family it shares with
879/// notices and nothing else. Neutral is the bare class rather than a variant,
880/// because it is the absence of a status and not a status called "none".
881/// Text that goes somewhere.
882///
883/// The one inline control, and the vocabulary had no word for it until a
884/// description layer needed one. A table cell has carried `cell-link` since
885/// 0.14.0's part list, deliberately unruled because the cell's own rule covers
886/// it; what was missing is the same thing outside a table, which is what a
887/// described run holds when a sentence contains a link.
888///
889/// Colour and underline only. Whether a link is inline in a sentence or sitting
890/// on its own line is the app's layout, and how much room it takes is
891/// `makeover-geometry`'s. What is here is the pair of signals that say "this
892/// goes somewhere" and nothing that says where it sits.
893///
894/// The visited arm is deliberately absent. A link inside an app points at the
895/// app's own screens, which the user is expected to have been to, so painting
896/// them differently marks almost everything and distinguishes nothing.
897fn link_rules(opts: &Emit) -> String {
898    let mut css = String::new();
899    let link = class("link", opts);
900
901    let _ = writeln!(
902        css,
903        ".{link} {{\n    color: var(--action);\n    \
904         text-decoration: underline;\n}}"
905    );
906    // The hover step is the same one every other control takes, and it is a
907    // colour rather than a surface: a link has no box to raise.
908    let _ = writeln!(
909        css,
910        "@media (hover: hover) and (pointer: fine) {{\n    .{link}:hover \
911         {{\n        color: var(--action-hover);\n    }}\n}}"
912    );
913    let _ = writeln!(
914        css,
915        ".{link}:focus-visible {{\n    outline: {} solid var(--focus-ring);\n    \
916         outline-offset: 2px;\n}}",
917        opts.focus_width
918    );
919    // A link is often a `<button>` rather than an `<a>`: a renderer picks the
920    // element from the method, so a link that writes is a button that has to
921    // stop looking like one.
922    let _ = writeln!(
923        css,
924        "button.{link} {{\n    background: none;\n    border: none;\n    \
925         padding: 0;\n    font: inherit;\n    cursor: pointer;\n}}"
926    );
927    css
928}
929
930fn token_rules(opts: &Emit) -> String {
931    let mut css = String::new();
932
933    // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
934    // and a label with an edge says it can be pressed.
935    let badge = class("badge", opts);
936    let _ = writeln!(
937        css,
938        ".{badge} {{\n    color: var(--{});\n}}",
939        Tone::Neutral.token()
940    );
941    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
942        let _ = writeln!(
943            css,
944            ".{badge}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
945            tone.token()
946        );
947    }
948
949    // A button carries the four tones a badge does. It had none, on the reading
950    // that a control's colour is its surface rather than its text, and that
951    // reading has one hole big enough to matter: the button that destroys
952    // something. Every consumer had written that rule itself, and a description
953    // that says `Tone::Danger` on an act had nowhere for it to land.
954    //
955    // Colour and not a fill, matching the badge. A red surface is a decision
956    // about emphasis that belongs to an app's own layer, and two of them
957    // fighting is worse than neither.
958    let button = class("button", opts);
959    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
960        let _ = writeln!(
961            css,
962            ".{button}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
963            tone.token()
964        );
965    }
966
967    // A chip holds itself down, which is `Depth::pressed` arrived at
968    // independently by two apps. `removable` is a remove affordance, so it is
969    // markup and waits for phase B.
970    let chip = class("chip", opts);
971    let unlatched = Token::Chip { removable: false };
972    css.push_str(&depth_rule(&chip, unlatched.depth(false)));
973    css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
974    css.push_str(&depth_rule(
975        &format!("{chip}.latched"),
976        unlatched.depth(true),
977    ));
978    css
979}
980
981/// The three selectors, each named by what it picks.
982///
983/// A tab comes *forward* to join the pane it opens, which is why
984/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
985/// are held in. That is the folder semantic, and it is the whole reason the
986/// three are not one member with a flag.
987///
988/// [`Selector::abutting`] is not emitted: whether the options touch is
989/// spacing, and spacing is `makeover-geometry`'s question to answer.
990///
991/// Both states emit as of makeover-layout 0.3.0. Before it the description
992/// named only the chosen option, so an unchosen one fell through to
993/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
994/// strip hand-writing the recess that makes its chosen tab read as forward.
995fn selector_rules(opts: &Emit) -> String {
996    let mut css = String::new();
997    for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
998        let c = class(option_class(selector), opts);
999        css.push_str(&depth_rule(&c, selector.unchosen()));
1000        css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
1001        css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
1002    }
1003    css
1004}
1005
1006/// The parts of a list row.
1007///
1008/// The list is written out rather than derived because `RowPart` is
1009/// `#[non_exhaustive]` as of makeover-layout 0.9.0, so there is nothing to
1010/// iterate. A member added upstream emits no rule until it is named here, which
1011/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
1012/// [`part_class`] carries the same list and the same obligation.
1013fn row_rules(opts: &Emit) -> String {
1014    let mut css = String::new();
1015
1016    // The container the rows sit in. Three zeroes and a keyword, all of them
1017    // undoing a browser default the description never asked for: a described
1018    // list of SSH keys is not a bulleted list, and it rendered as one because
1019    // nothing here said otherwise. Not a size: there is no magnitude in it,
1020    // which is the line this crate holds.
1021    let _ = writeln!(
1022        css,
1023        ".{} {{\n    list-style: none;\n    margin: 0;\n    padding: 0;\n}}",
1024        class("list", opts)
1025    );
1026
1027    for part in [
1028        RowPart::Primary,
1029        RowPart::Secondary,
1030        RowPart::Meta,
1031        RowPart::Actions,
1032        RowPart::Tokens,
1033        RowPart::Proportion,
1034    ] {
1035        let c = class(part_class(part), opts);
1036
1037        // Actions carry controls rather than text, and `RowPart::intent` says
1038        // so by returning the same intent inheriting already gives. Pinning it
1039        // would be louder than saying nothing. Tokens answer alike, for their
1040        // own reason: each token carries its own tone, and a colour on the
1041        // strip would fight the things sitting in it. A proportion is the same
1042        // case again: the meter inside carries the tone.
1043        if !matches!(
1044            part,
1045            RowPart::Actions | RowPart::Tokens | RowPart::Proportion
1046        ) {
1047            let _ = writeln!(css, ".{c} {{\n    color: var(--{});\n}}", part.intent());
1048        }
1049
1050        // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
1051        // otherwise and was not honoured here from 0.23.0; makeover-layout
1052        // 0.13.0 retired the method, so there is no longer a description saying
1053        // one thing and a renderer doing another.
1054        //
1055        // The rule was `opacity: 0` gated to pointer devices, revealed on
1056        // `:hover` and on `:focus-within`. Each escape it needed was a report
1057        // that hiding was wrong for somebody: `focus-within` because tabbing
1058        // could never reach an action; the gate because a fingertip had no way
1059        // to unhide, which both webview apps had already hand-written
1060        // `opacity: 1` to undo. What was left was a control hidden from
1061        // exactly one group: people using a pointer, who are also the group
1062        // scanning a list to find out what can be done to a row.
1063        //
1064        // A settings screen is where that reads worst: the whole reason to be
1065        // on it is to remove a key, and the button doing so was invisible
1066        // until pointed at. A table cell's actions were never hidden, so the
1067        // two arrangements now agree.
1068    }
1069
1070    // A part that may take two lines. `Flow::Tight` gets no rule: one line is
1071    // what a run already does, and restating it here would put a declaration on
1072    // every part in every row to say nothing.
1073    //
1074    // This is the shape both webview apps had already written by hand and
1075    // commented -- Balanced Breakfast on a feed row's title, goingson on a
1076    // problem's body -- which is the whole argument for the description
1077    // carrying it. `-webkit-` prefixed and unprefixed together: the prefixed
1078    // trio is what every engine actually implements, and `line-clamp` is the
1079    // standard property landing behind it.
1080    let _ = writeln!(
1081        css,
1082        ".{} {{\n    display: -webkit-box;\n    -webkit-box-orient: vertical;\n    -webkit-line-clamp: {lines};\n    line-clamp: {lines};\n    overflow: hidden;\n}}",
1083        class("row-relaxed", opts),
1084        lines = Flow::Relaxed.lines()
1085    );
1086
1087    css
1088}
1089
1090/// A row of things that share their space, and what each fallback gets here.
1091///
1092/// Ruling: wiki `layout-room-and-fallback`, Max 2026-08-18. The bug it answers
1093/// is goingson's `styles.css:702`, which pinned every `.page-header` over the
1094/// pill strip with `position: absolute` and so took the toolbar out of flow:
1095/// zero width contributed to the row it shared, nothing able to collide with
1096/// it, and therefore nothing preventing the collision. Rule 1 of the ruling is
1097/// that every described member is in flow, and these rules are how that is kept
1098/// rather than asked for.
1099///
1100/// # The floor, which is most of the fix
1101///
1102/// `.run > *` gets `min-width: min-content`. That is the derived minimum the
1103/// ruling asks for, in this renderer's own unit and stated by the browser
1104/// rather than by anybody: a member cannot be squeezed narrower than what is
1105/// in it, so members in one flow push each other instead of overlapping. It
1106/// costs no query and no number, and it is what fixes all four measured widths
1107/// whichever fallback the group declared.
1108///
1109/// # What each fallback gets, exactly
1110///
1111/// [`Fallback::Wrap`] is `flex-wrap: wrap`, which is exact. The browser wraps
1112/// the run when the members no longer fit, deciding that from their own
1113/// intrinsic widths, which is the derived minimum doing the whole job.
1114///
1115/// [`Fallback::Stack`] is wrap plus `flex: 1 1 max-content` on the members, so
1116/// a member that cannot sit beside its sibling takes a line of its own and
1117/// fills it. For the two-member run this was ruled on -- a tab strip and a
1118/// band -- that is precisely "a row becomes a column".
1119///
1120/// [`Fallback::Shed`] and [`Fallback::Menu`] get wrap, and this renderer is
1121/// honouring less than the description says. **CSS cannot express either one
1122/// without breaking the ruling's own first constraint.** Both need to know that
1123/// the run is out of room in order to take a member out of it, a container
1124/// query is the only construct that can ask, and `@container` compares against
1125/// a `<length>` -- there is no `@container (inline-size < min-content)`. So
1126/// every honest spelling of Shed here needs an authored breakpoint, which is
1127/// the thing the ruling exists to forbid, and the dishonest ones are worse: a
1128/// clamped height clips by document order rather than by [`Priority`], and
1129/// `display: none` under a viewport `@media` is the `nth-child(n+5)` bug the
1130/// vocabulary replaced.
1131///
1132/// Wrapping is the right thing to do instead. It keeps every member reachable,
1133/// which is the property that was actually broken -- goingson's new-contact
1134/// button left the viewport entirely at 560 -- and it keeps rule 1. A renderer
1135/// answering with less than was described is precedented and deliberate here:
1136/// [`makeover_layout::Region::Columns`] says a terminal stacking a board's
1137/// columns is honouring the description rather than degrading it.
1138///
1139/// The real mechanism needs the shed members to have somewhere to go, which is
1140/// markup and belongs to quasi-webview: an overflow control is a member of the
1141/// run, and the description does not yet say that a member *is* one. Filed
1142/// rather than guessed at.
1143fn run_rules(opts: &Emit) -> String {
1144    let run = class("run", opts);
1145    let mut css = String::new();
1146
1147    // `flex-wrap: nowrap` is stated rather than left to the default, because
1148    // the fallbacks below are read as overrides of this line and a reader
1149    // should not have to know which way flexbox leans to see that.
1150    //
1151    // No gap. Spacing between members is the app's, the same way this crate
1152    // states no margins anywhere else; a gap here would be a size, and the one
1153    // hardcoded size in the mechanism is makeover-geometry's contact patch.
1154    let _ = writeln!(
1155        css,
1156        ".{run} {{\n    display: flex;\n    flex-wrap: nowrap;\n    align-items: center;\n}}"
1157    );
1158
1159    // The derived minimum, and the whole reason a member can no longer be
1160    // overlapped. `min-width: auto` is flexbox's default for a flex item and is
1161    // *not* the same thing: auto lets an item be compressed below its content
1162    // in a nowrap run, which is how a toolbar ends up drawn over a tab strip
1163    // even without anything leaving the flow.
1164    let _ = writeln!(css, ".{run} > * {{\n    min-width: min-content;\n}}");
1165
1166    for fallback in [
1167        Fallback::Wrap,
1168        Fallback::Stack,
1169        Fallback::Shed,
1170        Fallback::Menu,
1171    ] {
1172        let name = fallback_class(fallback);
1173        let c = class(name, opts);
1174        let _ = writeln!(css, ".{c} {{\n    flex-wrap: wrap;\n}}");
1175        if matches!(fallback, Fallback::Stack) {
1176            let _ = writeln!(css, ".{c} > * {{\n    flex: 1 1 max-content;\n}}");
1177        }
1178    }
1179
1180    css
1181}
1182
1183/// Every class [`fallback_class`] can return, plus the run itself.
1184///
1185/// [`ROW_PART_CLASSES`](crate::list::ROW_PART_CLASSES)'s reasoning and the same
1186/// obligation: a `match` over a `#[non_exhaustive]` enum cannot be enumerated
1187/// from outside, so the list sits beside it and a test holds the two together.
1188/// `run` is in it because it is emitted in its own right rather than only as a
1189/// fallback's fallback.
1190pub const RUN_CLASSES: &[&str] = &["run", "run-wrap", "run-stack", "run-shed", "run-menu"];
1191
1192/// The class a run carries for what it does when it is tight.
1193///
1194/// A run always carries `.run` as well, so an unrecognised fallback -- the enum
1195/// is `#[non_exhaustive]` -- lands as a plain nowrap row with the min-content
1196/// floor still under it. That is the safe failure: every member in flow and
1197/// none overlapped, which is the property, with only the rearrangement missing.
1198#[must_use]
1199pub fn fallback_class(fallback: Fallback) -> &'static str {
1200    match fallback {
1201        Fallback::Wrap => "run-wrap",
1202        Fallback::Stack => "run-stack",
1203        Fallback::Shed => "run-shed",
1204        Fallback::Menu => "run-menu",
1205        _ => "run",
1206    }
1207}
1208
1209/// The progress trough these rules fill.
1210///
1211/// This was renderer-local chrome with nothing behind it until makeover-layout
1212/// 0.10.0, which is the unusual order: the tones below were emitted for every
1213/// bar in the tree while the only way to describe one was to concatenate the
1214/// numbers into a heading. `Meter` is the word that arrived late, and
1215/// [`meter::meter_html`](crate::meter::meter_html) is what now fills these.
1216///
1217/// The rules stay a superset of what a description can ask for. An app drawing
1218/// its own bar keeps these classes, which is what the four goingson grew
1219/// independently were adopted onto.
1220///
1221/// The trough is a [`Depth::Well`], the same reading a text field gets:
1222/// something with its content down inside it.
1223fn progress_rules(opts: &Emit) -> String {
1224    let progress = class("progress", opts);
1225    // `progress-fill` rather than a bare `fill`: an unprefixed build claims
1226    // these names in the app's own stylesheet, and `.fill` is grabby enough to
1227    // catch things that have nothing to do with progress. goingson already
1228    // calls it `.progress-fill`, so this is also the name that deletes.
1229    let fill = class("progress-fill", opts);
1230    let mut css = depth_rule(&progress, Depth::Well);
1231
1232    // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
1233    // place this differs from the badge rules, and deliberately: a badge with
1234    // no status is a muted label, while a bar with no status is still
1235    // reporting progress, and `content-muted` would read as disabled.
1236    let _ = writeln!(
1237        css,
1238        ".{progress} > .{fill} {{\n    background: var(--action);\n}}"
1239    );
1240
1241    // A bar can be saying something, same as a badge: goingson colours subtask
1242    // progress as success and an over-estimate as danger, which is real
1243    // information rather than decoration. Emitting the tones is what lets that
1244    // survive adoption instead of staying hand-written.
1245    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1246        let _ = writeln!(
1247            css,
1248            ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n    background: var(--{0});\n}}",
1249            tone.token()
1250        );
1251    }
1252    css
1253}
1254
1255/// A strip of figures, and the two spans inside each one.
1256///
1257/// Colour only, which is the deferral rule applied to a component that badly
1258/// wants to break it. A figure reads as a figure because the value is set large
1259/// over a small caption, and that is a size: `makeover-geometry` answers how
1260/// much space and this crate answers what the thing is. Emitting `font-size`
1261/// here would be this crate naming a value, which is the one thing it is defined
1262/// by not doing, and `progress_rules` is the precedent — it emits the tones and
1263/// never the width, because the width is not its to know.
1264///
1265/// So the arrangement and the type scale are the app's, and what is generated is
1266/// the part an app cannot get right by itself: which of the two spans carries
1267/// the tone.
1268fn figure_rules(opts: &Emit) -> String {
1269    let figure = class("figure", opts);
1270    let value = class("figure-value", opts);
1271    let caption = class("figure-caption", opts);
1272    let change = class("figure-change", opts);
1273    let mut css = String::new();
1274
1275    let _ = writeln!(
1276        css,
1277        ".{figure} > .{value} {{\n    color: var(--{});\n}}",
1278        Tone::Neutral.token()
1279    );
1280    let _ = writeln!(
1281        css,
1282        ".{figure} > .{caption} {{\n    color: var(--content-muted);\n}}"
1283    );
1284    let _ = writeln!(
1285        css,
1286        ".{figure} > .{change} {{\n    color: var(--content-muted);\n}}"
1287    );
1288
1289    // A toned figure tones one part and never the caption. The caption is the
1290    // noun and stays muted.
1291    //
1292    // Which part depends on whether there is a change, and that is the whole of
1293    // what 0.13.0 changed here. A figure with a delta is an ordinary number that
1294    // has moved in a direction worth reading, so the delta takes the colour and
1295    // the number stays plain; a figure without one has nowhere else to put it.
1296    // `:has` is what lets one attribute mean both, and the alternative was the
1297    // emitter deciding by writing the attribute onto a different element, which
1298    // leaves two elements able to disagree about a figure's one meaning.
1299    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1300        let _ = writeln!(
1301            css,
1302            ".{figure}[data-tone=\"{0}\"] > .{change} {{\n    color: var(--{0});\n}}",
1303            tone.token()
1304        );
1305        let _ = writeln!(
1306            css,
1307            ".{figure}[data-tone=\"{0}\"]:not(:has(> .{change})) > .{value} \
1308             {{\n    color: var(--{0});\n}}",
1309            tone.token()
1310        );
1311    }
1312    css
1313}
1314
1315/// A picture, its frame and its caption.
1316///
1317/// `makeover_layout::Image` arrived at 0.21.0, found by trying to describe MNW's
1318/// carousel and discovering nothing named a picture.
1319///
1320/// # The frame is a border, and this is the one place a bevel is wrong
1321///
1322/// 0.36.0 emitted [`Depth::Raised`] here through [`depth_rule`], the same call
1323/// `button` and `card` make. It was wrong, and MNW's landing page is where it
1324/// showed: **the frames had no visible edge at all.**
1325///
1326/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow — a
1327/// 1px light run at the top-left and a dark one at the bottom-right, drawn
1328/// **inside** the element's box. On a button or a card that box is a surface
1329/// this crate owns, so an inset edge reads as the surface catching the light.
1330/// On a picture it is drawn on top of the picture, over whatever pixels the
1331/// image happens to have at its border. MNW's screenshots are light-on-light
1332/// parchment, so the light half landed on a light image and the frame
1333/// disappeared.
1334///
1335/// **You cannot bevel a surface you do not own.** A picture's content is the
1336/// app's, arrives at request time, and can be any colour, so its edge has to
1337/// sit *outside* the content rather than on it. That is a border.
1338///
1339/// The fill stays, and it is not decoration: it is what shows through a
1340/// transparent PNG and what stands in the frame's place while the image is
1341/// still loading.
1342///
1343/// This is a real limit on [`Depth`] rather than a special case. Every other
1344/// consumer of a depth draws its own surface; a picture is the first member
1345/// whose surface belongs to someone else.
1346///
1347/// # No size
1348///
1349/// `width: 100%` and nothing else. How large a picture is depends on the box it
1350/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
1351/// and a renderer that picked one would be answering for every consumer at
1352/// once. This is where `figure_rules` landed for the same reason.
1353fn picture_rules(opts: &Emit) -> String {
1354    let picture = class("picture", opts);
1355    let img = class("picture-img", opts);
1356    let caption = class("picture-caption", opts);
1357    let mut css = String::new();
1358
1359    // Block, or an inline image sits on the text baseline and carries a
1360    // descender's worth of space under it that no app ever wants and every app
1361    // deletes by hand. The border is the frame; see the type docs for why it is
1362    // not the bevel every other surface here gets.
1363    let _ = writeln!(
1364        css,
1365        ".{img} {{\n    display: block;\n    width: 100%;\n    height: auto;\n    \
1366         background: var(--{});\n    border: {} solid var(--border);\n}}",
1367        Fill::Raised.token(),
1368        opts.border_width
1369    );
1370
1371    // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
1372    // so it is the bare rule above and needs nothing here.
1373    let _ = writeln!(
1374        css,
1375        ".{img}[data-fit=\"cover\"] {{\n    height: 100%;\n    object-fit: cover;\n}}"
1376    );
1377    let _ = writeln!(
1378        css,
1379        ".{img}[data-fit=\"contain\"] {{\n    height: 100%;\n    object-fit: contain;\n}}"
1380    );
1381
1382    // A caption reads back one step, which is `figure-caption`'s answer and the
1383    // same claim: it says what the thing above it is, and it is not the thing.
1384    let _ = writeln!(
1385        css,
1386        ".{picture} > .{caption} {{\n    color: var(--content-muted);\n}}"
1387    );
1388
1389    css
1390}
1391
1392/// A region showing one child at a time, and the chrome that moves between them.
1393///
1394/// [`makeover_layout::Showing`] lets a description say that a region holds
1395/// several children and shows some of them. A renderer derives its own chrome
1396/// from that, which is what stops every renderer growing a `match` on a widget
1397/// name; these are the rules the derived chrome needs.
1398///
1399/// # Why the default is every child, and the enhancement takes them away
1400///
1401/// The controls are a lie until something binds them. A prev button rendered
1402/// into a document with no script is a control that looks live and answers
1403/// nothing, and the reader it lies to is exactly the one who cannot see the
1404/// other children either — the collapsing and the moving are the same half.
1405///
1406/// So the rules run in the direction the enhancement does. Nothing here hides a
1407/// child and nothing here shows a control. Whatever binds the region sets
1408/// `data-ready` on it, and that is what collapses the stack to one and reveals
1409/// the row that moves it. A reader with no script gets every child in order and
1410/// no controls, which is more content rather than less, and a reader with
1411/// script gets a settled page rather than a stack that jumps to one frame after
1412/// load.
1413///
1414/// MNW proved this shape by hand — a `<noscript>` stylesheet opening its
1415/// carousel back out — and it is here rather than there because the property is
1416/// the description's, not one app's.
1417///
1418/// # Not spacing
1419///
1420/// The row's gaps are `makeover-geometry`'s question and are absent for
1421/// [`row_rules`]'s reason. What is here is `display`, which carries no
1422/// magnitude, and the muted readout, which is the same claim `picture-caption`
1423/// makes: it says where you are among the children and it is not one of them.
1424fn showing_rules(opts: &Emit) -> String {
1425    let controls = class("showing", opts);
1426    let position = class("showing-position", opts);
1427    let frame = class("showing-frame", opts);
1428    let mut css = String::new();
1429
1430    // Hidden until something binds it, which is the whole argument above.
1431    let _ = writeln!(css, ".{controls} {{\n    display: none;\n}}");
1432    // Block, and nothing about how the three sit in it. A button and a span are
1433    // inline already, so they make a row without this crate saying so, and
1434    // saying so is where `align-items` and a gap would follow -- both spacing,
1435    // both `makeover-geometry`'s, and `row_rules` refuses them for the same
1436    // reason.
1437    let _ = writeln!(
1438        css,
1439        "[data-ready] > .{controls} {{\n    display: block;\n}}"
1440    );
1441
1442    // A child is in flow until the region is bound, and then only the current
1443    // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
1444    // are: one name for the state, set by whoever knows it.
1445    let _ = writeln!(
1446        css,
1447        "[data-ready] > .{frame}:not(.current) {{\n    display: none;\n}}"
1448    );
1449
1450    // Reads back one step. `picture-caption`'s rule and its reason.
1451    let _ = writeln!(css, ".{position} {{\n    color: var(--content-muted);\n}}");
1452
1453    css
1454}
1455
1456/// A time axis: the container, its gridlines and ruler, and the placed things.
1457///
1458/// `makeover-layout` 0.24.0's [`Track`](makeover_layout::Track), and the first
1459/// member here whose whole point is *position*. That makes the magnitude line
1460/// this crate keeps worth restating rather than assuming.
1461///
1462/// # Where the numbers come from
1463///
1464/// Every value that varies per item is a custom property the caller sets
1465/// inline, and every rule here reads one. `--track-at` and `--track-for` are
1466/// percentages of the span, which
1467/// [`Track::fraction`](makeover_layout::Track::fraction) computes once so three
1468/// renderers cannot disagree about it. Nothing here knows a pixel.
1469///
1470/// That is what lets the stylesheet stay static while the items move: an entry
1471/// carries `style="--track-at: 37.5%; --track-for: 4.166%"` and the rule below
1472/// turns it into a box. The alternative was emitting a rule per item, which is
1473/// a stylesheet that grows with the data.
1474///
1475/// **The height of the track is the app's**, not this crate's. 96 quarter-hour
1476/// slots at some slot height is a size, and a size is `makeover-geometry`'s
1477/// question -- the same refusal `figure_rules` and `placeholder_rules` make.
1478/// Percentages need a resolved height above them, so `.track` gets
1479/// `position: relative` and nothing else; the app says how tall a day is.
1480///
1481/// # Overlap
1482///
1483/// Two things at the same time is intrinsic to an axis and has no analogue in a
1484/// list. The description does not declare it -- `Placement::overlaps` derives it
1485/// from the times -- so what arrives here is a lane index and a lane count, and
1486/// the rule divides the width. A renderer that would rather stack them ignores
1487/// both properties and the defaults give it one full-width lane.
1488fn track_rules(opts: &Emit) -> String {
1489    let track = class("track", opts);
1490    let slot = class("track-slot", opts);
1491    let tick = class("track-tick", opts);
1492    let entry = class("track-entry", opts);
1493    let mut css = String::new();
1494
1495    // The positioning context every entry resolves against, and the whole of
1496    // what this crate says about the container. No height: see the doc above.
1497    let _ = writeln!(css, ".{track} {{\n    position: relative;\n}}");
1498
1499    // Gridlines and the ruler are the axis reading itself back, which is
1500    // `picture-caption` and `showing-position`'s claim: about the thing rather
1501    // than one of the things.
1502    //
1503    // `border_width` rather than a literal, the way `depth_rule` writes its
1504    // edge. A gridline is the one place a timeline would most naturally reach
1505    // for a hardcoded 1px, and a hardcoded 1px is this crate naming a size.
1506    let _ = writeln!(
1507        css,
1508        ".{slot} {{\n    border-top: {} solid var(--border);\n}}",
1509        opts.border_width
1510    );
1511    let _ = writeln!(css, ".{tick} {{\n    color: var(--content-muted);\n}}");
1512
1513    // The one rule that does real work. Top and height are the placement;
1514    // left and width are the lane. Both lane properties default so an entry
1515    // that names neither is full width, which is the common case and the one a
1516    // renderer gets for free.
1517    let _ = writeln!(
1518        css,
1519        ".{entry} {{\n    \
1520         position: absolute;\n    \
1521         top: var(--track-at, 0%);\n    \
1522         height: var(--track-for, 100%);\n    \
1523         left: calc(var(--track-lane, 0) / var(--track-lanes, 1) * 100%);\n    \
1524         width: calc(100% / var(--track-lanes, 1));\n\
1525         }}"
1526    );
1527
1528    css
1529}
1530
1531/// A region's stand-in, and the header of a table that can be reordered.
1532///
1533/// Both are 0.12.0 members and both are colour and affordance only, which is
1534/// where `figure_rules` landed after trying to emit a type scale. How much room
1535/// a stand-in gets is a size — goingson has the same one at three, as
1536/// `--compact`, `--dashboard` and `--padded` — and a size is
1537/// `makeover-geometry`'s question.
1538///
1539/// The caret is the one thing here that is neither colour nor affordance, and it
1540/// is a renderer's own expression rather than a value the description named:
1541/// `aria-sort` is what the table actually says, and this turns it into something
1542/// visible for everyone not using a screen reader. A terminal draws its own; an
1543/// immediate-mode painter draws its own.
1544fn state_rules(opts: &Emit) -> String {
1545    let placeholder = class("placeholder", opts);
1546    let text = class("placeholder-text", opts);
1547    let heading = class("table-heading", opts);
1548    let mut css = String::new();
1549
1550    let _ = writeln!(
1551        css,
1552        ".{placeholder} > .{text} {{\n    color: var(--content-muted);\n}}"
1553    );
1554    // Only the failure is toned. An empty list is the normal state of a new
1555    // install, and `Readiness::tone` is what says so.
1556    let _ = writeln!(
1557        css,
1558        ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n    color: var(--{0});\n}}",
1559        Tone::Danger.token()
1560    );
1561
1562    // A header that reorders the table is a control, and the pointer is the
1563    // only part of saying so that is not the app's own type and spacing.
1564    let _ = writeln!(
1565        css,
1566        ".{heading}[data-sortable] {{\n    cursor: pointer;\n}}"
1567    );
1568    // The caret carries its own leading space, the way `makeover-tui` and
1569    // `makeover-immediate` both write `" \u{25B2}"`. It used to be emitted bare,
1570    // and both apps that adopted the vocabulary had to put the gap back in their
1571    // own stylesheets on the same afternoon -- each having to work out first that
1572    // app CSS outranks this crate's cascade layer, so adding the space the
1573    // obvious way, as `content`, silently wins over the glyph and leaves the
1574    // heading with no caret at all. A consumer should not have to know that, and
1575    // with the space emitted here there is nothing left for one to add.
1576    //
1577    // Three states, three tones, on the convention in wiki
1578    // `three-tone-convention`. A column in force is `content`; a column offering
1579    // to reorder and not doing it now is `content-secondary`, because it still
1580    // answers a press; a column that is not sortable emits no caret at all and
1581    // takes nothing. The idle arm used to hide its glyph and reserve the box,
1582    // which cost a reflow-free press and said nothing. It draws now, and the
1583    // reservation stops being a thing to get right.
1584    //
1585    // The glyph is `Sort::glyph`, escaped rather than written: a CSS `content`
1586    // string cannot carry the character literally through this file's own
1587    // escaping, and spelling it here as well would put the third copy back that
1588    // `makeover-layout` 0.27.5 exists to remove.
1589    let _ = writeln!(
1590        css,
1591        ".{heading}[data-sortable]::after \
1592         {{\n    content: \" {}\";\n    color: var(--content-secondary);\n}}",
1593        css_escape(Sort::Ascending.glyph())
1594    );
1595    for direction in [Sort::Ascending, Sort::Descending] {
1596        let _ = writeln!(
1597            css,
1598            ".{heading}[aria-sort=\"{}\"]::after \
1599             {{\n    content: \" {}\";\n    color: var(--content);\n}}",
1600            direction.as_str(),
1601            css_escape(direction.glyph())
1602        );
1603    }
1604    css
1605}
1606
1607/// The frame a table sits in.
1608///
1609/// # Why this is a CSS table and not the grid the rest of the module assumes
1610///
1611/// A grid row needs `grid-template-columns`, which has to name every column in
1612/// order, so it cannot be written without knowing the columns. That is what
1613/// [`list::narrowing_css`] is for, and it works: goingson builds `tables.css` in
1614/// its own `build.rs` out of it, and nothing here changes that.
1615///
1616/// It does not work for a table a *description* produced. Those columns are
1617/// known at render time rather than at build time, and the rules would have to
1618/// travel with the markup: a `<style>` element per table, which needs
1619/// `style-src 'unsafe-inline'` and so blocks the MNW server's standing plan to
1620/// drop it. The head is not an escape: a table swapped in by htmx after a
1621/// delete arrives as a fragment with no head at all.
1622///
1623/// A CSS table aligns its columns across rows knowing nothing about how many
1624/// there are, so there is no track list to emit and nothing per-table to carry.
1625/// The cost is that a described table cannot take a per-column fixed length,
1626/// which costs nothing today: [`Sizing`](list::Sizing) is looked up by column
1627/// name and a description carries no lengths to put in it, so every track a
1628/// described table could ask for is already content, fill or auto.
1629///
1630/// [`Priority`] hiding is unchanged in kind. It moves from a generated
1631/// `display: none` per dropped column to one rule per drop class, which is the
1632/// same fact addressed by class rather than by cutoff, and still never by
1633/// position.
1634fn table_rules(opts: &Emit) -> String {
1635    let table = class("table", opts);
1636    let head = class("table-head", opts);
1637    let row = class("table-row", opts);
1638    let heading = class("table-heading", opts);
1639    let cell = class("cell", opts);
1640    let mut css = String::new();
1641
1642    let _ = writeln!(
1643        css,
1644        ".{table} {{\n    display: table;\n    width: 100%;\n}}"
1645    );
1646    let _ = writeln!(css, ".{head},\n.{row} {{\n    display: table-row;\n}}");
1647    let _ = writeln!(css, ".{heading},\n.{cell} {{\n    display: table-cell;\n}}");
1648
1649    // A content column shrinks to what is in it. `width: 1%` is how a CSS table
1650    // is told that: auto layout hands the slack to the columns that asked for
1651    // room, and a column asking for almost none gets what it needs and no more.
1652    // The `nowrap` is what stops it being given less by wrapping.
1653    let _ = writeln!(
1654        css,
1655        ".{} {{\n    white-space: nowrap;\n    width: 1%;\n}}",
1656        class("cell-content", opts)
1657    );
1658
1659    // A fixed column has no length to be fixed to. The description carries none
1660    // and `Sizing` is not reachable from here, so it behaves as content: the
1661    // honest answer to a width nobody supplied, and the same one `Sizing::track`
1662    // gives it.
1663    let _ = writeln!(
1664        css,
1665        ".{} {{\n    white-space: nowrap;\n}}",
1666        class("cell-fixed", opts)
1667    );
1668
1669    // Optional columns go at the narrowest class, secondary ones go with them,
1670    // which is the cutoff walk `kept_at` describes said as two media queries.
1671    // Essential columns have no rule at all, because never dropping is what not
1672    // being mentioned already means.
1673    for (size, drops) in [
1674        (
1675            SizeClass::Compact,
1676            &["cell-drops-first", "cell-drops-next"][..],
1677        ),
1678        (SizeClass::Medium, &["cell-drops-first"][..]),
1679    ] {
1680        let selectors: Vec<String> = drops
1681            .iter()
1682            .map(|drop| format!(".{}", class(drop, opts)))
1683            .collect();
1684        css.push_str(&gated(
1685            Some(&size.media_condition()),
1686            &format!("{} {{\n    display: none;\n}}\n", selectors.join(",\n")),
1687        ));
1688    }
1689
1690    // What is inside a cell, which the table side could not say until
1691    // makeover-layout 0.14.0. Every cell was one `.cell` and one content
1692    // colour, so a button in a cell was painted as text -- the drift
1693    // `RowPart::intent` has prevented for list rows since 0.2.0 and prevented
1694    // for nothing here.
1695    //
1696    // The colour goes on `.cell-value` rather than on `.cell`, and that
1697    // placement is the whole fix. On the container it would cascade into the
1698    // tokens and the controls sitting beside the text, which is the bug said
1699    // in one rule; on the part that is text, it reaches text and stops.
1700    for part in [
1701        CellPart::Value,
1702        CellPart::Tokens,
1703        CellPart::Actions,
1704        CellPart::Link,
1705    ] {
1706        // Three of the four inherit, each for its own reason: a token carries
1707        // its own tone, an action is a control rather than text, and a link
1708        // takes the action colour from the anchor it is. `CellPart::intent`
1709        // says so by answering with the intent inheriting already gives, and
1710        // pinning that would be louder than saying nothing.
1711        //
1712        // Written as a skip-list rather than as a match on Value, so a member
1713        // added upstream gets its intent emitted rather than being silently
1714        // dropped. That is the same trade `part_class`'s fallback makes: land
1715        // plainly, never land as nothing.
1716        if !matches!(part, CellPart::Tokens | CellPart::Actions | CellPart::Link) {
1717            let _ = writeln!(
1718                css,
1719                ".{} {{\n    color: var(--{});\n}}",
1720                class(cell_part_class(part), opts),
1721                part.intent()
1722            );
1723        }
1724    }
1725
1726    css
1727}
1728
1729/// The component layer: every named thing phase A emits.
1730///
1731/// No scrollbar track. It was on the phase A list and came off: eight lines of
1732/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
1733/// would want handed to it, so it stays with the apps.
1734#[must_use]
1735pub fn component_rules(opts: &Emit) -> String {
1736    let mut css = String::new();
1737    css.push_str(&surface_rules(opts));
1738    css.push_str(&link_rules(opts));
1739    css.push_str(&token_rules(opts));
1740    css.push_str(&selector_rules(opts));
1741    css.push_str(&row_rules(opts));
1742    css.push_str(&run_rules(opts));
1743    css.push_str(&progress_rules(opts));
1744    css.push_str(&figure_rules(opts));
1745    css.push_str(&picture_rules(opts));
1746    css.push_str(&showing_rules(opts));
1747    css.push_str(&track_rules(opts));
1748    css.push_str(&state_rules(opts));
1749    css.push_str(&table_rules(opts));
1750    css.push_str(&facet::facet_rules(opts));
1751    css.push_str(&form::editor_rules(opts));
1752    css.push_str(&form::suggestion_rules(opts));
1753    css.push_str(&form::unit_rules(opts));
1754    css
1755}
1756
1757/// The whole phase-A stylesheet: properties, depth rules and components, in
1758/// [`CSS_LAYER`], under a generated-file banner.
1759///
1760/// The banner sits outside the layer, because a comment participates in no
1761/// cascade and a reader opening the file should see what it is before seeing
1762/// an at-rule.
1763#[must_use]
1764pub fn stylesheet(opts: &Emit) -> String {
1765    format!(
1766        "/* Generated by makeover-webview from makeover-layout. Do not edit.\n   \
1767         Depth is a fill and an edge together; naming them apart is what let\n   \
1768         them disagree. See the crate's README and wiki note makeover-layout.\n\n   \
1769         Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n   \
1770         order once in your own stylesheet, or this layer's position is decided\n   \
1771         by whichever generated file the browser happens to see first:\n\n   \
1772         @layer {CSS_LAYER}, base, components, responsive; */\n{}",
1773        in_css_layer(&format!(
1774            ":root {{\n{}}}\n\n{}\n{}",
1775            bevel_properties(opts),
1776            depth_rules(opts),
1777            component_rules(opts)
1778        ))
1779    )
1780}
1781
1782#[cfg(test)]
1783mod tests {
1784    use super::*;
1785    use makeover_layout::Edge;
1786
1787    #[test]
1788    fn every_fallback_class_is_one_a_checker_knows_about() {
1789        // The obligation ROW_PART_CLASSES carries, for the same reason: a class
1790        // this crate can write and the vocabulary list does not carry is
1791        // invisible to the dead-vocabulary seal and to the overlap check both.
1792        for fallback in [
1793            Fallback::Wrap,
1794            Fallback::Stack,
1795            Fallback::Shed,
1796            Fallback::Menu,
1797        ] {
1798            assert!(
1799                RUN_CLASSES.contains(&fallback_class(fallback)),
1800                "{fallback:?} is missing from RUN_CLASSES"
1801            );
1802        }
1803        let names = crate::vocabulary::names(&Emit::default());
1804        for name in RUN_CLASSES {
1805            assert!(names.contains(*name), "{name} is not in the vocabulary");
1806        }
1807    }
1808
1809    #[test]
1810    fn a_run_gives_every_member_a_floor_it_cannot_be_squeezed_below() {
1811        // The whole of what stops the overlap, and it is not a fallback: it
1812        // applies to every run whatever the group declared. flexbox's default
1813        // min-width is auto, which lets an item be compressed below its own
1814        // content in a nowrap row, and that is how a toolbar is drawn over a
1815        // tab strip even with nothing out of flow.
1816        let css = run_rules(&Emit::default());
1817        assert!(css.contains(".run > * {\n    min-width: min-content;\n}"));
1818        // No number anywhere in it. The minimum is derived by the browser from
1819        // what the members contain, which is the ruling's own requirement.
1820        assert!(!css.contains("px"));
1821        assert!(!css.contains("rem"));
1822        assert!(!css.contains("@media"));
1823    }
1824
1825    #[test]
1826    fn room_is_never_asked_of_the_viewport() {
1827        // The 913 case: a window in SizeClass::Expanded holding a group out of
1828        // room. A viewport query answers about the window and would be wrong
1829        // about the group, which is why the table's @media walk is not the
1830        // precedent this follows.
1831        let css = run_rules(&Emit::default());
1832        for size in [SizeClass::Compact, SizeClass::Medium] {
1833            assert!(!css.contains(&size.media_condition()));
1834        }
1835    }
1836
1837    #[test]
1838    fn every_fallback_lands_as_a_class_and_an_unknown_one_lands_plainly() {
1839        let css = run_rules(&Emit::default());
1840        for fallback in [
1841            Fallback::Wrap,
1842            Fallback::Stack,
1843            Fallback::Shed,
1844            Fallback::Menu,
1845        ] {
1846            let class = fallback_class(fallback);
1847            assert!(css.contains(&format!(".{class} {{")), "{class} unemitted");
1848        }
1849        // Stack is the one that also says what a member does with the line it
1850        // took, which is what separates it from wrapping.
1851        assert!(css.contains(".run-stack > * {\n    flex: 1 1 max-content;\n}"));
1852    }
1853
1854    #[test]
1855    fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
1856        // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
1857        // deletion, not a redesign, or nobody will take it.
1858        let opts = Emit::default();
1859        assert_eq!(
1860            bevel_shadow(Bevel::Raised, &opts),
1861            "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
1862        );
1863        assert_eq!(
1864            bevel_shadow(Bevel::Inset, &opts),
1865            "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
1866        );
1867    }
1868
1869    #[test]
1870    fn no_colour_ever_reaches_the_output() {
1871        let css = stylesheet(&Emit::default());
1872        assert!(!css.contains('#'), "a hex literal escaped into the CSS");
1873        assert!(
1874            !css.contains("rgb"),
1875            "a colour function escaped into the CSS"
1876        );
1877        // Every colour is named, never resolved.
1878        assert!(css.contains("var(--surface-raised)"));
1879        assert!(css.contains("var(--bevel-light)"));
1880    }
1881
1882    #[test]
1883    fn a_well_falls_back_through_css_rather_than_through_rust() {
1884        assert_eq!(
1885            fill_var(Fill::Well),
1886            "var(--surface-well, var(--surface-page))"
1887        );
1888        // Nothing else needs one.
1889        assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
1890        assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
1891    }
1892
1893    #[test]
1894    fn raised_and_well_do_not_collapse_onto_each_other() {
1895        let css = depth_rules(&Emit::default());
1896        assert!(css.contains(".raised {"));
1897        assert!(css.contains(".well {"));
1898        assert!(css.contains("var(--bevel-raised)"));
1899        assert!(css.contains("var(--bevel-inset)"));
1900    }
1901
1902    /// The cast shadow is composed here from the tone `makeover` derives, so
1903    /// neither crate has to hold the other's numbers.
1904    ///
1905    /// It is a `:root` property and deliberately not a depth class. There is no
1906    /// `Depth::Overlay` in the description layer, and adding one would be a
1907    /// claim about what a screen means rather than about how it is painted;
1908    /// until something asks for it, a consumer names the property on the rule
1909    /// for the menu or the toast it already has.
1910    #[test]
1911    fn the_cast_shadow_is_a_root_property_not_a_depth() {
1912        let css = bevel_properties(&Emit::default());
1913        assert!(css.contains("--elevation-overlay:"));
1914        assert!(css.contains("var(--elevation)"));
1915        assert!(
1916            !depth_rules(&Emit::default()).contains("elevation"),
1917            "elevation is not a depth class"
1918        );
1919    }
1920
1921    #[test]
1922    fn the_cascade_carries_the_pressed_state() {
1923        let css = surface_rules(&Emit::default());
1924        // The one thing this renderer gets free that the other two resolve by
1925        // hand, eighteen call sites deep in audiofiles' case. Asserted on a
1926        // named surface: pressing belongs to the control, not to the depth.
1927        assert!(css.contains(".card:active {"));
1928        assert!(css.contains(".button:active {"));
1929    }
1930
1931    #[test]
1932    fn the_depth_class_is_a_surface_and_not_a_control() {
1933        let css = depth_rules(&Emit::default());
1934        // The static surface the vocabulary was missing. Sixteen goingson
1935        // elements wore .card and cancelled its hover and press to get this,
1936        // because a raised object that is not pressable had no other spelling.
1937        for state in [":hover", ":active", ":focus-visible", ":disabled"] {
1938            assert!(
1939                !css.contains(&format!(".raised{state}")),
1940                "the depth class claimed {state}: {css}"
1941            );
1942        }
1943        assert!(css.contains("var(--bevel-raised)"), "still raised: {css}");
1944    }
1945
1946    #[test]
1947    fn pressing_moves_the_fill_and_not_only_the_edge() {
1948        // The decision-1 guard, and the regression that mattered: emitting the
1949        // bevel flip alone is what left goingson hand-writing `background:
1950        // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
1951        // of the three could be deleted.
1952        let pressed = interactive_rules("button", Depth::Raised, &Emit::default());
1953        assert!(pressed.contains(".button:active {"));
1954        assert!(
1955            pressed.contains("background: var(--surface-well, var(--surface-page))"),
1956            "pressed dropped its fill: {pressed}"
1957        );
1958        assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
1959    }
1960
1961    #[test]
1962    fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
1963        // goingson presses to --surface-sunken. The description says a pressed
1964        // raised region reads as a well, and makeover says outright that
1965        // surface-sunken cannot serve as one, so the app is the thing that
1966        // moves.
1967        //
1968        // Scoped to the pressed rules rather than to the whole sheet: since
1969        // makeover-layout 0.3.0 an unchosen tab is legitimately
1970        // --surface-sunken, so the token appearing somewhere in the output no
1971        // longer means the app's choice leaked in.
1972        let css = stylesheet(&Emit::default());
1973        let mut checked = 0;
1974        for rule in css.split("}\n") {
1975            if !rule.contains(":active") {
1976                continue;
1977            }
1978            checked += 1;
1979            assert!(
1980                !rule.contains("surface-sunken"),
1981                "a pressed rule took the app's fill: {rule}"
1982            );
1983        }
1984        assert!(checked > 0, "no pressed rules found to check");
1985        assert_eq!(
1986            Depth::Raised.pressed().fill(),
1987            Some(Fill::Well),
1988            "the description changed under us"
1989        );
1990    }
1991
1992    #[test]
1993    fn the_whole_stylesheet_is_emitted_in_the_family_layer() {
1994        // The point of 0.11.0. Unlayered normal declarations outrank every
1995        // named layer, so an app declaring `@layer base, components` loses
1996        // every rule it owns to this file until this file is layered too.
1997        let css = stylesheet(&Emit::default());
1998        assert!(css.contains(&format!("@layer {CSS_LAYER} {{")));
1999
2000        // Exactly one layer block, and nothing outside it but the banner.
2001        assert_eq!(css.matches("@layer").count(), 2, "banner names it once");
2002        let opened = css.find("@layer makeover {").expect("layer opens");
2003        for (i, line) in css.lines().enumerate() {
2004            let before_layer = css.lines().take(i).map(str::len).sum::<usize>() < opened;
2005            if before_layer || line.is_empty() {
2006                continue;
2007            }
2008            assert!(
2009                line.starts_with("    ") || line == "}" || line.starts_with("   "),
2010                "line outside the layer: {line:?}"
2011            );
2012        }
2013    }
2014
2015    #[test]
2016    fn the_generated_sheet_carries_no_trailing_whitespace() {
2017        // A checked-in generated file that a formatter wants to rewrite is a
2018        // diff every time somebody saves it.
2019        let css = stylesheet(&Emit::default());
2020        for (i, line) in css.lines().enumerate() {
2021            assert_eq!(line, line.trim_end(), "trailing whitespace on line {i}");
2022        }
2023    }
2024
2025    #[test]
2026    fn the_banner_tells_an_app_how_to_order_the_layer() {
2027        // Without a declared order the layer's position depends on which
2028        // generated file the browser sees first, which is not a contract.
2029        let css = stylesheet(&Emit::default());
2030        assert!(css.contains("@layer makeover, base, components, responsive;"));
2031        // And the banner is outside the layer, not a rule inside it.
2032        assert!(css.starts_with("/* Generated by makeover-webview"));
2033    }
2034
2035    #[test]
2036    fn a_primitive_owns_every_state_it_implies() {
2037        // The whole point of 0.10.0. Anything emitting a hover rule owes the
2038        // other three, or the consuming app supplies them by out-specifying a
2039        // rule it does not own: 19 such rules in goingson, 21 in the MNW
2040        // server, and three focus rings that do not match.
2041        let css = stylesheet(&Emit::default());
2042        for selector in ["button", "card", "chip", "tab", "segment", "toggle"] {
2043            assert!(css.contains(&format!(".{selector}:hover {{")), "{selector}");
2044            assert!(
2045                css.contains(&format!(".{selector}:active {{")),
2046                "{selector}"
2047            );
2048            assert!(
2049                css.contains(&format!(".{selector}:focus-visible {{")),
2050                "{selector} has no focus ring"
2051            );
2052            assert!(
2053                css.contains(&format!(".{selector}:disabled,")),
2054                "{selector} has no disabled state"
2055            );
2056        }
2057    }
2058
2059    #[test]
2060    fn a_field_takes_focus_and_refuses_input_without_taking_a_hover() {
2061        // A text field does not light up under the pointer, so it gets the two
2062        // states it has and not the two it does not.
2063        let css = stylesheet(&Emit::default());
2064        assert!(css.contains(".field:focus-visible {"));
2065        assert!(css.contains(".field:disabled,"));
2066        assert!(!css.contains(".field:hover {"));
2067        assert!(!css.contains(".field:active {"));
2068    }
2069
2070    #[test]
2071    fn disabled_is_emitted_after_hover_so_source_order_settles_it() {
2072        // Every one of these selectors is specificity (0,2,0), so nothing but
2073        // order decides which wins. A disabled button taking the hover fill is
2074        // the exact bug goingson's `.button:disabled:hover` was written to fix,
2075        // and the reason it had to reach (0,3,0) to do it.
2076        let css = interactive_rules("button", Depth::Raised, &Emit::default());
2077        let hover = css.find(":hover").expect("hover");
2078        let active = css.find(":active").expect("active");
2079        let focus = css.find(":focus-visible").expect("focus");
2080        let disabled = css.find(":disabled").expect("disabled");
2081        assert!(hover < active && active < focus && focus < disabled);
2082
2083        // And it restores the surface, or the hover fill survives underneath.
2084        let tail = &css[disabled..];
2085        assert!(tail.contains("background: var(--surface-raised)"));
2086    }
2087
2088    #[test]
2089    fn a_disabled_state_reaches_things_that_cannot_be_disabled() {
2090        // `:disabled` matches form elements only, and a chip is a div. Keying
2091        // on the ARIA attribute too is the pattern the invalid field already
2092        // set: one fact, read by the styling and the accessibility tree alike.
2093        let css = disabled_rule("chip", Depth::Raised);
2094        assert!(css.contains(".chip:disabled,"));
2095        assert!(css.contains(".chip[aria-disabled=\"true\"]"));
2096        assert!(css.contains("cursor: not-allowed"));
2097    }
2098
2099    #[test]
2100    fn the_focus_ring_does_not_disturb_the_bevel_it_lands_on() {
2101        // `outline` has its own property, so unlike the invalid ring there is
2102        // no bevel to restate beside it and nothing to keep in agreement.
2103        let opts = Emit::default();
2104        let css = focus_rule("button", Depth::Raised, &opts);
2105        assert!(css.contains("outline: 2px solid var(--focus-ring)"));
2106        assert!(!css.contains("box-shadow"), "the ring restated the bevel");
2107    }
2108
2109    #[test]
2110    fn a_well_takes_the_ring_inside_and_a_raised_surface_outside() {
2111        // One ring, placed by depth. The offset comes off `Depth::bevel` and
2112        // not off a per-component choice, which is what gave three apps three
2113        // different rings.
2114        let opts = Emit::default();
2115        assert!(focus_rule("field", Depth::Well, &opts).contains("outline-offset: calc(-1 * 2px)"));
2116        assert!(focus_rule("button", Depth::Raised, &opts).contains("outline-offset: 2px"));
2117        // Nothing to sit inside of, so it sits outside.
2118        assert!(focus_rule("badge", Depth::Sunken, &opts).contains("outline-offset: 2px"));
2119
2120        // And the ring is not the bevel. Reusing border_width emitted a 1px
2121        // ring that every consumer had already overridden.
2122        assert_ne!(opts.focus_width, opts.border_width);
2123    }
2124
2125    #[test]
2126    fn hover_is_gated_on_capability_and_the_keyboard_path_is_not() {
2127        // goingson's section 60 exists only to take back the hover state this
2128        // crate handed it. Gating at the source is what deletes that section
2129        // in all three apps rather than having each fight for it.
2130        let css = stylesheet(&Emit::default());
2131        let condition = format!("@media {}", Density::Pointer.media_condition());
2132        assert!(css.contains(&condition));
2133
2134        // What is gated is every hover state the surfaces carry. The row's
2135        // actions used to be the other half of this test and are not gated any
2136        // more, because they are not hidden any more: a rule that reveals
2137        // nothing needs no capability answer.
2138        let gated: Vec<&str> = css.lines().filter(|line| line.contains(":hover")).collect();
2139        assert!(!gated.is_empty(), "{css}");
2140        for line in gated {
2141            let indent = line.len() - line.trim_start().len();
2142            assert!(indent > 4, "an ungated hover rule: {line}");
2143        }
2144        assert!(!css.contains(".row:hover"), "{css}");
2145    }
2146
2147    #[test]
2148    fn the_capability_answer_is_asked_for_and_not_assumed() {
2149        // Both halves come from the crates that own them. If `makeover-touch`
2150        // ever says a fingertip has hover, this stops gating on its own.
2151        assert!(!Affordance::Hover.available(Density::Touch, SizeClass::Compact));
2152        assert!(Affordance::Hover.available(Density::Pointer, SizeClass::Compact));
2153        assert_eq!(hover_condition(), Some(Density::Pointer.media_condition()));
2154
2155        // And the size class passed to that call is not a claim about width.
2156        assert!(Affordance::Hover.reads_density());
2157        for size in [SizeClass::Compact, SizeClass::Medium, SizeClass::Expanded] {
2158            assert!(!Affordance::Hover.available(Density::Touch, size));
2159        }
2160    }
2161
2162    #[test]
2163    fn hover_resolves_against_the_token_makeover_already_derives() {
2164        let css = interactive_rules("card", Depth::Raised, &Emit::default());
2165        assert!(css.contains(".card:hover {"));
2166        assert!(css.contains("background: var(--hover-surface)"));
2167        // Not the app's choice, which was --surface-overlay.
2168        assert!(!css.contains("surface-overlay"));
2169    }
2170
2171    #[test]
2172    fn a_badge_gets_no_edge_and_no_fill() {
2173        // Decision 2, and the one visible redesign in phase A. Token::Badge is
2174        // Flat: an edge on a label says it can be pressed.
2175        let css = token_rules(&Emit::default());
2176        let badge = css
2177            .lines()
2178            .skip_while(|l| !l.starts_with(".badge {"))
2179            .take_while(|l| !l.starts_with('}'))
2180            .collect::<Vec<_>>()
2181            .join("\n");
2182        assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
2183        assert!(!badge.contains("background"), "badge kept a fill: {badge}");
2184        assert_eq!(Token::Badge.depth(false), Depth::Flat);
2185        assert_eq!(Token::Badge.depth(true), Depth::Flat);
2186    }
2187
2188    #[test]
2189    fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
2190        let css = token_rules(&Emit::default());
2191        // Neutral is the absence of a status, not a status named "none".
2192        assert!(css.contains(".badge {\n    color: var(--content-muted);"));
2193        assert!(!css.contains("data-tone=\"content-muted\""));
2194        for tone in ["info", "success", "warning", "danger"] {
2195            assert!(
2196                css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
2197                "missing tone {tone}"
2198            );
2199            assert!(css.contains(&format!("color: var(--{tone})")));
2200        }
2201    }
2202
2203    #[test]
2204    fn a_chip_is_raised_and_latches_into_a_well() {
2205        let css = token_rules(&Emit::default());
2206        assert!(css.contains(".chip {"));
2207        assert!(css.contains(".chip.latched {"));
2208        assert!(css.contains(".chip:active {"));
2209        // The whole difference from a badge: it answers a click.
2210        assert!(Token::Chip { removable: false }.interactive());
2211        assert!(!Token::Badge.interactive());
2212    }
2213
2214    #[test]
2215    fn only_a_tab_comes_forward_when_chosen() {
2216        // The folder semantic. Collapsing the three selectors would lose it.
2217        let css = selector_rules(&Emit::default());
2218        assert!(css.contains(".tab.chosen {"));
2219        assert!(css.contains(".segment.chosen {"));
2220        assert!(css.contains(".toggle.chosen {"));
2221        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
2222        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2223        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
2224
2225        let tab = css
2226            .lines()
2227            .skip_while(|l| !l.starts_with(".tab.chosen {"))
2228            .take_while(|l| !l.starts_with('}'))
2229            .collect::<Vec<_>>()
2230            .join("\n");
2231        assert!(
2232            tab.contains("var(--bevel-raised)"),
2233            "tab was held in: {tab}"
2234        );
2235    }
2236
2237    #[test]
2238    fn an_unchosen_tab_recedes_without_looking_picked() {
2239        let css = selector_rules(&Emit::default());
2240        // Recessed by colour and given no edge. An edge would make every option
2241        // look picked; flat would leave the chosen one nothing to come forward
2242        // from, which is the gap makeover-layout 0.3.0 closed.
2243        assert!(
2244            css.contains(".tab {\n    background: var(--surface-sunken);\n}"),
2245            "unchosen tab is not recessed: {css}"
2246        );
2247        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
2248        assert!(css.contains(".tab:hover {"));
2249    }
2250
2251    #[test]
2252    fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
2253        // The inverse of the tab, and why the three selectors are not one
2254        // member with a flag.
2255        let css = selector_rules(&Emit::default());
2256        assert!(css.contains(".segment {\n    background: var(--surface-raised);"));
2257        assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
2258        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2259    }
2260
2261    #[test]
2262    fn a_rows_actions_are_shown_at_rest() {
2263        let css = row_rules(&Emit::default());
2264
2265        // The hover reveal is gone, and with it every escape it needed. What
2266        // it hid was hidden from pointer users alone, who are the ones
2267        // scanning a list to learn what can be done to a row.
2268        assert!(!css.contains("opacity"), "{css}");
2269        assert!(!css.contains("pointer-events"), "{css}");
2270        assert!(!css.contains(":hover"), "{css}");
2271        assert!(!css.contains(":focus-within"), "{css}");
2272
2273        // Nor is it hidden any other way. `display: none` would reflow the row
2274        // and `visibility: hidden` would take the actions out of the focus
2275        // order; the point is that neither is reached for.
2276        assert!(!css.contains("display: none"), "{css}");
2277        assert!(!css.contains("visibility:"), "{css}");
2278    }
2279
2280    #[test]
2281    fn a_figures_tone_lands_on_the_delta_when_there_is_one() {
2282        // 0.13.0. The delta is the part that reads as good or bad; the number
2283        // itself is an ordinary fact. A figure with no delta has nowhere else to
2284        // put the colour, so the value takes it, and `:has` is what lets one
2285        // attribute mean both without the emitter choosing an element.
2286        let css = stylesheet(&Emit::default());
2287
2288        assert!(
2289            css.contains(".figure[data-tone=\"success\"] > .figure-change"),
2290            "{css}"
2291        );
2292        assert!(
2293            css.contains(
2294                ".figure[data-tone=\"success\"]:not(:has(> .figure-change)) > .figure-value"
2295            ),
2296            "{css}"
2297        );
2298        // The caption is the noun and never takes the tone.
2299        assert!(
2300            !css.contains("[data-tone=\"success\"] > .figure-caption"),
2301            "{css}"
2302        );
2303    }
2304
2305    #[test]
2306    fn the_three_text_parts_take_their_intents_and_actions_inherits() {
2307        let css = row_rules(&Emit::default());
2308        assert!(css.contains(".row-primary {\n    color: var(--content);"));
2309        assert!(css.contains(".row-secondary {\n    color: var(--content-secondary);"));
2310        assert!(css.contains(".row-meta {\n    color: var(--content-muted);"));
2311        // Actions carry controls, not text. Pinning the colour it would inherit
2312        // anyway is louder than saying nothing.
2313        assert!(!css.contains(".row-actions {\n    color:"));
2314    }
2315
2316    #[test]
2317    fn the_token_strip_takes_no_colour_of_its_own() {
2318        // makeover-layout 0.9.0. A token carries its own tone, so a colour on
2319        // the strip would be a rule fighting the things sitting in it -- the
2320        // same reasoning as actions, reached for a different reason.
2321        let css = row_rules(&Emit::default());
2322        assert!(!css.contains(".row-tokens {\n    color:"));
2323    }
2324
2325    #[test]
2326    fn an_unknown_row_part_renders_plainly_rather_than_failing_to_build() {
2327        // What `#[non_exhaustive]` bought and what it cost. `part_class` can no
2328        // longer be exhaustive, so a member added upstream lands as a bare
2329        // class with no rule instead of stopping the build. Asserting the
2330        // fallback exists is what keeps it from being written as `unreachable!`
2331        // by someone who reads the match as closed.
2332        assert_eq!(part_class(RowPart::Tokens), "row-tokens");
2333        assert_eq!(part_class(RowPart::Meta), "row-meta");
2334    }
2335
2336    #[test]
2337    fn a_link_takes_the_action_colour_the_theme_actually_defines() {
2338        // `--action-primary` shipped here for months and no theme has ever
2339        // defined it, so every `.link` dropped its colour declaration outright
2340        // and fell back to inherited text. Nothing caught it because the sheet
2341        // is valid CSS either way; MNW's no-undefined-token lint is what found
2342        // it, 2026-08-14. The hover arm two lines below was always `--action-hover`,
2343        // which is what makes the typo legible in hindsight.
2344        let css = link_rules(&Emit::default());
2345        assert!(css.contains("color: var(--action);"));
2346        assert!(!css.contains("--action-primary"));
2347        assert!(css.contains("color: var(--action-hover);"));
2348    }
2349
2350    #[test]
2351    fn the_progress_trough_is_a_well() {
2352        let css = progress_rules(&Emit::default());
2353        assert!(css.contains(".progress {"));
2354        assert!(css.contains("box-shadow: var(--bevel-inset)"));
2355        assert!(css.contains(".progress > .progress-fill {"));
2356        assert!(css.contains("background: var(--action)"));
2357        // A bare `.fill` would catch things that have nothing to do with
2358        // progress once the sheet lands unprefixed.
2359        assert!(!css.contains("> .fill "));
2360    }
2361
2362    #[test]
2363    fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
2364        let css = progress_rules(&Emit::default());
2365        // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
2366        // status is still reporting progress, and muted would read as disabled.
2367        assert!(css.contains(".progress > .progress-fill {\n    background: var(--action);"));
2368        assert!(!css.contains("progress-fill {\n    color: var(--content-muted)"));
2369        for tone in ["info", "success", "warning", "danger"] {
2370            assert!(
2371                css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
2372                "missing progress tone {tone}"
2373            );
2374        }
2375        // goingson's two live cases, which is why the tones are emitted at all.
2376        assert!(css.contains("[data-tone=\"success\"] {\n    background: var(--success);"));
2377        assert!(css.contains("[data-tone=\"danger\"] {\n    background: var(--danger);"));
2378    }
2379
2380    #[test]
2381    fn no_scrollbar_track_is_emitted() {
2382        // Decision 3's negative half. It was on the phase A list and came off;
2383        // this is what stops it drifting back in.
2384        let css = stylesheet(&Emit::default());
2385        assert!(!css.contains("scrollbar"));
2386        assert!(!css.contains("::-webkit"));
2387    }
2388
2389    #[test]
2390    fn an_invalid_field_is_ringed_without_being_lit() {
2391        let css = surface_rules(&Emit::default());
2392        assert!(css.contains(".field {"));
2393        // The ARIA attribute, not a class: one fact, read by both the visual
2394        // and the accessible state, so they cannot drift.
2395        assert!(css.contains(".field[aria-invalid=\"true\"] {"));
2396        assert!(!css.contains(".field.invalid"));
2397        // A flat ring: this edge says "wrong", and a two-tone bevel would have
2398        // it say "raised" at the same time.
2399        assert!(css.contains("0 0 0 1px var(--danger)"));
2400    }
2401
2402    #[test]
2403    fn an_invalid_field_keeps_the_well_underneath_it() {
2404        // box-shadow is not additive. A lone ring replaces the bevel and drops
2405        // the well out from under the field, which is what this emitted before
2406        // 0.5.0 and is the whole reason the rule composes.
2407        let css = surface_rules(&Emit::default());
2408        let invalid = css
2409            .lines()
2410            .skip_while(|l| !l.starts_with(".field[aria-invalid"))
2411            .take_while(|l| !l.starts_with('}'))
2412            .collect::<Vec<_>>()
2413            .join("\n");
2414        assert!(
2415            invalid.contains("var(--bevel-inset)"),
2416            "the well was dropped: {invalid}"
2417        );
2418        assert!(invalid.contains("var(--danger)"));
2419    }
2420
2421    #[test]
2422    fn button_and_card_come_out_identical_by_construction() {
2423        // The duplication phase A deletes. They are the same composition, so
2424        // the only honest way to emit both is from one call.
2425        let opts = Emit::default();
2426        let css = surface_rules(&opts);
2427        assert_eq!(
2428            depth_declarations(Depth::Raised),
2429            depth_declarations(Depth::Raised)
2430        );
2431        assert!(css.contains(".button {"));
2432        assert!(css.contains(".card {"));
2433        assert_eq!(
2434            interactive_rules("button", Depth::Raised, &Emit::default()).replace("button", "card"),
2435            interactive_rules("card", Depth::Raised, &Emit::default())
2436        );
2437    }
2438
2439    #[test]
2440    fn a_prefix_reaches_the_component_classes_too() {
2441        let opts = Emit {
2442            class_prefix: "mo-",
2443            ..Emit::default()
2444        };
2445        let css = stylesheet(&opts);
2446        for name in [
2447            "mo-button",
2448            "mo-card",
2449            "mo-field",
2450            "mo-badge",
2451            "mo-chip",
2452            "mo-tab",
2453            "mo-row-primary",
2454            "mo-progress",
2455            "mo-progress-fill",
2456        ] {
2457            assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
2458        }
2459        // The bare names must be gone entirely, or a prefixed build still
2460        // collides with the app's own stylesheet.
2461        assert!(!css.contains(".button {"));
2462        assert!(!css.contains(".card {"));
2463        assert!(!css.contains(".badge {"));
2464    }
2465
2466    #[test]
2467    fn the_class_a_renderer_puts_on_an_option_is_the_one_the_rules_key_off() {
2468        // `option_class` is the contract a screen renderer writes markup
2469        // against, and the rules below are the other half of it. They come off
2470        // one mapping now, so this asserts the mapping is the one that reaches
2471        // the stylesheet rather than that two lists still agree.
2472        let css = stylesheet(&Emit::default());
2473        for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
2474            let name = option_class(selector);
2475            assert!(css.contains(&format!(".{name} {{")), "{name}: {css}");
2476            assert!(css.contains(&format!(".{name}.chosen {{")), "{name}: {css}");
2477        }
2478        assert_eq!(option_class(Selector::Tabs), "tab");
2479    }
2480
2481    #[test]
2482    fn the_caret_brings_its_own_gap_and_is_the_glyph_the_description_names() {
2483        let css = stylesheet(&Emit::default());
2484
2485        // The space is inside the glyph, which is what the other two renderers
2486        // write. Emitted bare, every consumer has to add it back, and the
2487        // obvious way to add it -- `content` in an app stylesheet, which is
2488        // unlayered and so outranks this sheet -- deletes the caret instead.
2489        assert!(css.contains("content: \" \\25B2\";"), "{css}");
2490        assert!(css.contains("content: \" \\25BC\";"), "{css}");
2491        assert!(!css.contains("content: \"\\2"), "{css}");
2492
2493        // The arrows this renderer used to draw alone are gone. Composition
2494        // rather than agreement: the glyph comes from `Sort::glyph`, so a
2495        // fourth spelling cannot appear here without appearing everywhere.
2496        assert!(!css.contains("2191") && !css.contains("2193"), "{css}");
2497        assert!(css.contains(&css_escape(Sort::Ascending.glyph())), "{css}");
2498
2499        // Three states, three tones. An idle sortable heading draws its caret
2500        // now rather than reserving a hidden box for it, so there is no
2501        // visibility to order and no reflow left to guard against; what
2502        // separates the states is the colour, and the sorted arms come after
2503        // the idle one because the specificity is the same.
2504        let idle = css
2505            .find(".table-heading[data-sortable]::after")
2506            .expect("the idle caret is emitted");
2507        let sorted = css
2508            .find(".table-heading[aria-sort=\"ascending\"]::after")
2509            .expect("the ascending caret is emitted");
2510        assert!(idle < sorted, "{css}");
2511        assert!(
2512            css[idle..sorted].contains("color: var(--content-secondary);"),
2513            "{css}"
2514        );
2515        assert!(css[sorted..].contains("color: var(--content);"), "{css}");
2516        assert!(!css.contains("visibility: hidden;"), "{css}");
2517    }
2518
2519    #[test]
2520    fn a_destructive_button_has_somewhere_for_its_tone_to_land() {
2521        let css = component_rules(&Emit::default());
2522
2523        for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
2524            assert!(
2525                css.contains(&format!(".button[data-tone=\"{}\"]", tone.token())),
2526                "{css}"
2527            );
2528        }
2529        // Colour, not a fill. A red surface is an app's decision about emphasis.
2530        assert!(!css.contains(".button[data-tone=\"danger\"] {\n    background"));
2531    }
2532
2533    #[test]
2534    fn a_described_list_is_not_a_bulleted_list() {
2535        let css = component_rules(&Emit::default());
2536        assert!(css.contains(".list {\n    list-style: none;"), "{css}");
2537    }
2538
2539    #[test]
2540    fn a_table_lays_itself_out_without_being_told_its_columns() {
2541        // The whole point of the CSS table. A described table's columns are
2542        // known at render time, so anything the stylesheet has to be told about
2543        // them would have to travel with the markup.
2544        let css = component_rules(&Emit::default());
2545
2546        assert!(css.contains(".table {\n    display: table;"), "{css}");
2547        assert!(css.contains("display: table-row;"), "{css}");
2548        assert!(css.contains("display: table-cell;"), "{css}");
2549        assert!(!css.contains("grid-template-columns"), "{css}");
2550    }
2551
2552    #[test]
2553    fn a_control_in_a_cell_is_not_painted_as_text() {
2554        // The point of makeover-layout 0.14.0's CellPart, and the table-side
2555        // twin of `the_three_text_parts_take_their_intents_and_actions_inherits`
2556        // above. One `.cell` and one content colour meant a button in a cell
2557        // inherited it.
2558        let css = table_rules(&Emit::default());
2559
2560        assert!(
2561            css.contains(".cell-value {\n    color: var(--content);"),
2562            "{css}"
2563        );
2564        assert!(!css.contains(".cell-actions {\n    color:"), "{css}");
2565        assert!(!css.contains(".cell-tokens {\n    color:"), "{css}");
2566        assert!(!css.contains(".cell-link {\n    color:"), "{css}");
2567
2568        // The colour is on the part that is text, never on the container. On
2569        // `.cell` it would cascade into the three parts that are not text,
2570        // which is the bug written as one rule.
2571        assert!(!css.contains(".cell {\n    color:"), "{css}");
2572    }
2573
2574    #[test]
2575    fn an_unknown_cell_part_renders_plainly_rather_than_failing_to_build() {
2576        // `part_class`'s obligation, taken on for the table side too. CellPart
2577        // is `#[non_exhaustive]`, so a member added upstream must land as a
2578        // bare class rather than as a build that stops.
2579        assert_eq!(cell_part_class(CellPart::Value), "cell-value");
2580        assert_eq!(cell_part_class(CellPart::Actions), "cell-actions");
2581    }
2582
2583    #[test]
2584    fn a_column_drops_by_its_priority_and_never_by_its_position() {
2585        let css = component_rules(&Emit::default());
2586
2587        // Optional goes at the narrowest class and secondary goes with it,
2588        // which is `kept_at`'s cutoff walk said as two queries.
2589        let compact = css
2590            .find(&format!("@media {}", SizeClass::Compact.media_condition()))
2591            .expect("a compact query");
2592        let medium = css
2593            .find(&format!("@media {}", SizeClass::Medium.media_condition()))
2594            .expect("a medium query");
2595        assert!(css[compact..].contains(".cell-drops-next"), "{css}");
2596        assert!(!css[medium..].contains(".cell-drops-next"), "{css}");
2597
2598        // Essential columns are never mentioned, because not being mentioned is
2599        // already what never dropping means.
2600        assert!(!css.contains(".cell-keeps"), "{css}");
2601
2602        // And nothing counts. `nth-child` is the bug the priority vocabulary
2603        // exists to end.
2604        assert!(!css.contains("nth-child"), "{css}");
2605    }
2606
2607    #[test]
2608    fn a_track_places_by_custom_property_and_never_by_a_size() {
2609        let css = track_rules(&Emit::default());
2610
2611        // Placement arrives from the caller, computed once by Track::fraction.
2612        // If either of these becomes a literal, three renderers have started
2613        // disagreeing about where 09:30 is.
2614        assert!(css.contains("top: var(--track-at"), "{css}");
2615        assert!(css.contains("height: var(--track-for"), "{css}");
2616
2617        // Overlap lanes default so an entry naming neither is full width.
2618        assert!(css.contains("--track-lane, 0"), "{css}");
2619        assert!(css.contains("--track-lanes, 1"), "{css}");
2620
2621        // The refusal that matters. A slot height here would be this crate
2622        // deciding how tall a quarter of an hour is, which is the thing
2623        // makeover-geometry owns and the reason `.track` gets no height at all.
2624        assert!(!css.contains("height: var(--track-slot"), "{css}");
2625        for size in ["px", "rem", "em", "vh"] {
2626            let bare = css
2627                .lines()
2628                .filter(|l| !l.contains("var(--"))
2629                .any(|l| l.contains(size));
2630            assert!(!bare, "track_rules named a {size} outside a var(): {css}");
2631        }
2632    }
2633
2634    #[test]
2635    fn a_relaxed_part_clamps_and_a_tight_one_says_nothing() {
2636        let css = stylesheet(&Emit::default());
2637        assert!(css.contains(".row-relaxed {"));
2638        assert!(css.contains("-webkit-line-clamp: 2;"));
2639        // The count is `Flow`'s, not this crate's. If the tier ever means three
2640        // lines, this fails here rather than in an app.
2641        assert!(css.contains(&format!("line-clamp: {};", Flow::Relaxed.lines())));
2642        // Tight gets no rule at all: one line is what a run already does, and a
2643        // class per part saying so is a declaration that changes nothing.
2644        assert!(!css.contains("row-tight"));
2645        assert_eq!(crate::list::flow_class(Flow::Relaxed), Some("row-relaxed"));
2646        assert_eq!(crate::list::flow_class(Flow::Tight), None);
2647        // Emitted, therefore checkable: an app's dead-vocabulary seal and the
2648        // overlap check both read `vocabulary::names`, so a class the renderer
2649        // can write and that list does not carry is invisible to both.
2650        assert!(crate::vocabulary::names(&Emit::default()).contains("row-relaxed"));
2651    }
2652
2653    #[test]
2654    fn the_whole_sheet_still_names_every_colour() {
2655        // The crate's founding property, asserted over the component layer and
2656        // not only the primitives.
2657        let css = stylesheet(&Emit::default());
2658        assert!(!css.contains('#'));
2659        assert!(!css.contains("rgb"));
2660        for line in css.lines() {
2661            // Declarations only: a selector or an at-rule can carry a colon of
2662            // its own (`:root`, `:hover`, `@media (hover: hover)`) and declares
2663            // nothing. Keyed on the trailing semicolon rather than on leading
2664            // indentation, which only ever worked as a proxy for nesting depth
2665            // and stopped when the sheet gained a cascade layer around it.
2666            let trimmed = line.trim();
2667            if !trimmed.ends_with(';') {
2668                continue;
2669            }
2670            let Some((_, value)) = trimmed.split_once(": ") else {
2671                continue;
2672            };
2673            if value.contains("var(--") {
2674                continue;
2675            }
2676            // Everything left has to be a keyword, a number or a
2677            // caller-supplied length, never a colour.
2678            //
2679            // The length arm is what the comment above always claimed and the
2680            // list never covered: `border_width` arrives from `Emit` and lands
2681            // bare in the focus ring's offset, where the bevel had only ever
2682            // used it inside an `inset` shadow.
2683            let opts = Emit::default();
2684            assert!(
2685                value.contains("inset")
2686                    || value.contains(opts.border_width)
2687                    || value.contains(opts.focus_width)
2688                    // 0.12.0's two: a sortable header is a control and says so
2689                    // with the pointer, and the caret is this renderer's own
2690                    // expression of `aria-sort`. Neither is a colour, which is
2691                    // what this test is actually about, and neither is a size,
2692                    // which is the other thing this crate must not name. The
2693                    // leading space inside the glyph is the same thing the other
2694                    // two renderers write into theirs, so it is part of the
2695                    // caret rather than spacing this crate decided on.
2696                    || value
2697                        .trim_start_matches('"')
2698                        .trim_start()
2699                        .starts_with("\\2")
2700                    || matches!(
2701                        value.trim_end_matches(';'),
2702                        "0" | "1"
2703                            | "none"
2704                            | "auto"
2705                            | "not-allowed"
2706                            | "pointer"
2707                            // The caret's reserved box. Visibility is presence,
2708                            // not magnitude and not colour.
2709                            | "hidden"
2710                            | "visible"
2711                            // The link's two signals. `underline` is a line and
2712                            // `inherit` defers to whatever the app set, so
2713                            // neither names a colour or a magnitude.
2714                            | "underline"
2715                            | "inherit"
2716                            // The table frame. `display` is structure and not a
2717                            // size; `nowrap` is what makes a content column
2718                            // content. The two widths are the awkward pair and
2719                            // they are still not sizes: `100%` is "all of
2720                            // whatever you were given" and `1%` is the CSS
2721                            // table idiom for "shrink to fit", which is a
2722                            // behaviour spelled as a number because CSS has no
2723                            // keyword for it. Neither names a magnitude, which
2724                            // is the thing this crate leaves to
2725                            // makeover-geometry.
2726                            | "table"
2727                            | "table-row"
2728                            | "table-cell"
2729                            | "nowrap"
2730                            | "100%"
2731                            | "1%"
2732                            // The time axis, 0.42.0. `position` is the one
2733                            // property whose whole job is where a thing sits,
2734                            // which is exactly what this crate spent its life
2735                            // refusing to say -- so it is worth being exact
2736                            // about why these two are not that refusal
2737                            // breaking.
2738                            //
2739                            // Neither names a magnitude. `relative` says the
2740                            // track is what its entries resolve against, and
2741                            // `absolute` says an entry is placed rather than
2742                            // flowed. *Where* each entry lands is
2743                            // `--track-at` and `--track-for`, custom
2744                            // properties the caller sets from
2745                            // `Track::fraction`, and they are skipped by the
2746                            // `var(--` arm above like every other value this
2747                            // crate refuses to decide.
2748                            //
2749                            // The rule that would break the refusal is a slot
2750                            // height, and there is none: the track's height is
2751                            // the app's, so the percentages have something to
2752                            // resolve against and this crate still never says
2753                            // how tall a day is.
2754                            | "relative"
2755                            | "absolute"
2756                            // A run's five, 0.49.0. `flex`, `wrap` and
2757                            // `center` are structure and alignment, the same
2758                            // reading `table` gets: which way members are laid
2759                            // out and how they line up, never how much of
2760                            // anything.
2761                            //
2762                            // The two intrinsic keywords are the interesting
2763                            // pair and they are the opposite of a size. A
2764                            // magnitude is a number somebody chose;
2765                            // `min-content` and `max-content` are the browser
2766                            // being asked what the members themselves come to,
2767                            // which is the derived minimum the room ruling
2768                            // requires and the reason no breakpoint appears
2769                            // anywhere in these rules. `1 1 max-content` is
2770                            // grow, shrink and that basis, so its two digits
2771                            // are ratios rather than lengths.
2772                            | "flex"
2773                            | "wrap"
2774                            | "center"
2775                            | "min-content"
2776                            | "1 1 max-content"
2777                            // A picture's three, 0.36.0. `block` is structure
2778                            // for the reason `table` is: an inline image sits
2779                            // on the baseline and carries a descender's worth
2780                            // of space under it, which is a fact about
2781                            // replaced elements rather than a size this crate
2782                            // chose. `cover` and `contain` are `Fit`'s two
2783                            // named members reaching CSS unchanged, which is
2784                            // an intent arriving rather than a value being
2785                            // picked.
2786                            | "block"
2787                            | "cover"
2788                            | "contain"
2789                            // A relaxed part's three, and the third is the
2790                            // awkward one. `-webkit-box` and `vertical` are
2791                            // structure: they say the part is a box of lines
2792                            // stacked downward, which is the only way CSS lets
2793                            // anyone ask for a clamp at all.
2794                            //
2795                            // `2` is a count of lines, not a length. The
2796                            // distinction this crate holds is between naming a
2797                            // magnitude -- a padding, a height, a font size,
2798                            // all of which belong to makeover-geometry -- and
2799                            // naming how many of something there are. A line's
2800                            // height is still the app's, so two lines is
2801                            // whatever two of the app's lines come to, and
2802                            // nothing here decides how tall that is. It is also
2803                            // not a value picked here: it is `Flow::Relaxed`'s
2804                            // own answer arriving unchanged, the same way
2805                            // `cover` and `contain` are `Fit`'s.
2806                            | "-webkit-box"
2807                            | "vertical"
2808                            | "2"
2809                    ),
2810                "unrecognised literal value: {line}"
2811            );
2812        }
2813    }
2814
2815    #[test]
2816    fn flat_emits_nothing_at_all() {
2817        assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
2818        assert!(!depth_rules(&Emit::default()).contains("flat"));
2819    }
2820
2821    #[test]
2822    fn a_prefix_namespaces_every_class() {
2823        let opts = Emit {
2824            class_prefix: "mo-",
2825            ..Emit::default()
2826        };
2827        let css = depth_rules(&opts);
2828        assert!(css.contains(".mo-raised {"));
2829        assert!(css.contains(".mo-well {"));
2830        assert!(!css.contains(".raised {"));
2831    }
2832
2833    #[test]
2834    fn the_border_width_is_the_callers() {
2835        let opts = Emit {
2836            border_width: "2px",
2837            ..Emit::default()
2838        };
2839        assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
2840    }
2841
2842    #[test]
2843    fn edges_agree_with_the_description() {
2844        // Not a tautology: it is the guard that a CSS-shaped convenience never
2845        // quietly reverses which side is lit.
2846        let (tl, br) = Bevel::Raised.edges();
2847        assert_eq!(tl.token(), Edge::Light.token());
2848        assert_eq!(br.token(), Edge::Dark.token());
2849    }
2850}