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