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