Skip to main content

makeover_webview/
lib.rs

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