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//! [`list`] is the other half: column tracks, the narrowing rules, and the cell
46//! containers a row is made of. It stops at the cell boundary and does not
47//! render what goes inside one, on the reasoning in that module. So phase B is
48//! now the frame around content in both directions, and what an app still owns
49//! is the content itself.
50//!
51//! # What phase A settled, and what it costs
52//!
53//! Decided 2026-07-29 against goingson's `styles.css` rather than against a
54//! component list. The useful finding there was that `.btn` (line 644),
55//! `.card` (768) and `.tag, .badge` (882) each hand-write the same
56//! composition, so three quarters of phase A is one rule with several names.
57//!
58//! Two of the four decisions change how goingson looks, and adoption should
59//! not be described as a pure deletion:
60//!
61//! - **Pressed carries its fill.** [`interactive_rules`] emits
62//!   [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
63//!   will press to `--surface-well`, and hovers to `--surface-overlay` today
64//!   and will hover to `--hover-surface`. Since `surface-well` inverts by theme
65//!   where `surface-sunken` does not, a dark theme presses *lighter* than it
66//!   hovers. That falls out of `makeover`'s own derivation, which says outright
67//!   that `surface-sunken` cannot serve as a well, so if it reads wrong the
68//!   answer is there and not here.
69//! - **Badges go flat.** See [`token_rules`].
70//!
71//! The other two: the progress trough is renderer-local and the scrollbar
72//! track was dropped ([`component_rules`]), and no class prefix ships by
73//! default, so adoption means deleting the app's hand-written rule in the same
74//! commit that adds the generated one. `.card`, `.badge` and the tab classes
75//! all already exist in goingson, and while both rules exist the cascade order
76//! decides which wins. That is the one real risk in adopting this, and it is
77//! why the migration lands per component rather than in one commit.
78//!
79//! # 0.10.0: the states this crate used to leave to its consumers
80//!
81//! [`interactive_rules`] emitted hover and pressed and stopped, because
82//! `makeover-layout` modelled no interaction state. Focus and disabled were
83//! therefore unsayable, and every app completed the primitive from outside the
84//! only way that works: by out-specifying a rule it does not own. goingson
85//! carries 19 such rules and the MNW server 21, and the three focus rings do
86//! not match each other.
87//!
88//! That also blocked the cascade-layer work outright. An app that declares
89//! `@layer` puts its own rules in a named layer, and unlayered declarations
90//! outrank every named layer regardless of specificity, so all of those
91//! overrides lose in the commit that adopts layers. They cannot simply be
92//! deleted, because they are the only thing supplying the missing states.
93//! Emitting the states here is what turns that adoption into a deletion.
94//!
95//! Four states now, in emission order, and the order is load-bearing: they are
96//! all specificity (0,2,0), so disabled beats hover by coming last and by
97//! nothing else. Nothing here reaches for `:not(:disabled)`, which would raise
98//! a selector this crate will shortly be wrapping in its own layer.
99//!
100//! Hover additionally sits inside a capability query now. `makeover-touch`
101//! answers whether a fingertip has hover and `makeover-geometry` spells the
102//! condition; this crate asks and does not decide. goingson's section 60 exists
103//! solely to take the hover state back on touch, which is a fight it should
104//! never have been handed.
105//!
106//! # 0.11.0: the layer contract
107//!
108//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
109//! lives in `makeover-geometry` because that is the one crate every CSS emitter
110//! in the family already depends on). `makeover-geometry` 0.6.0 does the same
111//! for `geometry.css`.
112//!
113//! The cascade resolves origin and importance, then layer, then specificity,
114//! then source order, and **unlayered normal declarations outrank every named
115//! layer**. So before this, an app that declared `@layer base, components,
116//! responsive` put every rule it owns into a named layer and lost all of them to
117//! this unlayered file, regardless of specificity and regardless of loading
118//! last. Nothing errors when that happens: the CSS is valid, the minifier is
119//! happy, and buttons and badges look subtly wrong.
120//!
121//! That is why the layer belongs here rather than in each app. An app cannot fix
122//! it from its own stylesheet, because the fix is to layer the file it does not
123//! own.
124//!
125//! **What it flips**, and the reason each app wants a look when it bumps the
126//! pin: a generated rule that currently beats an app rule by being more specific
127//! stops beating it. The direction is always "the app wins", which is what the
128//! apps already assume, but a hand-written rule an app thought was dead can come
129//! back to life.
130//!
131//! An app should declare the order once, or the layer's position is decided by
132//! whichever generated file the browser happens to see first:
133//!
134//! ```css
135//! @layer makeover, base, components, responsive;
136//! ```
137//!
138//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
139//! from this crate's pieces. goingson builds `tables.css` in its own `build.rs`
140//! out of [`list::narrowing_css`] and [`list::grid_template_columns`], and those
141//! rules are as generated as the ones here, so they belong in the same layer and
142//! this crate cannot put them there on the app's behalf.
143//!
144//! # 0.12.0: the ring gets its own width
145//!
146//! [`focus_rule`] reused [`Emit::border_width`] and emitted a 1px ring. That was
147//! an implementation convenience dressed as consistency with the invalid-field
148//! ring: a bevel and a focus indicator answer different questions, and only one
149//! of them has to be noticed from across a desk.
150//!
151//! Caught while adopting 0.11.0 into goingson, by the check the adoption tasks
152//! ask for. Every consumer had already written its own ring and all three chose
153//! at least 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
154//! goingson 2px on three rules and 3px on the one covering twelve selectors. The
155//! design system was the only thing in the tree saying 1px, so deleting the app
156//! rules in favour of it would have thinned the focus indicator everywhere.
157//!
158//! [`Emit::focus_width`] now carries it, defaulting to `2px`, and the offset is
159//! the same magnitude with its sign off the depth. Both values are the measured
160//! consensus rather than a new opinion.
161//!
162//! # 0.25.0: a cell says what it holds
163//!
164//! 0.23.0 gave a table its layout and left every cell the same. One `.cell`
165//! carried the whole thing, so a cell holding text and a cell holding a button
166//! were one class and one content colour, and a control in a cell was painted
167//! as text. That is the drift [`RowPart::intent`](makeover_layout::RowPart)
168//! has prevented for list rows since 0.2.0 and prevented for nothing here.
169//!
170//! makeover-layout 0.14.0's [`CellPart`](makeover_layout::CellPart) names the
171//! four things a cell holds, and [`table_rules`] turns them into
172//! `.cell-value`, `.cell-tokens`, `.cell-actions` and `.cell-link`. Only the
173//! first takes a colour: a token carries its own tone, an action is a control
174//! rather than text, and a link takes the action colour from the anchor it is.
175//!
176//! The colour going on `.cell-value` rather than on `.cell` is the fix rather
177//! than an implementation detail. On the container it cascades into the parts
178//! that are not text, which is the bug said in one rule.
179//!
180//! [`list::Cell::part`] is `Option<CellPart>` here, where it was
181//! `Option<RowPart>`. A table cell borrowing the list row's vocabulary was the
182//! drift with a type on it: the two answer different questions, and only one of
183//! them was ever about a cell.
184//!
185//! # 0.23.0: a table lays itself out, and a row shows its controls
186//!
187//! Three things a description could say and this renderer had no rule for,
188//! found together by rendering the MNW server's SSH-keys settings tab through
189//! `quasi` and preferring the hand-written Askama original.
190//!
191//! **A table had no layout at all.** [`list::narrowing_css`] emits the track
192//! list, and it has to be called with the columns, so it works where the
193//! columns are known at build time: goingson builds `tables.css` in its own
194//! `build.rs` and is untouched. A table a description produced knows its
195//! columns at render time, and the rules would have had to travel with the
196//! markup: a `<style>` element per table, which needs `style-src
197//! 'unsafe-inline'` that the MNW server is working to drop, or the head, which
198//! an htmx fragment swap does not carry. [`table_rules`] lays a table out with
199//! `display: table` instead, which aligns columns across rows knowing nothing
200//! about how many there are. [`Priority`](makeover_layout::Priority) hiding
201//! moves from a generated rule per dropped column to one rule per drop class,
202//! and [`list::column_classes`] is what puts those classes on a cell. A header
203//! row emitted by a renderer's own code should call it too, or the header and
204//! the body disagree about which column just dropped.
205//!
206//! **A destructive button had nowhere for its tone to land.** `.button` carried
207//! no tone, on the reading that a control's colour is its surface. Every
208//! consumer had written the danger rule itself. It joins the badge in taking
209//! the four tones as colour, off `data-tone`.
210//!
211//! **A list rendered as a bulleted list**, because nothing here reset the `ul`
212//! a renderer emits for one.
213//!
214//! `RowPart::revealed_on_hover` also stops being honoured, which its own doc
215//! sanctioned: a renderer decides. It was retired outright in makeover-layout
216//! 0.13.0, once this had been its only consumer for a release. The rule hid a
217//! row's actions until hover,
218//! and every escape it grew was a report that hiding was wrong for somebody:
219//! `focus-within` for the keyboard, the capability gate for a fingertip with no
220//! way to unhide. What survived hid the controls from pointer users alone, who
221//! are the ones scanning a list to learn what can be done to a row.
222//!
223//! # 0.17.0: the depth classes stop being controls
224//!
225//! [`depth_rules`] gave `.raised` the whole interactive set. A depth is a
226//! statement about shape, so that left the vocabulary with no raised surface
227//! that is merely an object, and an app wanting one had two moves: write its
228//! own class from tokens, or take a control class and cancel the control half.
229//! goingson took the second, in three variants over sixteen elements
230//! (`.card--static` at 14 call sites, `.card--muted` at 2, `.card--shell` at 1),
231//! each re-asserting the resting fill and bevel on `:hover` and `:active`.
232//!
233//! Measured before changing it: `.raised` is emitted into goingson, Balanced
234//! Breakfast and the MNW server, and none of the three has a single call site.
235//! The states were unasked-for everywhere at once, and dropping them costs no
236//! migration anywhere.
237//!
238//! `.card` and `.button` are unchanged. They are the same depth *and* controls,
239//! and they take their states from [`surface_rules`], which is where a state
240//! belongs: on the thing that claims to answer a pointer.
241//!
242//! # Substitution, three ways
243//!
244//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
245//! answers that differently, which is the evidence that dropping
246//! `Fill::fallback` from the description was right:
247//!
248//! - `makeover-immediate` substitutes the page in Rust.
249//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
250//!   terminal would quantise the two together.
251//! - here, CSS already has the mechanism: `var(--surface-well,
252//!   var(--surface-page))` falls back in the browser, and nothing in Rust
253//!   decides anything.
254
255#![forbid(unsafe_code)]
256
257pub mod figure;
258pub mod form;
259pub mod list;
260pub mod meter;
261pub mod placeholder;
262pub mod vocabulary;
263
264use crate::list::{cell_part_class, part_class};
265use makeover_geometry::{Density, SizeClass};
266// Re-exported rather than redefined. An app assembling its own stylesheet out
267// of this crate's pieces needs the same layer name, and most such apps depend
268// on this crate and not on `makeover-geometry` directly: goingson builds
269// `tables.css` in its own build.rs from [`list::narrowing_css`], and those
270// rules are as generated as the ones here.
271pub use makeover_geometry::{CSS_LAYER, in_css_layer};
272use makeover_layout::{
273    Bevel, CellPart, Depth, Fill, Intent, RowPart, Selector, State, Token, Tone,
274};
275use makeover_touch::Affordance;
276use std::fmt::Write as _;
277
278/// How the emitted CSS is shaped.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub struct Emit {
281    /// Bevel thickness, as a CSS length.
282    ///
283    /// A value, so it arrives from the caller: border widths belong to
284    /// `makeover-geometry` and will come from there once it carries them.
285    pub border_width: &'static str,
286    /// Focus ring thickness, as a CSS length.
287    ///
288    /// Separate from [`border_width`](Self::border_width), which it reused
289    /// until 0.12.0. That reuse was an implementation convenience dressed as
290    /// consistency, and it emitted a 1px ring: a bevel and a focus indicator
291    /// are answering different questions, and only one of them has to be
292    /// noticed from across a desk.
293    ///
294    /// The default is the measured consensus rather than a new opinion. Every
295    /// consumer had already written its own ring and all three chose at least
296    /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
297    /// goingson 2px on three rules and 3px on the one covering twelve
298    /// selectors. The design system was the only thing in the tree saying 1px.
299    pub focus_width: &'static str,
300    /// Prefix for emitted class names, without the leading dot.
301    pub class_prefix: &'static str,
302}
303
304impl Default for Emit {
305    fn default() -> Self {
306        Self {
307            border_width: "1px",
308            focus_width: "2px",
309            class_prefix: "",
310        }
311    }
312}
313
314/// The CSS custom property holding a bevel's composition.
315#[must_use]
316pub fn bevel_var(bevel: Bevel) -> &'static str {
317    match bevel {
318        Bevel::Raised => "--bevel-raised",
319        Bevel::Inset => "--bevel-inset",
320    }
321}
322
323/// A `var()` reference to a fill intent, with the browser's own fallback where
324/// the intent may be absent.
325///
326/// The fallback is CSS syntax, not a decision made here. That is the whole
327/// difference between this renderer and the other two.
328#[must_use]
329pub fn fill_var(fill: Fill) -> String {
330    match fill {
331        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
332        other => format!("var(--{})", other.token()),
333    }
334}
335
336/// The two-tone edge as a `box-shadow` value.
337///
338/// Two inset shadows, one per corner pair: the light one offset down and
339/// right so it lands on the top and left edges, the dark one the other way.
340/// The same assignment `makeover-immediate` draws with polylines and
341/// `makeover-tui` draws with box-drawing characters.
342#[must_use]
343pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
344    let (top_left, bottom_right) = bevel.edges();
345    let w = opts.border_width;
346    format!(
347        "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
348        top_left.token(),
349        bottom_right.token()
350    )
351}
352
353/// The custom properties both bevels resolve through.
354///
355/// Emitted as properties rather than inlined into every rule because that is
356/// what the apps already do, and because a consumer that wants the edge
357/// without the fill reads the property directly.
358#[must_use]
359pub fn bevel_properties(opts: &Emit) -> String {
360    let mut css = String::new();
361    for bevel in [Bevel::Raised, Bevel::Inset] {
362        let _ = writeln!(
363            css,
364            "    {}: {};",
365            bevel_var(bevel),
366            bevel_shadow(bevel, opts)
367        );
368    }
369    css.push_str(ELEVATION_PROPERTY);
370    css
371}
372
373/// The cast shadow of a surface that floats over the page.
374///
375/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
376/// this crate owns the geometry, and neither has to know the other's numbers.
377///
378/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
379/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
380/// that reaches for this on a card or a plate has renamed a literal rather than
381/// replaced it.
382///
383/// Two lengths rather than one, because a single blur reads as a smudge at
384/// plate size and as a halo at menu size. The offset is small and downward: a
385/// Platinum-era menu sits just off the page rather than hovering above it.
386const ELEVATION_PROPERTY: &str =
387    "    --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
388
389/// The class name for a depth.
390#[must_use]
391pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
392    let name = match depth {
393        Depth::Flat => return None,
394        Depth::Raised => "raised",
395        Depth::Well => "well",
396        Depth::Sunken => "sunken",
397        // A depth added to the description since this renderer was last
398        // built. No class, on the same footing as Flat: emitting a name
399        // whose rule body we cannot write would put a class in the markup
400        // that the stylesheet never defines.
401        _ => return None,
402    };
403    Some(format!("{}{name}", opts.class_prefix))
404}
405
406/// A prefixed class name.
407///
408/// Public since 0.27.0, for the renderers that emit markup this crate does not.
409/// A screen renderer writing `class="row"` has to prefix it the way the
410/// stylesheet half does or a prefixed app gets rules matching everything except
411/// the elements that renderer wrote, and the failure is invisible: the CSS
412/// stays valid and one element is unstyled. quasi-webview carried a byte
413/// identical copy of this function until it could call this one.
414#[must_use]
415pub fn class(name: &str, opts: &Emit) -> String {
416    let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
417    push_class(&mut out, name, opts);
418    out
419}
420
421/// A prefixed class name, written into a buffer the caller already has.
422///
423/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
424/// every class on every element went through a `format!` before 0.40.0,
425/// including the default case where the prefix is empty and the answer is the
426/// argument. A described table row carried roughly eighty transient
427/// allocations, and this and the escaper were most of them.
428///
429/// [`class`] stays for callers holding a name rather than a buffer.
430///
431/// [`escape_into`]: crate::form::escape_into
432pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
433    out.push_str(opts.class_prefix);
434    out.push_str(name);
435}
436
437/// The class an option of a selector carries, which is what the rules key off.
438///
439/// Named for the option and not for the group: [`selector_rules`] styles the
440/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
441/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
442/// and `option`, put `toggle` on the wrapping element rather than on the
443/// buttons inside it, and every described selector in that renderer came out
444/// with no depth, no focus ring and no chosen state, while the toggle group got
445/// a bevel meant for its buttons.
446///
447/// The chosen option additionally carries `chosen`, the same way a latched chip
448/// carries `latched`. That name is this crate's too; there is no reason for a
449/// caller to spell it, and [`selector_rules`] is where it is written down.
450#[must_use]
451pub fn option_class(selector: Selector) -> &'static str {
452    match selector {
453        Selector::Tabs => "tab",
454        Selector::Segmented => "segment",
455        Selector::Toggle => "toggle",
456    }
457}
458
459/// The fill and edge declarations for a depth, as a rule body.
460///
461/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
462/// Callers lean on the emptiness to skip the rule rather than emit a class that
463/// sets nothing: a class that sets no properties is a class that means "I
464/// thought about this", which is what comments are for.
465///
466/// The two halves are emitted independently because [`Depth::Sunken`] has a
467/// fill and no bevel. Requiring both, which this did before makeover-layout
468/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
469/// mean unpaired: both halves still come off one `Depth`, so they cannot
470/// disagree about what the region is.
471#[must_use]
472pub fn depth_declarations(depth: Depth) -> String {
473    let mut css = String::new();
474    if let Some(fill) = depth.fill() {
475        let _ = writeln!(css, "    background: {};", fill_var(fill));
476    }
477    if let Some(bevel) = depth.bevel() {
478        let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
479    }
480    css
481}
482
483/// One rule giving a selector a depth, or nothing when the depth declares
484/// nothing.
485#[must_use]
486pub fn depth_rule(selector: &str, depth: Depth) -> String {
487    let body = depth_declarations(depth);
488    if body.is_empty() {
489        return String::new();
490    }
491    format!(".{selector} {{\n{body}}}\n")
492}
493
494/// The media condition a hover rule has to sit inside, or `None` if hover is
495/// unconditional.
496///
497/// Two crates answer this and neither answer is made here. `makeover-touch`
498/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
499/// that capability is spelled as a media condition. Asking both is what stops
500/// this renderer minting a third opinion, which is what all three apps did:
501/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
502/// alone, and the MNW server had no gate at all.
503///
504/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
505/// member, which reports as much through `reads_size`. Passing Compact is not
506/// a claim about width; the test below pins that every class agrees.
507fn hover_condition() -> Option<&'static str> {
508    if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
509        // A fingertip grew a hover state. Nothing to gate, and this renderer
510        // should not invent a reason to gate anyway.
511        None
512    } else {
513        Some(Density::Pointer.media_condition())
514    }
515}
516
517/// Put a rule inside a media query, or leave it alone.
518fn gated(condition: Option<&str>, rule: &str) -> String {
519    let Some(condition) = condition else {
520        return rule.to_string();
521    };
522    let mut css = format!("@media {condition} {{\n");
523    for line in rule.lines() {
524        // Blank lines stay blank. Indenting one leaves trailing whitespace,
525        // which is the sort of thing a formatter later reverts and calls a diff.
526        if line.is_empty() {
527            css.push('\n');
528        } else {
529            let _ = writeln!(css, "    {line}");
530        }
531    }
532    css.push_str("}\n");
533    css
534}
535
536/// The keyboard focus ring, placed by the depth it lands on.
537///
538/// This is the webview's **focus ring** and nothing more. **Reach** and
539/// **focus** are both the browser's — the document decides what is reachable
540/// and `:focus-visible` decides which reached thing wears the ring — and no
541/// description states either. The three terms are defined once in
542/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
543///
544/// One ring for the whole system, because a focus ring's job is to be
545/// recognised and three apps having three of them is the failure. What varies
546/// is where it sits, and that comes off [`Depth`] rather than off a per-
547/// component choice: a well takes the ring inside its own edge, and anything
548/// standing proud of the page takes it outside.
549///
550/// `outline` rather than the composed `box-shadow` the invalid-field ring at
551/// [`field_rules`] uses, and deliberately the one place the two rings are built
552/// differently. A `box-shadow` ring has to restate the bevel beside it, because
553/// `box-shadow` is not additive and a lone ring silently drops the well out
554/// from under the element. That restatement is a second copy of the depth,
555/// living in a different function from the first, and it is exactly the
556/// duplication `Depth` exists to prevent. `outline` occupies its own property,
557/// so the bevel survives untouched and there is nothing to keep in agreement.
558/// They render the same: both are a flush ring one border-width wide.
559#[must_use]
560pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
561    let w = opts.focus_width;
562    // Same magnitude either way, and only the sign comes off the depth. Both
563    // values are what the consumers had already converged on independently:
564    // 2px out is what all three wrote, and 2px in is the MNW server's own
565    // answer for the one inset ring it had.
566    let offset = match depth.bevel() {
567        // Inside the well, clear of its edge rather than painted over it.
568        Some(Bevel::Inset) => format!("calc(-1 * {w})"),
569        // Raised, or no edge at all. Outside, standing off by its own width.
570        _ => w.to_string(),
571    };
572    // The token by name. It is `makeover`'s, derived from the action colour,
573    // and reaching it through a description member was a second path to the
574    // same variable for as long as one existed.
575    format!(
576        ".{selector}:focus-visible {{\n    outline: {w} solid var(--focus-ring);\n    outline-offset: {offset};\n}}\n"
577    )
578}
579
580/// Present, visible, and not answering.
581///
582/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
583/// only matches form elements and half the things this crate emits are not
584/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
585/// the accessible state is the pattern [`field_rules`] already establishes for
586/// `aria-invalid`, on the reasoning that one fact read by both the styling and
587/// the accessibility tree cannot drift from itself.
588///
589/// The rest depth is re-asserted rather than assumed, because this rule has to
590/// beat the hover and pressed rules above it. It does that on source order at
591/// equal specificity, not by out-specifying them: every rule this function's
592/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
593/// one of them and have to be unpicked when this output moves inside its own
594/// cascade layer.
595#[must_use]
596pub fn disabled_rule(selector: &str, depth: Depth) -> String {
597    format!(
598        ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{}    color: var(--{});\n    cursor: not-allowed;\n}}\n",
599        depth_declarations(depth),
600        State::Disabled.token()
601    )
602}
603
604/// Every state a selector that answers a click implies: hover, pressed, focus
605/// and disabled, in that order.
606///
607/// Order is the whole cascade mechanism here. All four selectors are
608/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
609/// and by nothing else.
610///
611/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
612/// only the edge is what left goingson hand-writing `background:
613/// var(--surface-sunken)` on three separate rules, and a fill that does not
614/// travel with its edge is precisely the disagreement `Depth` exists to make
615/// unrepresentable. So the pressed fill comes from the description
616/// (`--surface-well`) rather than from whatever each app reached for.
617///
618/// Hover has no member in the description and is renderer policy: a terminal
619/// and an immediate-mode painter have no hover to express. It resolves against
620/// `--hover-surface`, which `makeover` already derives and which nothing
621/// consumed until now. What it *is* gated on is capability, via
622/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
623/// goingson's section 60 exists solely to take back the hover state this
624/// function had just handed it, by out-specifying a rule it does not own.
625///
626/// `depth` is the selector's **rest** depth, used to place the focus ring and
627/// to restore the surface under a disabled control. The pressed rule keeps
628/// inverting from [`Depth::Raised`] regardless, which is what every caller got
629/// before this parameter existed: a tab's unchosen depth is
630/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
631/// from the rest depth would leave a tab with no press at all.
632#[must_use]
633pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
634    let mut css = gated(
635        hover_condition(),
636        &format!(".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n"),
637    );
638    css.push_str(&depth_rule(
639        &format!("{selector}:active"),
640        Depth::Raised.pressed(),
641    ));
642    css.push_str(&focus_rule(selector, depth, opts));
643    css.push_str(&disabled_rule(selector, depth));
644    css
645}
646
647/// One rule per depth: its fill and its edge, together.
648///
649/// A depth and nothing else. `.raised` says a surface sits on what is behind
650/// it, which is a statement about the shape and not about what happens when a
651/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
652/// named surfaces are where interaction lives: `.card` and `.button` are the
653/// same depth *and* controls, and they get their states from
654/// [`surface_rules`].
655///
656/// This class carried the interactive set until 0.17.0, which left the
657/// vocabulary with no raised surface that is merely an object. Consumers that
658/// needed one took a control class and cancelled half of it instead: sixteen
659/// elements in goingson across three `.card--*` variants, each re-asserting the
660/// resting fill and bevel on `:hover` and `:active`. Nothing anywhere used
661/// `.raised` itself, so the states were unasked-for in every consumer at once.
662#[must_use]
663pub fn depth_rules(opts: &Emit) -> String {
664    let mut css = String::new();
665    for depth in [Depth::Raised, Depth::Well] {
666        let Some(class) = depth_class(depth, opts) else {
667            continue;
668        };
669        css.push_str(&depth_rule(&class, depth));
670    }
671    css
672}
673
674/// The three surfaces that are a depth with a name.
675///
676/// `button` and `card` are both [`Depth::Raised`], and `field` is a
677/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
678/// gives a text field. Their bodies come out identical by construction rather
679/// than by hand: three hand-written copies in goingson's stylesheet is what
680/// phase A deletes, and generating them from one call is what stops them
681/// drifting apart again.
682fn surface_rules(opts: &Emit) -> String {
683    let mut css = String::new();
684    for name in ["button", "card"] {
685        let c = class(name, opts);
686        css.push_str(&depth_rule(&c, Depth::Raised));
687        css.push_str(&interactive_rules(&c, Depth::Raised, opts));
688    }
689
690    let field = class("field", opts);
691    css.push_str(&depth_rule(&field, Depth::Well));
692
693    // A field takes focus and refuses input like everything else here, and got
694    // neither until now, which is why all three apps hand-write a focus ring
695    // for it and no two of them match. No hover or pressed: a text field does
696    // not light up under the pointer and does not invert when clicked, so the
697    // two states `interactive_rules` would add are the two it does not have.
698    css.push_str(&focus_rule(&field, Depth::Well, opts));
699    css.push_str(&disabled_rule(&field, Depth::Well));
700
701    // Keyed on the ARIA attribute rather than on a class, so the visual state
702    // and the accessible state cannot drift apart: there is one fact and both
703    // read it. goingson already drove its invalid styling this way and was
704    // right to; the `.invalid` class this emitted before 0.5.0 was a second
705    // place to forget.
706    //
707    // The ring composes *after* the bevel rather than replacing it. box-shadow
708    // is not additive, so a lone ring silently dropped the well out from under
709    // an invalid field. Flat and unlit: this edge is saying "wrong", and
710    // lighting one side would have it say "raised" at the same time.
711    let _ = writeln!(
712        css,
713        ".{field}[aria-invalid=\"true\"] {{\n    box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
714        bevel_var(Bevel::Inset),
715        opts.border_width
716    );
717    css
718}
719
720/// Badges and chips.
721///
722/// The one place phase A changes how goingson looks rather than only where its
723/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
724/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
725/// carrying the raised bevel. Splitting that means reading every call site to
726/// decide which of the two it always was.
727///
728/// What a badge does carry is a [`Tone`], the intent family it shares with
729/// notices and nothing else. Neutral is the bare class rather than a variant,
730/// because it is the absence of a status and not a status called "none".
731/// Text that goes somewhere.
732///
733/// The one inline control, and the vocabulary had no word for it until a
734/// description layer needed one. A table cell has carried `cell-link` since
735/// 0.14.0's part list, deliberately unruled because the cell's own rule covers
736/// it; what was missing is the same thing outside a table, which is what a
737/// described run holds when a sentence contains a link.
738///
739/// Colour and underline only. Whether a link is inline in a sentence or sitting
740/// on its own line is the app's layout, and how much room it takes is
741/// `makeover-geometry`'s. What is here is the pair of signals that say "this
742/// goes somewhere" and nothing that says where it sits.
743///
744/// The visited arm is deliberately absent. A link inside an app points at the
745/// app's own screens, which the user is expected to have been to, so painting
746/// them differently marks almost everything and distinguishes nothing.
747fn link_rules(opts: &Emit) -> String {
748    let mut css = String::new();
749    let link = class("link", opts);
750
751    let _ = writeln!(
752        css,
753        ".{link} {{\n    color: var(--action);\n    \
754         text-decoration: underline;\n}}"
755    );
756    // The hover step is the same one every other control takes, and it is a
757    // colour rather than a surface: a link has no box to raise.
758    let _ = writeln!(
759        css,
760        "@media (hover: hover) and (pointer: fine) {{\n    .{link}:hover \
761         {{\n        color: var(--action-hover);\n    }}\n}}"
762    );
763    let _ = writeln!(
764        css,
765        ".{link}:focus-visible {{\n    outline: {} solid var(--focus-ring);\n    \
766         outline-offset: 2px;\n}}",
767        opts.focus_width
768    );
769    // A link is often a `<button>` rather than an `<a>`: a renderer picks the
770    // element from the method, so a link that writes is a button that has to
771    // stop looking like one.
772    let _ = writeln!(
773        css,
774        "button.{link} {{\n    background: none;\n    border: none;\n    \
775         padding: 0;\n    font: inherit;\n    cursor: pointer;\n}}"
776    );
777    css
778}
779
780fn token_rules(opts: &Emit) -> String {
781    let mut css = String::new();
782
783    // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
784    // and a label with an edge says it can be pressed.
785    let badge = class("badge", opts);
786    let _ = writeln!(
787        css,
788        ".{badge} {{\n    color: var(--{});\n}}",
789        Tone::Neutral.token()
790    );
791    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
792        let _ = writeln!(
793            css,
794            ".{badge}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
795            tone.token()
796        );
797    }
798
799    // A button carries the four tones a badge does. It had none, on the reading
800    // that a control's colour is its surface rather than its text, and that
801    // reading has one hole big enough to matter: the button that destroys
802    // something. Every consumer had written that rule itself, and a description
803    // that says `Tone::Danger` on an act had nowhere for it to land.
804    //
805    // Colour and not a fill, matching the badge. A red surface is a decision
806    // about emphasis that belongs to an app's own layer, and two of them
807    // fighting is worse than neither.
808    let button = class("button", opts);
809    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
810        let _ = writeln!(
811            css,
812            ".{button}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
813            tone.token()
814        );
815    }
816
817    // A chip holds itself down, which is `Depth::pressed` arrived at
818    // independently by two apps. `removable` is a remove affordance, so it is
819    // markup and waits for phase B.
820    let chip = class("chip", opts);
821    let unlatched = Token::Chip { removable: false };
822    css.push_str(&depth_rule(&chip, unlatched.depth(false)));
823    css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
824    css.push_str(&depth_rule(
825        &format!("{chip}.latched"),
826        unlatched.depth(true),
827    ));
828    css
829}
830
831/// The three selectors, each named by what it picks.
832///
833/// A tab comes *forward* to join the pane it opens, which is why
834/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
835/// are held in. That is the folder semantic, and it is the whole reason the
836/// three are not one member with a flag.
837///
838/// [`Selector::abutting`] is not emitted: whether the options touch is
839/// spacing, and spacing is `makeover-geometry`'s question to answer.
840///
841/// Both states emit as of makeover-layout 0.3.0. Before it the description
842/// named only the chosen option, so an unchosen one fell through to
843/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
844/// strip hand-writing the recess that makes its chosen tab read as forward.
845fn selector_rules(opts: &Emit) -> String {
846    let mut css = String::new();
847    for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
848        let c = class(option_class(selector), opts);
849        css.push_str(&depth_rule(&c, selector.unchosen()));
850        css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
851        css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
852    }
853    css
854}
855
856/// The parts of a list row.
857///
858/// The list is written out rather than derived because `RowPart` is
859/// `#[non_exhaustive]` as of makeover-layout 0.9.0, so there is nothing to
860/// iterate. A member added upstream emits no rule until it is named here, which
861/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
862/// [`part_class`] carries the same list and the same obligation.
863fn row_rules(opts: &Emit) -> String {
864    let mut css = String::new();
865
866    // The container the rows sit in. Three zeroes and a keyword, all of them
867    // undoing a browser default the description never asked for: a described
868    // list of SSH keys is not a bulleted list, and it rendered as one because
869    // nothing here said otherwise. Not a size: there is no magnitude in it,
870    // which is the line this crate holds.
871    let _ = writeln!(
872        css,
873        ".{} {{\n    list-style: none;\n    margin: 0;\n    padding: 0;\n}}",
874        class("list", opts)
875    );
876
877    for part in [
878        RowPart::Primary,
879        RowPart::Secondary,
880        RowPart::Meta,
881        RowPart::Actions,
882        RowPart::Tokens,
883        RowPart::Proportion,
884    ] {
885        let c = class(part_class(part), opts);
886
887        // Actions carry controls rather than text, and `RowPart::intent` says
888        // so by returning the same intent inheriting already gives. Pinning it
889        // would be louder than saying nothing. Tokens answer alike, for their
890        // own reason: each token carries its own tone, and a colour on the
891        // strip would fight the things sitting in it. A proportion is the same
892        // case again: the meter inside carries the tone.
893        if !matches!(
894            part,
895            RowPart::Actions | RowPart::Tokens | RowPart::Proportion
896        ) {
897            let _ = writeln!(css, ".{c} {{\n    color: var(--{});\n}}", part.intent());
898        }
899
900        // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
901        // otherwise and was not honoured here from 0.23.0; makeover-layout
902        // 0.13.0 retired the method, so there is no longer a description saying
903        // one thing and a renderer doing another.
904        //
905        // The rule was `opacity: 0` gated to pointer devices, revealed on
906        // `:hover` and on `:focus-within`. Each escape it needed was a report
907        // that hiding was wrong for somebody: `focus-within` because tabbing
908        // could never reach an action; the gate because a fingertip had no way
909        // to unhide, which both webview apps had already hand-written
910        // `opacity: 1` to undo. What was left was a control hidden from
911        // exactly one group: people using a pointer, who are also the group
912        // scanning a list to find out what can be done to a row.
913        //
914        // A settings screen is where that reads worst: the whole reason to be
915        // on it is to remove a key, and the button doing so was invisible
916        // until pointed at. A table cell's actions were never hidden, so the
917        // two arrangements now agree.
918    }
919    css
920}
921
922/// The progress trough these rules fill.
923///
924/// This was renderer-local chrome with nothing behind it until makeover-layout
925/// 0.10.0, which is the unusual order: the tones below were emitted for every
926/// bar in the tree while the only way to describe one was to concatenate the
927/// numbers into a heading. `Meter` is the word that arrived late, and
928/// [`meter::meter_html`](crate::meter::meter_html) is what now fills these.
929///
930/// The rules stay a superset of what a description can ask for. An app drawing
931/// its own bar keeps these classes, which is what the four goingson grew
932/// independently were adopted onto.
933///
934/// The trough is a [`Depth::Well`], the same reading a text field gets:
935/// something with its content down inside it.
936fn progress_rules(opts: &Emit) -> String {
937    let progress = class("progress", opts);
938    // `progress-fill` rather than a bare `fill`: an unprefixed build claims
939    // these names in the app's own stylesheet, and `.fill` is grabby enough to
940    // catch things that have nothing to do with progress. goingson already
941    // calls it `.progress-fill`, so this is also the name that deletes.
942    let fill = class("progress-fill", opts);
943    let mut css = depth_rule(&progress, Depth::Well);
944
945    // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
946    // place this differs from the badge rules, and deliberately: a badge with
947    // no status is a muted label, while a bar with no status is still
948    // reporting progress, and `content-muted` would read as disabled.
949    let _ = writeln!(
950        css,
951        ".{progress} > .{fill} {{\n    background: var(--action);\n}}"
952    );
953
954    // A bar can be saying something, same as a badge: goingson colours subtask
955    // progress as success and an over-estimate as danger, which is real
956    // information rather than decoration. Emitting the tones is what lets that
957    // survive adoption instead of staying hand-written.
958    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
959        let _ = writeln!(
960            css,
961            ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n    background: var(--{0});\n}}",
962            tone.token()
963        );
964    }
965    css
966}
967
968/// A strip of figures, and the two spans inside each one.
969///
970/// Colour only, which is the deferral rule applied to a component that badly
971/// wants to break it. A figure reads as a figure because the value is set large
972/// over a small caption, and that is a size: `makeover-geometry` answers how
973/// much space and this crate answers what the thing is. Emitting `font-size`
974/// here would be this crate naming a value, which is the one thing it is defined
975/// by not doing, and `progress_rules` is the precedent — it emits the tones and
976/// never the width, because the width is not its to know.
977///
978/// So the arrangement and the type scale are the app's, and what is generated is
979/// the part an app cannot get right by itself: which of the two spans carries
980/// the tone.
981fn figure_rules(opts: &Emit) -> String {
982    let figure = class("figure", opts);
983    let value = class("figure-value", opts);
984    let caption = class("figure-caption", opts);
985    let change = class("figure-change", opts);
986    let mut css = String::new();
987
988    let _ = writeln!(
989        css,
990        ".{figure} > .{value} {{\n    color: var(--{});\n}}",
991        Tone::Neutral.token()
992    );
993    let _ = writeln!(
994        css,
995        ".{figure} > .{caption} {{\n    color: var(--content-muted);\n}}"
996    );
997    let _ = writeln!(
998        css,
999        ".{figure} > .{change} {{\n    color: var(--content-muted);\n}}"
1000    );
1001
1002    // A toned figure tones one part and never the caption. The caption is the
1003    // noun and stays muted.
1004    //
1005    // Which part depends on whether there is a change, and that is the whole of
1006    // what 0.13.0 changed here. A figure with a delta is an ordinary number that
1007    // has moved in a direction worth reading, so the delta takes the colour and
1008    // the number stays plain; a figure without one has nowhere else to put it.
1009    // `:has` is what lets one attribute mean both, and the alternative was the
1010    // emitter deciding by writing the attribute onto a different element, which
1011    // leaves two elements able to disagree about a figure's one meaning.
1012    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1013        let _ = writeln!(
1014            css,
1015            ".{figure}[data-tone=\"{0}\"] > .{change} {{\n    color: var(--{0});\n}}",
1016            tone.token()
1017        );
1018        let _ = writeln!(
1019            css,
1020            ".{figure}[data-tone=\"{0}\"]:not(:has(> .{change})) > .{value} \
1021             {{\n    color: var(--{0});\n}}",
1022            tone.token()
1023        );
1024    }
1025    css
1026}
1027
1028/// A picture, its frame and its caption.
1029///
1030/// `makeover_layout::Image` arrived at 0.21.0, found by trying to describe MNW's
1031/// carousel and discovering nothing named a picture.
1032///
1033/// # The frame is a border, and this is the one place a bevel is wrong
1034///
1035/// 0.36.0 emitted [`Depth::Raised`] here through [`depth_rule`], the same call
1036/// `button` and `card` make. It was wrong, and MNW's landing page is where it
1037/// showed: **the frames had no visible edge at all.**
1038///
1039/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow — a
1040/// 1px light run at the top-left and a dark one at the bottom-right, drawn
1041/// **inside** the element's box. On a button or a card that box is a surface
1042/// this crate owns, so an inset edge reads as the surface catching the light.
1043/// On a picture it is drawn on top of the picture, over whatever pixels the
1044/// image happens to have at its border. MNW's screenshots are light-on-light
1045/// parchment, so the light half landed on a light image and the frame
1046/// disappeared.
1047///
1048/// **You cannot bevel a surface you do not own.** A picture's content is the
1049/// app's, arrives at request time, and can be any colour, so its edge has to
1050/// sit *outside* the content rather than on it. That is a border.
1051///
1052/// The fill stays, and it is not decoration: it is what shows through a
1053/// transparent PNG and what stands in the frame's place while the image is
1054/// still loading.
1055///
1056/// This is a real limit on [`Depth`] rather than a special case. Every other
1057/// consumer of a depth draws its own surface; a picture is the first member
1058/// whose surface belongs to someone else.
1059///
1060/// # No size
1061///
1062/// `width: 100%` and nothing else. How large a picture is depends on the box it
1063/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
1064/// and a renderer that picked one would be answering for every consumer at
1065/// once. This is where `figure_rules` landed for the same reason.
1066fn picture_rules(opts: &Emit) -> String {
1067    let picture = class("picture", opts);
1068    let img = class("picture-img", opts);
1069    let caption = class("picture-caption", opts);
1070    let mut css = String::new();
1071
1072    // Block, or an inline image sits on the text baseline and carries a
1073    // descender's worth of space under it that no app ever wants and every app
1074    // deletes by hand. The border is the frame; see the type docs for why it is
1075    // not the bevel every other surface here gets.
1076    let _ = writeln!(
1077        css,
1078        ".{img} {{\n    display: block;\n    width: 100%;\n    height: auto;\n    \
1079         background: var(--{});\n    border: {} solid var(--border);\n}}",
1080        Fill::Raised.token(),
1081        opts.border_width
1082    );
1083
1084    // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
1085    // so it is the bare rule above and needs nothing here.
1086    let _ = writeln!(
1087        css,
1088        ".{img}[data-fit=\"cover\"] {{\n    height: 100%;\n    object-fit: cover;\n}}"
1089    );
1090    let _ = writeln!(
1091        css,
1092        ".{img}[data-fit=\"contain\"] {{\n    height: 100%;\n    object-fit: contain;\n}}"
1093    );
1094
1095    // A caption reads back one step, which is `figure-caption`'s answer and the
1096    // same claim: it says what the thing above it is, and it is not the thing.
1097    let _ = writeln!(
1098        css,
1099        ".{picture} > .{caption} {{\n    color: var(--content-muted);\n}}"
1100    );
1101
1102    css
1103}
1104
1105/// A region showing one child at a time, and the chrome that moves between them.
1106///
1107/// [`makeover_layout::Showing`] lets a description say that a region holds
1108/// several children and shows some of them. A renderer derives its own chrome
1109/// from that, which is what stops every renderer growing a `match` on a widget
1110/// name; these are the rules the derived chrome needs.
1111///
1112/// # Why the default is every child, and the enhancement takes them away
1113///
1114/// The controls are a lie until something binds them. A prev button rendered
1115/// into a document with no script is a control that looks live and answers
1116/// nothing, and the reader it lies to is exactly the one who cannot see the
1117/// other children either — the collapsing and the moving are the same half.
1118///
1119/// So the rules run in the direction the enhancement does. Nothing here hides a
1120/// child and nothing here shows a control. Whatever binds the region sets
1121/// `data-ready` on it, and that is what collapses the stack to one and reveals
1122/// the row that moves it. A reader with no script gets every child in order and
1123/// no controls, which is more content rather than less, and a reader with
1124/// script gets a settled page rather than a stack that jumps to one frame after
1125/// load.
1126///
1127/// MNW proved this shape by hand — a `<noscript>` stylesheet opening its
1128/// carousel back out — and it is here rather than there because the property is
1129/// the description's, not one app's.
1130///
1131/// # Not spacing
1132///
1133/// The row's gaps are `makeover-geometry`'s question and are absent for
1134/// [`row_rules`]'s reason. What is here is `display`, which carries no
1135/// magnitude, and the muted readout, which is the same claim `picture-caption`
1136/// makes: it says where you are among the children and it is not one of them.
1137fn showing_rules(opts: &Emit) -> String {
1138    let controls = class("showing", opts);
1139    let position = class("showing-position", opts);
1140    let frame = class("showing-frame", opts);
1141    let mut css = String::new();
1142
1143    // Hidden until something binds it, which is the whole argument above.
1144    let _ = writeln!(css, ".{controls} {{\n    display: none;\n}}");
1145    // Block, and nothing about how the three sit in it. A button and a span are
1146    // inline already, so they make a row without this crate saying so, and
1147    // saying so is where `align-items` and a gap would follow -- both spacing,
1148    // both `makeover-geometry`'s, and `row_rules` refuses them for the same
1149    // reason.
1150    let _ = writeln!(
1151        css,
1152        "[data-ready] > .{controls} {{\n    display: block;\n}}"
1153    );
1154
1155    // A child is in flow until the region is bound, and then only the current
1156    // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
1157    // are: one name for the state, set by whoever knows it.
1158    let _ = writeln!(
1159        css,
1160        "[data-ready] > .{frame}:not(.current) {{\n    display: none;\n}}"
1161    );
1162
1163    // Reads back one step. `picture-caption`'s rule and its reason.
1164    let _ = writeln!(css, ".{position} {{\n    color: var(--content-muted);\n}}");
1165
1166    css
1167}
1168
1169/// A region's stand-in, and the header of a table that can be reordered.
1170///
1171/// Both are 0.12.0 members and both are colour and affordance only, which is
1172/// where `figure_rules` landed after trying to emit a type scale. How much room
1173/// a stand-in gets is a size — goingson has the same one at three, as
1174/// `--compact`, `--dashboard` and `--padded` — and a size is
1175/// `makeover-geometry`'s question.
1176///
1177/// The caret is the one thing here that is neither colour nor affordance, and it
1178/// is a renderer's own expression rather than a value the description named:
1179/// `aria-sort` is what the table actually says, and this turns it into something
1180/// visible for everyone not using a screen reader. A terminal draws its own; an
1181/// immediate-mode painter draws its own.
1182fn state_rules(opts: &Emit) -> String {
1183    let placeholder = class("placeholder", opts);
1184    let text = class("placeholder-text", opts);
1185    let heading = class("table-heading", opts);
1186    let mut css = String::new();
1187
1188    let _ = writeln!(
1189        css,
1190        ".{placeholder} > .{text} {{\n    color: var(--content-muted);\n}}"
1191    );
1192    // Only the failure is toned. An empty list is the normal state of a new
1193    // install, and `Readiness::tone` is what says so.
1194    let _ = writeln!(
1195        css,
1196        ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n    color: var(--{0});\n}}",
1197        Tone::Danger.token()
1198    );
1199
1200    // A header that reorders the table is a control, and the pointer is the
1201    // only part of saying so that is not the app's own type and spacing.
1202    let _ = writeln!(
1203        css,
1204        ".{heading}[data-sortable] {{\n    cursor: pointer;\n}}"
1205    );
1206    // The caret carries its own leading space, the way `makeover-tui` and
1207    // `makeover-immediate` both write `" \u{25B2}"`. It used to be emitted bare,
1208    // and both apps that adopted the vocabulary had to put the gap back in their
1209    // own stylesheets on the same afternoon -- each having to work out first that
1210    // app CSS outranks this crate's cascade layer, so adding the space the
1211    // obvious way, as `content`, silently wins over the glyph and leaves the
1212    // heading with no caret at all. A consumer should not have to know that, and
1213    // with the space emitted here there is nothing left for one to add.
1214    //
1215    // The unsorted arm reserves the same box with the glyph hidden, so pressing
1216    // a heading does not reflow the row it sits in. Hidden rather than sized:
1217    // the reservation is the caret's own width, so it names no magnitude and
1218    // stays out of `makeover-geometry`'s territory.
1219    let _ = writeln!(
1220        css,
1221        ".{heading}[data-sortable]::after \
1222         {{\n    content: \" \\2191\";\n    visibility: hidden;\n}}"
1223    );
1224    for (direction, caret) in [("ascending", "\\2191"), ("descending", "\\2193")] {
1225        let _ = writeln!(
1226            css,
1227            ".{heading}[aria-sort=\"{direction}\"]::after \
1228             {{\n    content: \" {caret}\";\n    visibility: visible;\n}}"
1229        );
1230    }
1231    css
1232}
1233
1234/// The frame a table sits in.
1235///
1236/// # Why this is a CSS table and not the grid the rest of the module assumes
1237///
1238/// A grid row needs `grid-template-columns`, which has to name every column in
1239/// order, so it cannot be written without knowing the columns. That is what
1240/// [`list::narrowing_css`] is for, and it works: goingson builds `tables.css` in
1241/// its own `build.rs` out of it, and nothing here changes that.
1242///
1243/// It does not work for a table a *description* produced. Those columns are
1244/// known at render time rather than at build time, and the rules would have to
1245/// travel with the markup: a `<style>` element per table, which needs
1246/// `style-src 'unsafe-inline'` and so blocks the MNW server's standing plan to
1247/// drop it. The head is not an escape: a table swapped in by htmx after a
1248/// delete arrives as a fragment with no head at all.
1249///
1250/// A CSS table aligns its columns across rows knowing nothing about how many
1251/// there are, so there is no track list to emit and nothing per-table to carry.
1252/// The cost is that a described table cannot take a per-column fixed length,
1253/// which costs nothing today: [`Sizing`](list::Sizing) is looked up by column
1254/// name and a description carries no lengths to put in it, so every track a
1255/// described table could ask for is already content, fill or auto.
1256///
1257/// [`Priority`] hiding is unchanged in kind. It moves from a generated
1258/// `display: none` per dropped column to one rule per drop class, which is the
1259/// same fact addressed by class rather than by cutoff, and still never by
1260/// position.
1261fn table_rules(opts: &Emit) -> String {
1262    let table = class("table", opts);
1263    let head = class("table-head", opts);
1264    let row = class("table-row", opts);
1265    let heading = class("table-heading", opts);
1266    let cell = class("cell", opts);
1267    let mut css = String::new();
1268
1269    let _ = writeln!(
1270        css,
1271        ".{table} {{\n    display: table;\n    width: 100%;\n}}"
1272    );
1273    let _ = writeln!(css, ".{head},\n.{row} {{\n    display: table-row;\n}}");
1274    let _ = writeln!(css, ".{heading},\n.{cell} {{\n    display: table-cell;\n}}");
1275
1276    // A content column shrinks to what is in it. `width: 1%` is how a CSS table
1277    // is told that: auto layout hands the slack to the columns that asked for
1278    // room, and a column asking for almost none gets what it needs and no more.
1279    // The `nowrap` is what stops it being given less by wrapping.
1280    let _ = writeln!(
1281        css,
1282        ".{} {{\n    white-space: nowrap;\n    width: 1%;\n}}",
1283        class("cell-content", opts)
1284    );
1285
1286    // A fixed column has no length to be fixed to. The description carries none
1287    // and `Sizing` is not reachable from here, so it behaves as content: the
1288    // honest answer to a width nobody supplied, and the same one `Sizing::track`
1289    // gives it.
1290    let _ = writeln!(
1291        css,
1292        ".{} {{\n    white-space: nowrap;\n}}",
1293        class("cell-fixed", opts)
1294    );
1295
1296    // Optional columns go at the narrowest class, secondary ones go with them,
1297    // which is the cutoff walk `kept_at` describes said as two media queries.
1298    // Essential columns have no rule at all, because never dropping is what not
1299    // being mentioned already means.
1300    for (size, drops) in [
1301        (
1302            SizeClass::Compact,
1303            &["cell-drops-first", "cell-drops-next"][..],
1304        ),
1305        (SizeClass::Medium, &["cell-drops-first"][..]),
1306    ] {
1307        let selectors: Vec<String> = drops
1308            .iter()
1309            .map(|drop| format!(".{}", class(drop, opts)))
1310            .collect();
1311        css.push_str(&gated(
1312            Some(&size.media_condition()),
1313            &format!("{} {{\n    display: none;\n}}\n", selectors.join(",\n")),
1314        ));
1315    }
1316
1317    // What is inside a cell, which the table side could not say until
1318    // makeover-layout 0.14.0. Every cell was one `.cell` and one content
1319    // colour, so a button in a cell was painted as text -- the drift
1320    // `RowPart::intent` has prevented for list rows since 0.2.0 and prevented
1321    // for nothing here.
1322    //
1323    // The colour goes on `.cell-value` rather than on `.cell`, and that
1324    // placement is the whole fix. On the container it would cascade into the
1325    // tokens and the controls sitting beside the text, which is the bug said
1326    // in one rule; on the part that is text, it reaches text and stops.
1327    for part in [
1328        CellPart::Value,
1329        CellPart::Tokens,
1330        CellPart::Actions,
1331        CellPart::Link,
1332    ] {
1333        // Three of the four inherit, each for its own reason: a token carries
1334        // its own tone, an action is a control rather than text, and a link
1335        // takes the action colour from the anchor it is. `CellPart::intent`
1336        // says so by answering with the intent inheriting already gives, and
1337        // pinning that would be louder than saying nothing.
1338        //
1339        // Written as a skip-list rather than as a match on Value, so a member
1340        // added upstream gets its intent emitted rather than being silently
1341        // dropped. That is the same trade `part_class`'s fallback makes: land
1342        // plainly, never land as nothing.
1343        if !matches!(part, CellPart::Tokens | CellPart::Actions | CellPart::Link) {
1344            let _ = writeln!(
1345                css,
1346                ".{} {{\n    color: var(--{});\n}}",
1347                class(cell_part_class(part), opts),
1348                part.intent()
1349            );
1350        }
1351    }
1352
1353    css
1354}
1355
1356/// The component layer: every named thing phase A emits.
1357///
1358/// No scrollbar track. It was on the phase A list and came off: eight lines of
1359/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
1360/// would want handed to it, so it stays with the apps.
1361#[must_use]
1362pub fn component_rules(opts: &Emit) -> String {
1363    let mut css = String::new();
1364    css.push_str(&surface_rules(opts));
1365    css.push_str(&link_rules(opts));
1366    css.push_str(&token_rules(opts));
1367    css.push_str(&selector_rules(opts));
1368    css.push_str(&row_rules(opts));
1369    css.push_str(&progress_rules(opts));
1370    css.push_str(&figure_rules(opts));
1371    css.push_str(&picture_rules(opts));
1372    css.push_str(&showing_rules(opts));
1373    css.push_str(&state_rules(opts));
1374    css.push_str(&table_rules(opts));
1375    css
1376}
1377
1378/// The whole phase-A stylesheet: properties, depth rules and components, in
1379/// [`CSS_LAYER`], under a generated-file banner.
1380///
1381/// The banner sits outside the layer, because a comment participates in no
1382/// cascade and a reader opening the file should see what it is before seeing
1383/// an at-rule.
1384#[must_use]
1385pub fn stylesheet(opts: &Emit) -> String {
1386    format!(
1387        "/* Generated by makeover-webview from makeover-layout. Do not edit.\n   \
1388         Depth is a fill and an edge together; naming them apart is what let\n   \
1389         them disagree. See the crate's README and wiki note makeover-layout.\n\n   \
1390         Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n   \
1391         order once in your own stylesheet, or this layer's position is decided\n   \
1392         by whichever generated file the browser happens to see first:\n\n   \
1393         @layer {CSS_LAYER}, base, components, responsive; */\n{}",
1394        in_css_layer(&format!(
1395            ":root {{\n{}}}\n\n{}\n{}",
1396            bevel_properties(opts),
1397            depth_rules(opts),
1398            component_rules(opts)
1399        ))
1400    )
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405    use super::*;
1406    use makeover_layout::Edge;
1407
1408    #[test]
1409    fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
1410        // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
1411        // deletion, not a redesign, or nobody will take it.
1412        let opts = Emit::default();
1413        assert_eq!(
1414            bevel_shadow(Bevel::Raised, &opts),
1415            "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
1416        );
1417        assert_eq!(
1418            bevel_shadow(Bevel::Inset, &opts),
1419            "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
1420        );
1421    }
1422
1423    #[test]
1424    fn no_colour_ever_reaches_the_output() {
1425        let css = stylesheet(&Emit::default());
1426        assert!(!css.contains('#'), "a hex literal escaped into the CSS");
1427        assert!(
1428            !css.contains("rgb"),
1429            "a colour function escaped into the CSS"
1430        );
1431        // Every colour is named, never resolved.
1432        assert!(css.contains("var(--surface-raised)"));
1433        assert!(css.contains("var(--bevel-light)"));
1434    }
1435
1436    #[test]
1437    fn a_well_falls_back_through_css_rather_than_through_rust() {
1438        assert_eq!(
1439            fill_var(Fill::Well),
1440            "var(--surface-well, var(--surface-page))"
1441        );
1442        // Nothing else needs one.
1443        assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
1444        assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
1445    }
1446
1447    #[test]
1448    fn raised_and_well_do_not_collapse_onto_each_other() {
1449        let css = depth_rules(&Emit::default());
1450        assert!(css.contains(".raised {"));
1451        assert!(css.contains(".well {"));
1452        assert!(css.contains("var(--bevel-raised)"));
1453        assert!(css.contains("var(--bevel-inset)"));
1454    }
1455
1456    /// The cast shadow is composed here from the tone `makeover` derives, so
1457    /// neither crate has to hold the other's numbers.
1458    ///
1459    /// It is a `:root` property and deliberately not a depth class. There is no
1460    /// `Depth::Overlay` in the description layer, and adding one would be a
1461    /// claim about what a screen means rather than about how it is painted;
1462    /// until something asks for it, a consumer names the property on the rule
1463    /// for the menu or the toast it already has.
1464    #[test]
1465    fn the_cast_shadow_is_a_root_property_not_a_depth() {
1466        let css = bevel_properties(&Emit::default());
1467        assert!(css.contains("--elevation-overlay:"));
1468        assert!(css.contains("var(--elevation)"));
1469        assert!(
1470            !depth_rules(&Emit::default()).contains("elevation"),
1471            "elevation is not a depth class"
1472        );
1473    }
1474
1475    #[test]
1476    fn the_cascade_carries_the_pressed_state() {
1477        let css = surface_rules(&Emit::default());
1478        // The one thing this renderer gets free that the other two resolve by
1479        // hand, eighteen call sites deep in audiofiles' case. Asserted on a
1480        // named surface: pressing belongs to the control, not to the depth.
1481        assert!(css.contains(".card:active {"));
1482        assert!(css.contains(".button:active {"));
1483    }
1484
1485    #[test]
1486    fn the_depth_class_is_a_surface_and_not_a_control() {
1487        let css = depth_rules(&Emit::default());
1488        // The static surface the vocabulary was missing. Sixteen goingson
1489        // elements wore .card and cancelled its hover and press to get this,
1490        // because a raised object that is not pressable had no other spelling.
1491        for state in [":hover", ":active", ":focus-visible", ":disabled"] {
1492            assert!(
1493                !css.contains(&format!(".raised{state}")),
1494                "the depth class claimed {state}: {css}"
1495            );
1496        }
1497        assert!(css.contains("var(--bevel-raised)"), "still raised: {css}");
1498    }
1499
1500    #[test]
1501    fn pressing_moves_the_fill_and_not_only_the_edge() {
1502        // The decision-1 guard, and the regression that mattered: emitting the
1503        // bevel flip alone is what left goingson hand-writing `background:
1504        // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
1505        // of the three could be deleted.
1506        let pressed = interactive_rules("button", Depth::Raised, &Emit::default());
1507        assert!(pressed.contains(".button:active {"));
1508        assert!(
1509            pressed.contains("background: var(--surface-well, var(--surface-page))"),
1510            "pressed dropped its fill: {pressed}"
1511        );
1512        assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
1513    }
1514
1515    #[test]
1516    fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
1517        // goingson presses to --surface-sunken. The description says a pressed
1518        // raised region reads as a well, and makeover says outright that
1519        // surface-sunken cannot serve as one, so the app is the thing that
1520        // moves.
1521        //
1522        // Scoped to the pressed rules rather than to the whole sheet: since
1523        // makeover-layout 0.3.0 an unchosen tab is legitimately
1524        // --surface-sunken, so the token appearing somewhere in the output no
1525        // longer means the app's choice leaked in.
1526        let css = stylesheet(&Emit::default());
1527        let mut checked = 0;
1528        for rule in css.split("}\n") {
1529            if !rule.contains(":active") {
1530                continue;
1531            }
1532            checked += 1;
1533            assert!(
1534                !rule.contains("surface-sunken"),
1535                "a pressed rule took the app's fill: {rule}"
1536            );
1537        }
1538        assert!(checked > 0, "no pressed rules found to check");
1539        assert_eq!(
1540            Depth::Raised.pressed().fill(),
1541            Some(Fill::Well),
1542            "the description changed under us"
1543        );
1544    }
1545
1546    #[test]
1547    fn the_whole_stylesheet_is_emitted_in_the_family_layer() {
1548        // The point of 0.11.0. Unlayered normal declarations outrank every
1549        // named layer, so an app declaring `@layer base, components` loses
1550        // every rule it owns to this file until this file is layered too.
1551        let css = stylesheet(&Emit::default());
1552        assert!(css.contains(&format!("@layer {CSS_LAYER} {{")));
1553
1554        // Exactly one layer block, and nothing outside it but the banner.
1555        assert_eq!(css.matches("@layer").count(), 2, "banner names it once");
1556        let opened = css.find("@layer makeover {").expect("layer opens");
1557        for (i, line) in css.lines().enumerate() {
1558            let before_layer = css.lines().take(i).map(str::len).sum::<usize>() < opened;
1559            if before_layer || line.is_empty() {
1560                continue;
1561            }
1562            assert!(
1563                line.starts_with("    ") || line == "}" || line.starts_with("   "),
1564                "line outside the layer: {line:?}"
1565            );
1566        }
1567    }
1568
1569    #[test]
1570    fn the_generated_sheet_carries_no_trailing_whitespace() {
1571        // A checked-in generated file that a formatter wants to rewrite is a
1572        // diff every time somebody saves it.
1573        let css = stylesheet(&Emit::default());
1574        for (i, line) in css.lines().enumerate() {
1575            assert_eq!(line, line.trim_end(), "trailing whitespace on line {i}");
1576        }
1577    }
1578
1579    #[test]
1580    fn the_banner_tells_an_app_how_to_order_the_layer() {
1581        // Without a declared order the layer's position depends on which
1582        // generated file the browser sees first, which is not a contract.
1583        let css = stylesheet(&Emit::default());
1584        assert!(css.contains("@layer makeover, base, components, responsive;"));
1585        // And the banner is outside the layer, not a rule inside it.
1586        assert!(css.starts_with("/* Generated by makeover-webview"));
1587    }
1588
1589    #[test]
1590    fn a_primitive_owns_every_state_it_implies() {
1591        // The whole point of 0.10.0. Anything emitting a hover rule owes the
1592        // other three, or the consuming app supplies them by out-specifying a
1593        // rule it does not own: 19 such rules in goingson, 21 in the MNW
1594        // server, and three focus rings that do not match.
1595        let css = stylesheet(&Emit::default());
1596        for selector in ["button", "card", "chip", "tab", "segment", "toggle"] {
1597            assert!(css.contains(&format!(".{selector}:hover {{")), "{selector}");
1598            assert!(
1599                css.contains(&format!(".{selector}:active {{")),
1600                "{selector}"
1601            );
1602            assert!(
1603                css.contains(&format!(".{selector}:focus-visible {{")),
1604                "{selector} has no focus ring"
1605            );
1606            assert!(
1607                css.contains(&format!(".{selector}:disabled,")),
1608                "{selector} has no disabled state"
1609            );
1610        }
1611    }
1612
1613    #[test]
1614    fn a_field_takes_focus_and_refuses_input_without_taking_a_hover() {
1615        // A text field does not light up under the pointer, so it gets the two
1616        // states it has and not the two it does not.
1617        let css = stylesheet(&Emit::default());
1618        assert!(css.contains(".field:focus-visible {"));
1619        assert!(css.contains(".field:disabled,"));
1620        assert!(!css.contains(".field:hover {"));
1621        assert!(!css.contains(".field:active {"));
1622    }
1623
1624    #[test]
1625    fn disabled_is_emitted_after_hover_so_source_order_settles_it() {
1626        // Every one of these selectors is specificity (0,2,0), so nothing but
1627        // order decides which wins. A disabled button taking the hover fill is
1628        // the exact bug goingson's `.button:disabled:hover` was written to fix,
1629        // and the reason it had to reach (0,3,0) to do it.
1630        let css = interactive_rules("button", Depth::Raised, &Emit::default());
1631        let hover = css.find(":hover").expect("hover");
1632        let active = css.find(":active").expect("active");
1633        let focus = css.find(":focus-visible").expect("focus");
1634        let disabled = css.find(":disabled").expect("disabled");
1635        assert!(hover < active && active < focus && focus < disabled);
1636
1637        // And it restores the surface, or the hover fill survives underneath.
1638        let tail = &css[disabled..];
1639        assert!(tail.contains("background: var(--surface-raised)"));
1640    }
1641
1642    #[test]
1643    fn a_disabled_state_reaches_things_that_cannot_be_disabled() {
1644        // `:disabled` matches form elements only, and a chip is a div. Keying
1645        // on the ARIA attribute too is the pattern the invalid field already
1646        // set: one fact, read by the styling and the accessibility tree alike.
1647        let css = disabled_rule("chip", Depth::Raised);
1648        assert!(css.contains(".chip:disabled,"));
1649        assert!(css.contains(".chip[aria-disabled=\"true\"]"));
1650        assert!(css.contains("cursor: not-allowed"));
1651    }
1652
1653    #[test]
1654    fn the_focus_ring_does_not_disturb_the_bevel_it_lands_on() {
1655        // `outline` has its own property, so unlike the invalid ring there is
1656        // no bevel to restate beside it and nothing to keep in agreement.
1657        let opts = Emit::default();
1658        let css = focus_rule("button", Depth::Raised, &opts);
1659        assert!(css.contains("outline: 2px solid var(--focus-ring)"));
1660        assert!(!css.contains("box-shadow"), "the ring restated the bevel");
1661    }
1662
1663    #[test]
1664    fn a_well_takes_the_ring_inside_and_a_raised_surface_outside() {
1665        // One ring, placed by depth. The offset comes off `Depth::bevel` and
1666        // not off a per-component choice, which is what gave three apps three
1667        // different rings.
1668        let opts = Emit::default();
1669        assert!(focus_rule("field", Depth::Well, &opts).contains("outline-offset: calc(-1 * 2px)"));
1670        assert!(focus_rule("button", Depth::Raised, &opts).contains("outline-offset: 2px"));
1671        // Nothing to sit inside of, so it sits outside.
1672        assert!(focus_rule("badge", Depth::Sunken, &opts).contains("outline-offset: 2px"));
1673
1674        // And the ring is not the bevel. Reusing border_width emitted a 1px
1675        // ring that every consumer had already overridden.
1676        assert_ne!(opts.focus_width, opts.border_width);
1677    }
1678
1679    #[test]
1680    fn hover_is_gated_on_capability_and_the_keyboard_path_is_not() {
1681        // goingson's section 60 exists only to take back the hover state this
1682        // crate handed it. Gating at the source is what deletes that section
1683        // in all three apps rather than having each fight for it.
1684        let css = stylesheet(&Emit::default());
1685        let condition = format!("@media {}", Density::Pointer.media_condition());
1686        assert!(css.contains(&condition));
1687
1688        // What is gated is every hover state the surfaces carry. The row's
1689        // actions used to be the other half of this test and are not gated any
1690        // more, because they are not hidden any more: a rule that reveals
1691        // nothing needs no capability answer.
1692        let gated: Vec<&str> = css.lines().filter(|line| line.contains(":hover")).collect();
1693        assert!(!gated.is_empty(), "{css}");
1694        for line in gated {
1695            let indent = line.len() - line.trim_start().len();
1696            assert!(indent > 4, "an ungated hover rule: {line}");
1697        }
1698        assert!(!css.contains(".row:hover"), "{css}");
1699    }
1700
1701    #[test]
1702    fn the_capability_answer_is_asked_for_and_not_assumed() {
1703        // Both halves come from the crates that own them. If `makeover-touch`
1704        // ever says a fingertip has hover, this stops gating on its own.
1705        assert!(!Affordance::Hover.available(Density::Touch, SizeClass::Compact));
1706        assert!(Affordance::Hover.available(Density::Pointer, SizeClass::Compact));
1707        assert_eq!(hover_condition(), Some(Density::Pointer.media_condition()));
1708
1709        // And the size class passed to that call is not a claim about width.
1710        assert!(Affordance::Hover.reads_density());
1711        for size in [SizeClass::Compact, SizeClass::Medium, SizeClass::Expanded] {
1712            assert!(!Affordance::Hover.available(Density::Touch, size));
1713        }
1714    }
1715
1716    #[test]
1717    fn hover_resolves_against_the_token_makeover_already_derives() {
1718        let css = interactive_rules("card", Depth::Raised, &Emit::default());
1719        assert!(css.contains(".card:hover {"));
1720        assert!(css.contains("background: var(--hover-surface)"));
1721        // Not the app's choice, which was --surface-overlay.
1722        assert!(!css.contains("surface-overlay"));
1723    }
1724
1725    #[test]
1726    fn a_badge_gets_no_edge_and_no_fill() {
1727        // Decision 2, and the one visible redesign in phase A. Token::Badge is
1728        // Flat: an edge on a label says it can be pressed.
1729        let css = token_rules(&Emit::default());
1730        let badge = css
1731            .lines()
1732            .skip_while(|l| !l.starts_with(".badge {"))
1733            .take_while(|l| !l.starts_with('}'))
1734            .collect::<Vec<_>>()
1735            .join("\n");
1736        assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
1737        assert!(!badge.contains("background"), "badge kept a fill: {badge}");
1738        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1739        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1740    }
1741
1742    #[test]
1743    fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
1744        let css = token_rules(&Emit::default());
1745        // Neutral is the absence of a status, not a status named "none".
1746        assert!(css.contains(".badge {\n    color: var(--content-muted);"));
1747        assert!(!css.contains("data-tone=\"content-muted\""));
1748        for tone in ["info", "success", "warning", "danger"] {
1749            assert!(
1750                css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
1751                "missing tone {tone}"
1752            );
1753            assert!(css.contains(&format!("color: var(--{tone})")));
1754        }
1755    }
1756
1757    #[test]
1758    fn a_chip_is_raised_and_latches_into_a_well() {
1759        let css = token_rules(&Emit::default());
1760        assert!(css.contains(".chip {"));
1761        assert!(css.contains(".chip.latched {"));
1762        assert!(css.contains(".chip:active {"));
1763        // The whole difference from a badge: it answers a click.
1764        assert!(Token::Chip { removable: false }.interactive());
1765        assert!(!Token::Badge.interactive());
1766    }
1767
1768    #[test]
1769    fn only_a_tab_comes_forward_when_chosen() {
1770        // The folder semantic. Collapsing the three selectors would lose it.
1771        let css = selector_rules(&Emit::default());
1772        assert!(css.contains(".tab.chosen {"));
1773        assert!(css.contains(".segment.chosen {"));
1774        assert!(css.contains(".toggle.chosen {"));
1775        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1776        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1777        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1778
1779        let tab = css
1780            .lines()
1781            .skip_while(|l| !l.starts_with(".tab.chosen {"))
1782            .take_while(|l| !l.starts_with('}'))
1783            .collect::<Vec<_>>()
1784            .join("\n");
1785        assert!(
1786            tab.contains("var(--bevel-raised)"),
1787            "tab was held in: {tab}"
1788        );
1789    }
1790
1791    #[test]
1792    fn an_unchosen_tab_recedes_without_looking_picked() {
1793        let css = selector_rules(&Emit::default());
1794        // Recessed by colour and given no edge. An edge would make every option
1795        // look picked; flat would leave the chosen one nothing to come forward
1796        // from, which is the gap makeover-layout 0.3.0 closed.
1797        assert!(
1798            css.contains(".tab {\n    background: var(--surface-sunken);\n}"),
1799            "unchosen tab is not recessed: {css}"
1800        );
1801        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1802        assert!(css.contains(".tab:hover {"));
1803    }
1804
1805    #[test]
1806    fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
1807        // The inverse of the tab, and why the three selectors are not one
1808        // member with a flag.
1809        let css = selector_rules(&Emit::default());
1810        assert!(css.contains(".segment {\n    background: var(--surface-raised);"));
1811        assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
1812        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1813    }
1814
1815    #[test]
1816    fn a_rows_actions_are_shown_at_rest() {
1817        let css = row_rules(&Emit::default());
1818
1819        // The hover reveal is gone, and with it every escape it needed. What
1820        // it hid was hidden from pointer users alone, who are the ones
1821        // scanning a list to learn what can be done to a row.
1822        assert!(!css.contains("opacity"), "{css}");
1823        assert!(!css.contains("pointer-events"), "{css}");
1824        assert!(!css.contains(":hover"), "{css}");
1825        assert!(!css.contains(":focus-within"), "{css}");
1826
1827        // Nor is it hidden any other way. `display: none` would reflow the row
1828        // and `visibility: hidden` would take the actions out of the focus
1829        // order; the point is that neither is reached for.
1830        assert!(!css.contains("display: none"), "{css}");
1831        assert!(!css.contains("visibility:"), "{css}");
1832    }
1833
1834    #[test]
1835    fn a_figures_tone_lands_on_the_delta_when_there_is_one() {
1836        // 0.13.0. The delta is the part that reads as good or bad; the number
1837        // itself is an ordinary fact. A figure with no delta has nowhere else to
1838        // put the colour, so the value takes it, and `:has` is what lets one
1839        // attribute mean both without the emitter choosing an element.
1840        let css = stylesheet(&Emit::default());
1841
1842        assert!(
1843            css.contains(".figure[data-tone=\"success\"] > .figure-change"),
1844            "{css}"
1845        );
1846        assert!(
1847            css.contains(
1848                ".figure[data-tone=\"success\"]:not(:has(> .figure-change)) > .figure-value"
1849            ),
1850            "{css}"
1851        );
1852        // The caption is the noun and never takes the tone.
1853        assert!(
1854            !css.contains("[data-tone=\"success\"] > .figure-caption"),
1855            "{css}"
1856        );
1857    }
1858
1859    #[test]
1860    fn the_three_text_parts_take_their_intents_and_actions_inherits() {
1861        let css = row_rules(&Emit::default());
1862        assert!(css.contains(".row-primary {\n    color: var(--content);"));
1863        assert!(css.contains(".row-secondary {\n    color: var(--content-secondary);"));
1864        assert!(css.contains(".row-meta {\n    color: var(--content-muted);"));
1865        // Actions carry controls, not text. Pinning the colour it would inherit
1866        // anyway is louder than saying nothing.
1867        assert!(!css.contains(".row-actions {\n    color:"));
1868    }
1869
1870    #[test]
1871    fn the_token_strip_takes_no_colour_of_its_own() {
1872        // makeover-layout 0.9.0. A token carries its own tone, so a colour on
1873        // the strip would be a rule fighting the things sitting in it -- the
1874        // same reasoning as actions, reached for a different reason.
1875        let css = row_rules(&Emit::default());
1876        assert!(!css.contains(".row-tokens {\n    color:"));
1877    }
1878
1879    #[test]
1880    fn an_unknown_row_part_renders_plainly_rather_than_failing_to_build() {
1881        // What `#[non_exhaustive]` bought and what it cost. `part_class` can no
1882        // longer be exhaustive, so a member added upstream lands as a bare
1883        // class with no rule instead of stopping the build. Asserting the
1884        // fallback exists is what keeps it from being written as `unreachable!`
1885        // by someone who reads the match as closed.
1886        assert_eq!(part_class(RowPart::Tokens), "row-tokens");
1887        assert_eq!(part_class(RowPart::Meta), "row-meta");
1888    }
1889
1890    #[test]
1891    fn a_link_takes_the_action_colour_the_theme_actually_defines() {
1892        // `--action-primary` shipped here for months and no theme has ever
1893        // defined it, so every `.link` dropped its colour declaration outright
1894        // and fell back to inherited text. Nothing caught it because the sheet
1895        // is valid CSS either way; MNW's no-undefined-token lint is what found
1896        // it, 2026-08-14. The hover arm two lines below was always `--action-hover`,
1897        // which is what makes the typo legible in hindsight.
1898        let css = link_rules(&Emit::default());
1899        assert!(css.contains("color: var(--action);"));
1900        assert!(!css.contains("--action-primary"));
1901        assert!(css.contains("color: var(--action-hover);"));
1902    }
1903
1904    #[test]
1905    fn the_progress_trough_is_a_well() {
1906        let css = progress_rules(&Emit::default());
1907        assert!(css.contains(".progress {"));
1908        assert!(css.contains("box-shadow: var(--bevel-inset)"));
1909        assert!(css.contains(".progress > .progress-fill {"));
1910        assert!(css.contains("background: var(--action)"));
1911        // A bare `.fill` would catch things that have nothing to do with
1912        // progress once the sheet lands unprefixed.
1913        assert!(!css.contains("> .fill "));
1914    }
1915
1916    #[test]
1917    fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
1918        let css = progress_rules(&Emit::default());
1919        // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
1920        // status is still reporting progress, and muted would read as disabled.
1921        assert!(css.contains(".progress > .progress-fill {\n    background: var(--action);"));
1922        assert!(!css.contains("progress-fill {\n    color: var(--content-muted)"));
1923        for tone in ["info", "success", "warning", "danger"] {
1924            assert!(
1925                css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
1926                "missing progress tone {tone}"
1927            );
1928        }
1929        // goingson's two live cases, which is why the tones are emitted at all.
1930        assert!(css.contains("[data-tone=\"success\"] {\n    background: var(--success);"));
1931        assert!(css.contains("[data-tone=\"danger\"] {\n    background: var(--danger);"));
1932    }
1933
1934    #[test]
1935    fn no_scrollbar_track_is_emitted() {
1936        // Decision 3's negative half. It was on the phase A list and came off;
1937        // this is what stops it drifting back in.
1938        let css = stylesheet(&Emit::default());
1939        assert!(!css.contains("scrollbar"));
1940        assert!(!css.contains("::-webkit"));
1941    }
1942
1943    #[test]
1944    fn an_invalid_field_is_ringed_without_being_lit() {
1945        let css = surface_rules(&Emit::default());
1946        assert!(css.contains(".field {"));
1947        // The ARIA attribute, not a class: one fact, read by both the visual
1948        // and the accessible state, so they cannot drift.
1949        assert!(css.contains(".field[aria-invalid=\"true\"] {"));
1950        assert!(!css.contains(".field.invalid"));
1951        // A flat ring: this edge says "wrong", and a two-tone bevel would have
1952        // it say "raised" at the same time.
1953        assert!(css.contains("0 0 0 1px var(--danger)"));
1954    }
1955
1956    #[test]
1957    fn an_invalid_field_keeps_the_well_underneath_it() {
1958        // box-shadow is not additive. A lone ring replaces the bevel and drops
1959        // the well out from under the field, which is what this emitted before
1960        // 0.5.0 and is the whole reason the rule composes.
1961        let css = surface_rules(&Emit::default());
1962        let invalid = css
1963            .lines()
1964            .skip_while(|l| !l.starts_with(".field[aria-invalid"))
1965            .take_while(|l| !l.starts_with('}'))
1966            .collect::<Vec<_>>()
1967            .join("\n");
1968        assert!(
1969            invalid.contains("var(--bevel-inset)"),
1970            "the well was dropped: {invalid}"
1971        );
1972        assert!(invalid.contains("var(--danger)"));
1973    }
1974
1975    #[test]
1976    fn button_and_card_come_out_identical_by_construction() {
1977        // The duplication phase A deletes. They are the same composition, so
1978        // the only honest way to emit both is from one call.
1979        let opts = Emit::default();
1980        let css = surface_rules(&opts);
1981        assert_eq!(
1982            depth_declarations(Depth::Raised),
1983            depth_declarations(Depth::Raised)
1984        );
1985        assert!(css.contains(".button {"));
1986        assert!(css.contains(".card {"));
1987        assert_eq!(
1988            interactive_rules("button", Depth::Raised, &Emit::default()).replace("button", "card"),
1989            interactive_rules("card", Depth::Raised, &Emit::default())
1990        );
1991    }
1992
1993    #[test]
1994    fn a_prefix_reaches_the_component_classes_too() {
1995        let opts = Emit {
1996            class_prefix: "mo-",
1997            ..Emit::default()
1998        };
1999        let css = stylesheet(&opts);
2000        for name in [
2001            "mo-button",
2002            "mo-card",
2003            "mo-field",
2004            "mo-badge",
2005            "mo-chip",
2006            "mo-tab",
2007            "mo-row-primary",
2008            "mo-progress",
2009            "mo-progress-fill",
2010        ] {
2011            assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
2012        }
2013        // The bare names must be gone entirely, or a prefixed build still
2014        // collides with the app's own stylesheet.
2015        assert!(!css.contains(".button {"));
2016        assert!(!css.contains(".card {"));
2017        assert!(!css.contains(".badge {"));
2018    }
2019
2020    #[test]
2021    fn the_class_a_renderer_puts_on_an_option_is_the_one_the_rules_key_off() {
2022        // `option_class` is the contract a screen renderer writes markup
2023        // against, and the rules below are the other half of it. They come off
2024        // one mapping now, so this asserts the mapping is the one that reaches
2025        // the stylesheet rather than that two lists still agree.
2026        let css = stylesheet(&Emit::default());
2027        for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
2028            let name = option_class(selector);
2029            assert!(css.contains(&format!(".{name} {{")), "{name}: {css}");
2030            assert!(css.contains(&format!(".{name}.chosen {{")), "{name}: {css}");
2031        }
2032        assert_eq!(option_class(Selector::Tabs), "tab");
2033    }
2034
2035    #[test]
2036    fn the_caret_brings_its_own_gap_and_its_own_reserved_box() {
2037        let css = stylesheet(&Emit::default());
2038
2039        // The space is inside the glyph, which is what the other two renderers
2040        // write. Emitted bare, every consumer has to add it back, and the
2041        // obvious way to add it -- `content` in an app stylesheet, which is
2042        // unlayered and so outranks this sheet -- deletes the caret instead.
2043        assert!(css.contains("content: \" \\2191\";"), "{css}");
2044        assert!(css.contains("content: \" \\2193\";"), "{css}");
2045        assert!(!css.contains("content: \"\\2"), "{css}");
2046
2047        // The unsorted arm holds the box open so pressing a heading does not
2048        // move the row, and the sorted arms have to turn the glyph back on
2049        // after it: same specificity, so order is what decides.
2050        let reserve = css
2051            .find(".table-heading[data-sortable]::after")
2052            .expect("the reserved box is emitted");
2053        let sorted = css
2054            .find(".table-heading[aria-sort=\"ascending\"]::after")
2055            .expect("the ascending caret is emitted");
2056        assert!(reserve < sorted, "{css}");
2057        assert!(
2058            css[reserve..sorted].contains("visibility: hidden;"),
2059            "{css}"
2060        );
2061        assert!(css[sorted..].contains("visibility: visible;"), "{css}");
2062    }
2063
2064    #[test]
2065    fn a_destructive_button_has_somewhere_for_its_tone_to_land() {
2066        let css = component_rules(&Emit::default());
2067
2068        for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
2069            assert!(
2070                css.contains(&format!(".button[data-tone=\"{}\"]", tone.token())),
2071                "{css}"
2072            );
2073        }
2074        // Colour, not a fill. A red surface is an app's decision about emphasis.
2075        assert!(!css.contains(".button[data-tone=\"danger\"] {\n    background"));
2076    }
2077
2078    #[test]
2079    fn a_described_list_is_not_a_bulleted_list() {
2080        let css = component_rules(&Emit::default());
2081        assert!(css.contains(".list {\n    list-style: none;"), "{css}");
2082    }
2083
2084    #[test]
2085    fn a_table_lays_itself_out_without_being_told_its_columns() {
2086        // The whole point of the CSS table. A described table's columns are
2087        // known at render time, so anything the stylesheet has to be told about
2088        // them would have to travel with the markup.
2089        let css = component_rules(&Emit::default());
2090
2091        assert!(css.contains(".table {\n    display: table;"), "{css}");
2092        assert!(css.contains("display: table-row;"), "{css}");
2093        assert!(css.contains("display: table-cell;"), "{css}");
2094        assert!(!css.contains("grid-template-columns"), "{css}");
2095    }
2096
2097    #[test]
2098    fn a_control_in_a_cell_is_not_painted_as_text() {
2099        // The point of makeover-layout 0.14.0's CellPart, and the table-side
2100        // twin of `the_three_text_parts_take_their_intents_and_actions_inherits`
2101        // above. One `.cell` and one content colour meant a button in a cell
2102        // inherited it.
2103        let css = table_rules(&Emit::default());
2104
2105        assert!(
2106            css.contains(".cell-value {\n    color: var(--content);"),
2107            "{css}"
2108        );
2109        assert!(!css.contains(".cell-actions {\n    color:"), "{css}");
2110        assert!(!css.contains(".cell-tokens {\n    color:"), "{css}");
2111        assert!(!css.contains(".cell-link {\n    color:"), "{css}");
2112
2113        // The colour is on the part that is text, never on the container. On
2114        // `.cell` it would cascade into the three parts that are not text,
2115        // which is the bug written as one rule.
2116        assert!(!css.contains(".cell {\n    color:"), "{css}");
2117    }
2118
2119    #[test]
2120    fn an_unknown_cell_part_renders_plainly_rather_than_failing_to_build() {
2121        // `part_class`'s obligation, taken on for the table side too. CellPart
2122        // is `#[non_exhaustive]`, so a member added upstream must land as a
2123        // bare class rather than as a build that stops.
2124        assert_eq!(cell_part_class(CellPart::Value), "cell-value");
2125        assert_eq!(cell_part_class(CellPart::Actions), "cell-actions");
2126    }
2127
2128    #[test]
2129    fn a_column_drops_by_its_priority_and_never_by_its_position() {
2130        let css = component_rules(&Emit::default());
2131
2132        // Optional goes at the narrowest class and secondary goes with it,
2133        // which is `kept_at`'s cutoff walk said as two queries.
2134        let compact = css
2135            .find(&format!("@media {}", SizeClass::Compact.media_condition()))
2136            .expect("a compact query");
2137        let medium = css
2138            .find(&format!("@media {}", SizeClass::Medium.media_condition()))
2139            .expect("a medium query");
2140        assert!(css[compact..].contains(".cell-drops-next"), "{css}");
2141        assert!(!css[medium..].contains(".cell-drops-next"), "{css}");
2142
2143        // Essential columns are never mentioned, because not being mentioned is
2144        // already what never dropping means.
2145        assert!(!css.contains(".cell-keeps"), "{css}");
2146
2147        // And nothing counts. `nth-child` is the bug the priority vocabulary
2148        // exists to end.
2149        assert!(!css.contains("nth-child"), "{css}");
2150    }
2151
2152    #[test]
2153    fn the_whole_sheet_still_names_every_colour() {
2154        // The crate's founding property, asserted over the component layer and
2155        // not only the primitives.
2156        let css = stylesheet(&Emit::default());
2157        assert!(!css.contains('#'));
2158        assert!(!css.contains("rgb"));
2159        for line in css.lines() {
2160            // Declarations only: a selector or an at-rule can carry a colon of
2161            // its own (`:root`, `:hover`, `@media (hover: hover)`) and declares
2162            // nothing. Keyed on the trailing semicolon rather than on leading
2163            // indentation, which only ever worked as a proxy for nesting depth
2164            // and stopped when the sheet gained a cascade layer around it.
2165            let trimmed = line.trim();
2166            if !trimmed.ends_with(';') {
2167                continue;
2168            }
2169            let Some((_, value)) = trimmed.split_once(": ") else {
2170                continue;
2171            };
2172            if value.contains("var(--") {
2173                continue;
2174            }
2175            // Everything left has to be a keyword, a number or a
2176            // caller-supplied length, never a colour.
2177            //
2178            // The length arm is what the comment above always claimed and the
2179            // list never covered: `border_width` arrives from `Emit` and lands
2180            // bare in the focus ring's offset, where the bevel had only ever
2181            // used it inside an `inset` shadow.
2182            let opts = Emit::default();
2183            assert!(
2184                value.contains("inset")
2185                    || value.contains(opts.border_width)
2186                    || value.contains(opts.focus_width)
2187                    // 0.12.0's two: a sortable header is a control and says so
2188                    // with the pointer, and the caret is this renderer's own
2189                    // expression of `aria-sort`. Neither is a colour, which is
2190                    // what this test is actually about, and neither is a size,
2191                    // which is the other thing this crate must not name. The
2192                    // leading space inside the glyph is the same thing the other
2193                    // two renderers write into theirs, so it is part of the
2194                    // caret rather than spacing this crate decided on.
2195                    || value
2196                        .trim_start_matches('"')
2197                        .trim_start()
2198                        .starts_with("\\2")
2199                    || matches!(
2200                        value.trim_end_matches(';'),
2201                        "0" | "1"
2202                            | "none"
2203                            | "auto"
2204                            | "not-allowed"
2205                            | "pointer"
2206                            // The caret's reserved box. Visibility is presence,
2207                            // not magnitude and not colour.
2208                            | "hidden"
2209                            | "visible"
2210                            // The link's two signals. `underline` is a line and
2211                            // `inherit` defers to whatever the app set, so
2212                            // neither names a colour or a magnitude.
2213                            | "underline"
2214                            | "inherit"
2215                            // The table frame. `display` is structure and not a
2216                            // size; `nowrap` is what makes a content column
2217                            // content. The two widths are the awkward pair and
2218                            // they are still not sizes: `100%` is "all of
2219                            // whatever you were given" and `1%` is the CSS
2220                            // table idiom for "shrink to fit", which is a
2221                            // behaviour spelled as a number because CSS has no
2222                            // keyword for it. Neither names a magnitude, which
2223                            // is the thing this crate leaves to
2224                            // makeover-geometry.
2225                            | "table"
2226                            | "table-row"
2227                            | "table-cell"
2228                            | "nowrap"
2229                            | "100%"
2230                            | "1%"
2231                            // A picture's three, 0.36.0. `block` is structure
2232                            // for the reason `table` is: an inline image sits
2233                            // on the baseline and carries a descender's worth
2234                            // of space under it, which is a fact about
2235                            // replaced elements rather than a size this crate
2236                            // chose. `cover` and `contain` are `Fit`'s two
2237                            // named members reaching CSS unchanged, which is
2238                            // an intent arriving rather than a value being
2239                            // picked.
2240                            | "block"
2241                            | "cover"
2242                            | "contain"
2243                    ),
2244                "unrecognised literal value: {line}"
2245            );
2246        }
2247    }
2248
2249    #[test]
2250    fn flat_emits_nothing_at_all() {
2251        assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
2252        assert!(!depth_rules(&Emit::default()).contains("flat"));
2253    }
2254
2255    #[test]
2256    fn a_prefix_namespaces_every_class() {
2257        let opts = Emit {
2258            class_prefix: "mo-",
2259            ..Emit::default()
2260        };
2261        let css = depth_rules(&opts);
2262        assert!(css.contains(".mo-raised {"));
2263        assert!(css.contains(".mo-well {"));
2264        assert!(!css.contains(".raised {"));
2265    }
2266
2267    #[test]
2268    fn the_border_width_is_the_callers() {
2269        let opts = Emit {
2270            border_width: "2px",
2271            ..Emit::default()
2272        };
2273        assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
2274    }
2275
2276    #[test]
2277    fn edges_agree_with_the_description() {
2278        // Not a tautology: it is the guard that a CSS-shaped convenience never
2279        // quietly reverses which side is lit.
2280        let (tl, br) = Bevel::Raised.edges();
2281        assert_eq!(tl.token(), Edge::Light.token());
2282        assert_eq!(br.token(), Edge::Dark.token());
2283    }
2284}