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