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