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//! Some of what phase A emits is not a look but the withdrawal of one. A
36//! renderer that picks its element from the description inherits that element's
37//! user-agent chrome, and [`reset`] is where a primitive says which parts of it
38//! were never asked for.
39//!
40//! # Phase B: the markup, one description at a time
41//!
42//! [`form`] renders [`makeover_layout::Field`], which is the half of phase B
43//! whose description is settled. It emits strings, because both apps
44//! interpolate their fields into larger string-built forms and returning nodes
45//! would rewrite those too. It owns its own escaping, on the reasoning in that
46//! module: a Rust encoder can cover element text and attribute values with one
47//! function, where the apps need four and have to choose correctly at every
48//! call site.
49//!
50//! [`facet`] renders `makeover_layout::Facet`: a dimension a set is narrowed by,
51//! and the one phase-B emitter whose markup an app is not keeping, because the
52//! markup it replaces was two mechanisms rather than one. A tag's selection and
53//! a tag's browse position were separate state on MNW's discover page, which is
54//! why every filter row there carries a tick box *and* a chevron; one gesture
55//! doing both is what lets the second one go.
56//!
57//! [`list`] is the other half: column tracks, the narrowing rules, and the cell
58//! containers a row is made of. It stops at the cell boundary and does not
59//! render what goes inside one, on the reasoning in that module. So phase B is
60//! now the frame around content in both directions, and what an app still owns
61//! is the content itself.
62//!
63//! # What phase A settled, and what it costs
64//!
65//! Measured against goingson's `styles.css` rather than against a component
66//! list: `.btn`, `.card` and `.tag, .badge` each hand-write the same
67//! composition, so three quarters of phase A is one rule with several names.
68//!
69//! Two of the four decisions change how goingson looks, and adoption should
70//! not be described as a pure deletion:
71//!
72//! - **Pressed carries its fill.** [`interactive_rules`] emits
73//!   [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
74//!   will press to `--surface-well`, and hovers to `--surface-overlay` today
75//!   and will hover to `--hover-surface`. Since `surface-well` inverts by theme
76//!   where `surface-sunken` does not, a dark theme presses *lighter* than it
77//!   hovers. That falls out of `makeover`'s own derivation, which says outright
78//!   that `surface-sunken` cannot serve as a well, so if it reads wrong the
79//!   answer is there and not here.
80//! - **Badges go flat.** See [`token_rules`].
81//!
82//! The other two: the progress trough is renderer-local and the scrollbar
83//! track was dropped ([`component_rules`]), and no class prefix ships by
84//! default, so adoption means deleting the app's hand-written rule in the same
85//! commit that adds the generated one. `.card`, `.badge` and the tab classes
86//! all already exist in goingson, and while both rules exist the cascade order
87//! decides which wins. That is the one real risk in adopting this, and it is
88//! why the migration lands per component rather than in one commit.
89//!
90//! # Interaction states
91//!
92//! [`interactive_rules`] emits four states, in emission order, and the order is
93//! load-bearing: they are all specificity (0,2,0), so disabled beats hover by
94//! coming last and by nothing else. Nothing here reaches for `:not(:disabled)`,
95//! which would raise a selector this crate wraps in its own layer.
96//!
97//! Emitting the states here is what keeps an app from completing the primitive
98//! from outside, by out-specifying a rule it does not own. Those overrides are
99//! also what breaks under cascade layers: an app that declares `@layer` puts
100//! its own rules in a named layer, and unlayered declarations outrank every
101//! named layer regardless of specificity.
102//!
103//! Hover sits inside a capability query. `makeover-touch` answers whether a
104//! fingertip has hover and `makeover-geometry` spells the condition; this crate
105//! asks and does not decide, so no app has to take the hover state back on
106//! touch.
107//!
108//! # The layer contract
109//!
110//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
111//! lives in `makeover-geometry` because that is the one crate every CSS emitter
112//! in the family already depends on). `makeover-geometry` does the same for
113//! `geometry.css`.
114//!
115//! The cascade resolves origin and importance, then layer, then specificity,
116//! then source order, and **unlayered normal declarations outrank every named
117//! layer**. An unlayered generated file therefore beats every rule an app owns,
118//! regardless of specificity and regardless of loading last. Nothing errors when
119//! that happens: the CSS is valid, the minifier is happy, and buttons and badges
120//! look subtly wrong. The layer belongs here rather than in each app, because an
121//! app cannot fix it from its own stylesheet: the fix is to layer the file it
122//! does not own.
123//!
124//! An app should declare the order once, or the layer's position is decided by
125//! whichever generated file the browser happens to see first:
126//!
127//! ```css
128//! @layer makeover, base, components, responsive;
129//! ```
130//!
131//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
132//! from this crate's pieces. Rules an app generates from
133//! [`list::narrowing_css`] and [`list::grid_template_columns`] are as generated
134//! as the ones here, so they belong in the same layer and this crate cannot put
135//! them there on the app's behalf.
136//!
137//! # Suggestions
138//!
139//! `Outcome::Suggestions` carries `Candidate` rather than `Choice`, and a
140//! candidate has no `unavailable`: a suggestion that cannot be picked is a row
141//! a route should not have offered. What it has instead is a `detail`, the line
142//! that tells it from a row reading the same, and it is drawn in
143//! `--content-muted` rather than in the disabled token. A detail orients rather
144//! than refuses, and every other secondary line in this crate reads the same
145//! way. The class is `.form-suggestion-detail`.
146//!
147//! # An interval is one question with two ends
148//!
149//! [`makeover_layout::FieldKind::Interval`] emits a `role="group"` named by the
150//! field's label, holding one `<input type="number">` per end.
151//!
152//! - **The group carries the error and the descriptions**, on the split
153//!   [`makeover_layout::FieldKind::Radio`] already uses here: what is wrong is
154//!   the answer, and a crossed interval is not the fault of either end.
155//! - **Both boxes take the whole extent.** `min`, `max` and `step` describe the
156//!   axis, so they are written twice. The crossing rule is not emitted, because
157//!   HTML has no attribute for it and the description does not carry it: it
158//!   comes back as an error on the group, like every other refusal.
159//! - **Which end is which is `aria-label` and nothing more.** The description
160//!   states direction structurally, by which member holds which name, and never
161//!   in words. Visible Min and Max captions are a page's own and reach the
162//!   group through [`form::Filling::trailing`].
163//!
164//! [`form::Value::Between`] is the second value. A separator inside one string
165//! would make this crate the owner of a delimiter that either end could contain.
166//!
167//! # A number's unit is adjacent text
168//!
169//! HTML has no unit attribute and inventing one would be markup nothing reads,
170//! so `Field::unit` is a `<span>` after the control. It is named in
171//! `aria-describedby` rather than left as decoration, because a number and what
172//! it is measured in are one fact and reading the first without the second is
173//! reading it wrong. What that buys is a unit a consumer can read back rather
174//! than a suffix on a label it would have to parse.
175//!
176//! # A curve this renderer can carry, and one it declines
177//!
178//! A range takes its granularity from the curve (`Field::curve.step()`), every
179//! other kind keeps `Field::step`, and `Curve::Linear` emits a plain range.
180//!
181//! **A constant-ratio curve emits a linear track, and that is the answer, not a
182//! debt.** HTML has no logarithmic range input, so a described screen asking
183//! for one is asking the browser for something it does not have, the same class
184//! of request as [`makeover_layout::FieldKind::Date`] on a host with no
185//! calendar. The renderer answers with the nearest control the host really
186//! offers and keeps every fact that survives the translation: the extent, the
187//! granularity, and the value's own units. What does not survive is resolution
188//! at the small end. The value submitted is still a value in the field's own
189//! units, which is what every handler on this path reads.
190//!
191//! The alternatives are worse in the specific way this stack exists to avoid.
192//! Shipping JS that maps thumb position to value puts app code back in the
193//! renderer. Changing what the control submits from a value to a fraction moves
194//! the mapping to whoever reads the form, and a server reading these forms with
195//! its own handlers would take a fraction where a value is expected, silently.
196//!
197//! When this reopens: the day a described screen on the webview path asks for a
198//! non-linear range. The answer then is mapping in `quasi-router`, where one
199//! implementation serves every host, not JS here.
200//!
201//! # A markdown field gets a preview
202//!
203//! A [`makeover_layout::FieldKind::Rich`] field is marked
204//! `data-format="markdown"`, and [`form::editor_rules`] is what spends that
205//! mark. The Write/Preview pair is a segmented control, so it takes the depth,
206//! the focus ring and the chosen state from rules that already exist; the
207//! preview pane is a well, because it stands where the control stood. Both are
208//! gated on the attribute rather than on a class, which is what the attribute is
209//! for. A permission taken and not spent turns every conversion into a
210//! regression.
211//!
212//! **This crate renders no markdown.** The pane arrives empty and is filled by
213//! whatever binds the editor, which is where the host's sanitiser already is. A
214//! converter here would move that guarantee into a crate with no view of the
215//! host's content-security posture.
216//!
217//! # Ranges, ghost text, and an option that cannot be picked
218//!
219//! - `FieldKind::Range` emits `<input type="range">`, and `Field::step` emits
220//!   `step`. The step is emitted only when the description carries one: the
221//!   browser's own default is `step="1"`, which is what a description means by
222//!   saying nothing, and is also what turns a 0-to-1 threshold into a
223//!   two-position control.
224//! - A select with nothing chosen emits a disabled, selected, valueless first
225//!   option carrying `Field::placeholder`. HTML has no placeholder attribute on
226//!   `<select>`; this is the idiom, and `required` keeps working through it
227//!   because the option's value is empty.
228//! - `Choice::unavailable` emits `disabled` plus the reason. Where it goes
229//!   differs by control and the difference is forced: a radio group gets a
230//!   `.form-option-reason` span beside the label, and a `<select>` option has
231//!   room for no element at all, so the reason runs into its text.
232//! - `Choice::detail` takes the same split for the same reason: a
233//!   `.form-option-detail` span in a radio group, run into the text of a
234//!   `<select>`'s option. An option carrying both reads what it is before why it
235//!   cannot be picked.
236//!
237//! # A cell says what it holds
238//!
239//! [`CellPart`](makeover_layout::CellPart) names the four things a cell holds,
240//! and [`table_rules`] turns them into `.cell-value`, `.cell-tokens`,
241//! `.cell-actions` and `.cell-link`. The value and the link take a colour: a
242//! token carries its own tone and an action is a control rather than text.
243//!
244//! The colour goes on `.cell-value` rather than on `.cell`. On the container it
245//! cascades into the parts that are not text, and a control in a cell is painted
246//! as text, which is the drift
247//! [`RowPart::intent`](makeover_layout::RowPart) prevents for list rows.
248//!
249//! [`list::Cell::part`] is `Option<CellPart>` and never `Option<RowPart>`: the
250//! two answer different questions, and only one of them is about a cell.
251//!
252//! # A table lays itself out
253//!
254//! [`list::narrowing_css`] emits the track list and has to be called with the
255//! columns, so it works where the columns are known at build time. A table a
256//! description produced knows its columns at render time, and the rules would
257//! have to travel with the markup: a `<style>` element per table, which needs
258//! `style-src 'unsafe-inline'`, or the head, which an htmx fragment swap does
259//! not carry. [`table_rules`] lays a table out with `display: table` instead,
260//! which aligns columns across rows knowing nothing about how many there are.
261//! [`Priority`](makeover_layout::Priority) hiding is one rule per drop class,
262//! and [`list::column_classes`] is what puts those classes on a cell. **A header
263//! row emitted by a renderer's own code has to call it too**, or the header and
264//! the body disagree about which column just dropped.
265//!
266//! `.button` takes the four tones as colour, off `data-tone`, the way the badge
267//! does, so a destructive button has somewhere for its tone to land. A list is
268//! reset rather than left as a bulleted list.
269//!
270//! `RowPart::revealed_on_hover` is not honoured. Hiding a row's actions until
271//! hover hides them from pointer users alone, who are the ones scanning a list
272//! to learn what can be done to a row, and every escape the rule grows
273//! (`focus-within` for the keyboard, a capability gate for a fingertip) is a
274//! report that hiding was wrong for somebody.
275//!
276//! # The depth classes are not controls
277//!
278//! `.raised` is a statement about shape and carries no interactive set, so the
279//! vocabulary has a raised surface that is merely an object. An app that wants
280//! one does not have to take a control class and cancel the control half.
281//!
282//! `.button` is the same depth *and* a control, and takes its states from
283//! [`surface_rules`], which is where a state belongs: on the thing that claims
284//! to answer a pointer. `.card` is a raised object, and it answers a pointer
285//! only when the element it is written on is a control -- `a`, `button`,
286//! `label`, or anything carrying `data-act` -- so one name serves the card
287//! that is read and the card that is pressed.
288//!
289//! # Substitution, three ways
290//!
291//! A theme with no `surface-well` is answered differently by each renderer,
292//! which is why substitution belongs to a renderer and not to the description:
293//!
294//! - `makeover-immediate` substitutes the page in Rust.
295//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
296//!   terminal would quantise the two together.
297//! - here, CSS already has the mechanism: `var(--surface-well,
298//!   var(--surface-page))` falls back in the browser, and nothing in Rust
299//!   decides anything.
300
301#![forbid(unsafe_code)]
302
303pub mod chart;
304pub mod facet;
305pub mod figure;
306pub mod form;
307pub mod list;
308pub mod meter;
309pub mod placeholder;
310pub mod reset;
311pub mod vocabulary;
312
313/// A render of every emitter, scraped for the classes it wrote.
314///
315/// Test-only, and the guard behind [`vocabulary::names`]. See the module's own
316/// header for why the check renders rather than reads the source.
317#[cfg(test)]
318mod corpus;
319
320use crate::list::{cell_part_class, part_class};
321use crate::reset::{Chrome, Reset};
322use makeover_geometry::{Density, SizeClass};
323// Re-exported rather than redefined. An app assembling its own stylesheet out
324// of this crate's pieces needs the same layer name, and most such apps depend
325// on this crate and not on `makeover-geometry` directly: goingson builds
326// `tables.css` in its own build.rs from [`list::narrowing_css`], and those
327// rules are as generated as the ones here.
328pub use makeover_geometry::{CSS_LAYER, in_css_layer};
329
330/// This crate's version, as the generated stylesheet reports it.
331///
332/// A consumer whose lockfile still pins an old `makeover-webview` gets a
333/// well-formed sheet with components missing and no error anywhere, so the
334/// emitter has to name itself in what it writes. Read by
335/// `makeover_build::layout_css` through [`stylesheet`].
336pub const VERSION: &str = env!("CARGO_PKG_VERSION");
337use makeover_layout::{
338    Bevel, CellPart, Depth, Fallback, Fill, Flow, Intent, RowPart, Selector, Sort, State, Token,
339    Tone,
340};
341use makeover_touch::Affordance;
342use std::fmt::Write as _;
343
344/// How the emitted CSS is shaped.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346pub struct Emit {
347    /// Bevel thickness, as a CSS length.
348    ///
349    /// A value, so it arrives from the caller: border widths belong to
350    /// `makeover-geometry` and will come from there once it carries them.
351    pub border_width: &'static str,
352    /// Focus ring thickness, as a CSS length.
353    ///
354    /// Separate from [`border_width`](Self::border_width), and never derived
355    /// from it: a bevel and a focus indicator answer different questions, and
356    /// only one of them has to be noticed from across a desk.
357    ///
358    /// The default is the measured consensus rather than a new opinion. Every
359    /// consumer had already written its own ring and all three chose at least
360    /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
361    /// goingson 2px on three rules and 3px on the one covering twelve
362    /// selectors. The design system was the only thing in the tree saying 1px.
363    pub focus_width: &'static str,
364    /// Prefix for emitted class names, without the leading dot.
365    pub class_prefix: &'static str,
366}
367
368impl Default for Emit {
369    fn default() -> Self {
370        Self {
371            border_width: "1px",
372            focus_width: "2px",
373            class_prefix: "",
374        }
375    }
376}
377
378/// A string as CSS escapes, for a `content` value.
379///
380/// `\u{25B2}` becomes `\25B2`. Emitted escaped rather than literally so the
381/// stylesheet is ASCII whatever the description spells: a `content` string is
382/// read by whatever encoding the consumer serves the file as, and a caret that
383/// depends on that is a caret that works on one machine.
384///
385/// Terminated by the closing quote at every site here. A CSS hex escape takes
386/// up to six digits and ends at the first character that cannot be one, so an
387/// escape followed by more text would need a space that these do not.
388fn css_escape(text: &str) -> String {
389    text.chars().fold(String::new(), |mut out, c| {
390        let _ = write!(out, "\\{:X}", c as u32);
391        out
392    })
393}
394
395/// The CSS custom property holding a bevel's composition.
396#[must_use]
397pub fn bevel_var(bevel: Bevel) -> &'static str {
398    match bevel {
399        Bevel::Raised => "--bevel-raised",
400        Bevel::Inset => "--bevel-inset",
401    }
402}
403
404/// A `var()` reference to a fill intent, with the browser's own fallback where
405/// the intent may be absent.
406///
407/// The fallback is CSS syntax, not a decision made here. That is the whole
408/// difference between this renderer and the other two.
409#[must_use]
410pub fn fill_var(fill: Fill) -> String {
411    match fill {
412        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
413        other => format!("var(--{})", other.token()),
414    }
415}
416
417/// The two-tone edge as a `box-shadow` value.
418///
419/// Two inset shadows, one per corner pair: the light one offset down and
420/// right so it lands on the top and left edges, the dark one the other way.
421/// The same assignment `makeover-immediate` draws with polylines and
422/// `makeover-tui` draws with box-drawing characters.
423#[must_use]
424pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
425    let (top_left, bottom_right) = bevel.edges();
426    let w = opts.border_width;
427    format!(
428        "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
429        top_left.token(),
430        bottom_right.token()
431    )
432}
433
434/// The custom properties both bevels resolve through.
435///
436/// Emitted as properties rather than inlined into every rule because that is
437/// what the apps already do, and because a consumer that wants the edge
438/// without the fill reads the property directly.
439#[must_use]
440pub fn bevel_properties(opts: &Emit) -> String {
441    let mut css = String::new();
442    for bevel in [Bevel::Raised, Bevel::Inset] {
443        let _ = writeln!(
444            css,
445            "    {}: {};",
446            bevel_var(bevel),
447            bevel_shadow(bevel, opts)
448        );
449    }
450    css.push_str(ELEVATION_PROPERTY);
451    css
452}
453
454/// The cast shadow of a surface that floats over the page.
455///
456/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
457/// this crate owns the geometry, and neither has to know the other's numbers.
458///
459/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
460/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
461/// that reaches for this on a card or a plate has renamed a literal rather than
462/// replaced it.
463///
464/// Two lengths rather than one, because a single blur reads as a smudge at
465/// plate size and as a halo at menu size. The offset is small and downward: a
466/// Platinum-era menu sits just off the page rather than hovering above it.
467const ELEVATION_PROPERTY: &str =
468    "    --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
469
470/// The class name for a depth.
471#[must_use]
472pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
473    let name = match depth {
474        Depth::Flat => return None,
475        Depth::Raised => "raised",
476        Depth::Well => "well",
477        Depth::Sunken => "sunken",
478        // A depth added to the description since this renderer was last
479        // built. No class, on the same footing as Flat: emitting a name
480        // whose rule body we cannot write would put a class in the markup
481        // that the stylesheet never defines.
482        _ => return None,
483    };
484    Some(format!("{}{name}", opts.class_prefix))
485}
486
487/// A prefixed class name.
488///
489/// Public, for the renderers that emit markup this crate does not. A screen
490/// renderer writing `class="row"` has to prefix it the way the stylesheet half
491/// does, or a prefixed app gets rules matching everything except the elements
492/// that renderer wrote, and the failure is invisible: the CSS stays valid and
493/// one element is unstyled. Call this rather than copying it.
494#[must_use]
495pub fn class(name: &str, opts: &Emit) -> String {
496    let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
497    push_class(&mut out, name, opts);
498    out
499}
500
501/// A prefixed class name, written into a buffer the caller already has.
502///
503/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
504/// putting every class on every element through a `format!` allocates even in
505/// the default case, where the prefix is empty and the answer is the argument.
506/// A described table row carries roughly eighty transient allocations that way,
507/// and this and the escaper are most of them.
508///
509/// [`class`] stays for callers holding a name rather than a buffer.
510///
511/// [`escape_into`]: crate::form::escape_into
512pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
513    out.push_str(opts.class_prefix);
514    out.push_str(name);
515}
516
517/// The class an option of a selector carries, which is what the rules key off.
518///
519/// Named for the option and not for the group: [`selector_rules`] styles the
520/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
521/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
522/// and `option`, put `toggle` on the wrapping element rather than on the
523/// buttons inside it, and every described selector in that renderer came out
524/// with no depth, no focus ring and no chosen state, while the toggle group got
525/// a bevel meant for its buttons.
526///
527/// The chosen option additionally carries `chosen`, the same way a latched chip
528/// carries `latched`. That name is this crate's too; there is no reason for a
529/// caller to spell it, and [`selector_rules`] is where it is written down.
530#[must_use]
531pub fn option_class(selector: Selector) -> &'static str {
532    match selector {
533        Selector::Tabs => "tab",
534        Selector::Segmented => "segment",
535        Selector::Toggle => "toggle",
536    }
537}
538
539/// The fill and edge declarations for a depth, as a rule body.
540///
541/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
542/// Callers lean on the emptiness to skip the rule rather than emit a class that
543/// sets nothing: a class that sets no properties is a class that means "I
544/// thought about this", which is what comments are for.
545///
546/// The two halves are emitted independently because [`Depth::Sunken`] has a
547/// fill and no bevel. Requiring both would silently drop the fill for exactly
548/// that case. Independent does not
549/// mean unpaired: both halves still come off one `Depth`, so they cannot
550/// disagree about what the region is.
551#[must_use]
552pub fn depth_declarations(depth: Depth) -> String {
553    let mut css = String::new();
554    if let Some(fill) = depth.fill() {
555        let _ = writeln!(css, "    background: {};", fill_var(fill));
556    }
557    if let Some(bevel) = depth.bevel() {
558        let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
559    }
560    css
561}
562
563/// One rule giving a selector a depth, or nothing when the depth declares
564/// nothing.
565#[must_use]
566pub fn depth_rule(selector: &str, depth: Depth) -> String {
567    let body = depth_declarations(depth);
568    if body.is_empty() {
569        return String::new();
570    }
571    format!(".{selector} {{\n{body}}}\n")
572}
573
574/// The media condition a hover rule has to sit inside, or `None` if hover is
575/// unconditional.
576///
577/// Two crates answer this and neither answer is made here. `makeover-touch`
578/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
579/// that capability is spelled as a media condition. Asking both is what stops
580/// this renderer minting a third opinion, which is what all three apps did:
581/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
582/// alone, and the MNW server had no gate at all.
583///
584/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
585/// member, which reports as much through `reads_size`. Passing Compact is not
586/// a claim about width; the test below pins that every class agrees.
587fn hover_condition() -> Option<&'static str> {
588    if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
589        // A fingertip grew a hover state. Nothing to gate, and this renderer
590        // should not invent a reason to gate anyway.
591        None
592    } else {
593        Some(Density::Pointer.media_condition())
594    }
595}
596
597/// Put a rule inside a media query, or leave it alone.
598fn gated(condition: Option<&str>, rule: &str) -> String {
599    let Some(condition) = condition else {
600        return rule.to_string();
601    };
602    let mut css = format!("@media {condition} {{\n");
603    for line in rule.lines() {
604        // Blank lines stay blank. Indenting one leaves trailing whitespace,
605        // which is the sort of thing a formatter later reverts and calls a diff.
606        if line.is_empty() {
607            css.push('\n');
608        } else {
609            let _ = writeln!(css, "    {line}");
610        }
611    }
612    css.push_str("}\n");
613    css
614}
615
616/// The keyboard focus ring, placed by the depth it lands on.
617///
618/// This is the webview's **focus ring** and nothing more. **Reach** and
619/// **focus** are both the browser's — the document decides what is reachable
620/// and `:focus-visible` decides which reached thing wears the ring — and no
621/// description states either. The three terms are defined once in
622/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
623///
624/// One ring for the whole system, because a focus ring's job is to be
625/// recognised and three apps having three of them is the failure. What varies
626/// is where it sits, and that comes off [`Depth`] rather than off a per-
627/// component choice: a well takes the ring inside its own edge, and anything
628/// standing proud of the page takes it outside.
629///
630/// `outline` rather than the composed `box-shadow` the invalid-field ring at
631/// [`field_rules`] uses, and deliberately the one place the two rings are built
632/// differently. A `box-shadow` ring has to restate the bevel beside it, because
633/// `box-shadow` is not additive and a lone ring silently drops the well out
634/// from under the element. That restatement is a second copy of the depth,
635/// living in a different function from the first, and it is exactly the
636/// duplication `Depth` exists to prevent. `outline` occupies its own property,
637/// so the bevel survives untouched and there is nothing to keep in agreement.
638/// They render the same: both are a flush ring one border-width wide.
639#[must_use]
640pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
641    let w = opts.focus_width;
642    // Same magnitude either way, and only the sign comes off the depth. Both
643    // values are what the consumers had already converged on independently:
644    // 2px out is what all three wrote, and 2px in is the MNW server's own
645    // answer for the one inset ring it had.
646    let offset = match depth.bevel() {
647        // Inside the well, clear of its edge rather than painted over it.
648        Some(Bevel::Inset) => format!("calc(-1 * {w})"),
649        // Raised, or no edge at all. Outside, standing off by its own width.
650        _ => w.to_string(),
651    };
652    // The token by name. It is `makeover`'s, derived from the action colour,
653    // and reaching it through a description member was a second path to the
654    // same variable for as long as one existed.
655    format!(
656        ".{selector}:focus-visible {{\n    outline: {w} solid var(--focus-ring);\n    outline-offset: {offset};\n}}\n"
657    )
658}
659
660/// A rest depth said out loud on both axes, for a rule that has to beat the
661/// states above it.
662///
663/// [`depth_declarations`] states an axis only when the depth has something to
664/// say about it, which is right for a rest rule: a [`Depth::Flat`] region
665/// inherits what it sits on, and asserting `background: none` there would be
666/// the difference between level-with and painted-transparent. It is wrong for
667/// a rule whose whole job is to take a state back. An axis left unstated is an
668/// axis the state above keeps, so `Flat` re-asserted nothing at all and a
669/// disabled control kept whatever hover had given it.
670///
671/// So the axes the depth is silent on are withdrawn rather than skipped, and
672/// the withdrawal is spelled by [`reset`] rather than here, so a disabled
673/// control and a flat one say the same words. Reaches further than the fill:
674/// [`Depth::Sunken`] and [`Depth::Overlay`] have no bevel either, and the
675/// pressed rule above hands out an inset one.
676fn rest_declarations(depth: Depth) -> String {
677    let mut css = String::new();
678    match depth.fill() {
679        Some(fill) => {
680            let _ = writeln!(css, "    background: {};", fill_var(fill));
681        }
682        None => css.push_str(&Reset::NOTHING.and(Chrome::Fill).declarations()),
683    }
684    match depth.bevel() {
685        Some(bevel) => {
686            let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
687        }
688        None => css.push_str(&Reset::NOTHING.and(Chrome::Shadow).declarations()),
689    }
690    css
691}
692
693/// Present, visible, and not answering.
694///
695/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
696/// only matches form elements and half the things this crate emits are not
697/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
698/// the accessible state is the pattern [`field_rules`] already establishes for
699/// `aria-invalid`, on the reasoning that one fact read by both the styling and
700/// the accessibility tree cannot drift from itself.
701///
702/// The rest depth is re-asserted rather than assumed, because this rule has to
703/// beat the hover and pressed rules above it. It does that on source order at
704/// equal specificity, not by out-specifying them: every rule this function's
705/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
706/// one of them and have to be unpicked when this output moves inside its own
707/// cascade layer.
708///
709/// Re-asserted on **both** axes, through [`rest_declarations`].
710/// `depth_declarations` alone is empty for [`Depth::Flat`], so a flat control
711/// would win the contest with nothing to say and keep the hover surface
712/// underneath a control that had stopped answering.
713#[must_use]
714pub fn disabled_rule(selector: &str, depth: Depth) -> String {
715    format!(
716        ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{}    color: var(--{});\n    cursor: not-allowed;\n}}\n",
717        rest_declarations(depth),
718        State::Disabled.token()
719    )
720}
721
722/// Every state a selector that answers a click implies: hover, pressed, focus
723/// and disabled, in that order.
724///
725/// Order is the whole cascade mechanism here. All four selectors are
726/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
727/// and by nothing else.
728///
729/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
730/// only the edge is what left goingson hand-writing `background:
731/// var(--surface-sunken)` on three separate rules, and a fill that does not
732/// travel with its edge is precisely the disagreement `Depth` exists to make
733/// unrepresentable. So the pressed fill comes from the description
734/// (`--surface-well`) rather than from whatever each app reached for.
735///
736/// Hover has no member in the description and is renderer policy: a terminal
737/// and an immediate-mode painter have no hover to express. It resolves against
738/// `--hover-surface`, which `makeover` already derives and which nothing
739/// consumed until now. What it *is* gated on is capability, via
740/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
741/// goingson's section 60 exists solely to take back the hover state this
742/// function had just handed it, by out-specifying a rule it does not own.
743///
744/// `depth` is the selector's **rest** depth, used to place the focus ring and
745/// to restore the surface under a disabled control. The pressed rule keeps
746/// inverting from [`Depth::Raised`] regardless: a tab's unchosen depth is
747/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
748/// from the rest depth would leave a tab with no press at all.
749#[must_use]
750pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
751    let mut css = gated(
752        hover_condition(),
753        &format!(".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n"),
754    );
755    css.push_str(&depth_rule(
756        &format!("{selector}:active"),
757        Depth::Raised.pressed(),
758    ));
759    css.push_str(&focus_rule(selector, depth, opts));
760    css.push_str(&disabled_rule(selector, depth));
761    css
762}
763
764/// The compound a card's interactive states are written against: the class
765/// on an element that is itself a control.
766///
767/// `label` for a card wrapping a choice, `[data-act]` for an act a renderer
768/// drew on some other element. Without the class prefix, the way every
769/// selector handed to [`interactive_rules`] is.
770#[must_use]
771pub fn pressable_card(card: &str) -> String {
772    format!("{card}:is(a, button, label, [data-act])")
773}
774
775/// One rule per depth: its fill and its edge, together.
776///
777/// A depth and nothing else. `.raised` says a surface sits on what is behind
778/// it, which is a statement about the shape and not about what happens when a
779/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
780/// named surfaces are where interaction lives: `.button`, and `.card` written
781/// on a control, get their states from [`surface_rules`].
782///
783/// Giving this class the interactive set leaves the vocabulary with no raised
784/// surface that is merely an object, so a consumer that needs one has to take a
785/// control class and cancel half of it.
786#[must_use]
787pub fn depth_rules(opts: &Emit) -> String {
788    let mut css = String::new();
789    for depth in [Depth::Raised, Depth::Well] {
790        let Some(class) = depth_class(depth, opts) else {
791            continue;
792        };
793        css.push_str(&depth_rule(&class, depth));
794    }
795    css
796}
797
798/// The three surfaces that are a depth with a name.
799///
800/// `button` and `card` are both [`Depth::Raised`], and `field` is a
801/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
802/// gives a text field. Their bodies come out identical by construction rather
803/// than by hand: three hand-written copies in goingson's stylesheet is what
804/// phase A deletes, and generating them from one call is what stops them
805/// drifting apart again.
806///
807/// A card's states hang off [`pressable_card`] rather than the bare class. A
808/// card is a raised object that answers a pointer only when it is written on a
809/// control, which is what lets one name cover both: a store tile that is one
810/// link, a tier picker that is a label round a radio, and a use-case card that
811/// does nothing and so has no hover to cancel.
812fn surface_rules(opts: &Emit) -> String {
813    let mut css = String::new();
814    let button = class("button", opts);
815    css.push_str(&depth_rule(&button, Depth::Raised));
816    css.push_str(&interactive_rules(&button, Depth::Raised, opts));
817
818    let card = class("card", opts);
819    css.push_str(&depth_rule(&card, Depth::Raised));
820    css.push_str(&interactive_rules(
821        &pressable_card(&card),
822        Depth::Raised,
823        opts,
824    ));
825
826    let field = class("field", opts);
827    css.push_str(&depth_rule(&field, Depth::Well));
828
829    // A field takes focus and refuses input like everything else here, and got
830    // neither until now, which is why all three apps hand-write a focus ring
831    // for it and no two of them match. No hover or pressed: a text field does
832    // not light up under the pointer and does not invert when clicked, so the
833    // two states `interactive_rules` would add are the two it does not have.
834    css.push_str(&focus_rule(&field, Depth::Well, opts));
835    css.push_str(&disabled_rule(&field, Depth::Well));
836
837    // Keyed on the ARIA attribute rather than on a class, so the visual state
838    // and the accessible state cannot drift apart: there is one fact and both
839    // read it. goingson already drove its invalid styling this way and was
840    // right to; the `.invalid` class this emitted before 0.5.0 was a second
841    // place to forget.
842    //
843    // The ring composes *after* the bevel rather than replacing it. box-shadow
844    // is not additive, so a lone ring silently dropped the well out from under
845    // an invalid field. Flat and unlit: this edge is saying "wrong", and
846    // lighting one side would have it say "raised" at the same time.
847    let _ = writeln!(
848        css,
849        ".{field}[aria-invalid=\"true\"] {{\n    box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
850        bevel_var(Bevel::Inset),
851        opts.border_width
852    );
853    css
854}
855
856/// Badges and chips.
857///
858/// The one place phase A changes how goingson looks rather than only where its
859/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
860/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
861/// carrying the raised bevel. Splitting that means reading every call site to
862/// decide which of the two it always was.
863///
864/// What a badge does carry is a [`Tone`], the intent family it shares with
865/// notices and nothing else. Neutral is the bare class rather than a variant,
866/// because it is the absence of a status and not a status called "none".
867/// Text that goes somewhere.
868///
869/// The one inline control. A table cell carries `cell-link` instead, which
870/// reads as its row's title rather than as a link; this is the same thing
871/// outside a table, which is what a described run holds when a sentence
872/// contains a link.
873///
874/// Colour and underline only. Whether a link is inline in a sentence or sitting
875/// on its own line is the app's layout, and how much room it takes is
876/// `makeover-geometry`'s. What is here is the pair of signals that say "this
877/// goes somewhere" and nothing that says where it sits.
878///
879/// The visited arm is deliberately absent. A link inside an app points at the
880/// app's own screens, which the user is expected to have been to, so painting
881/// them differently marks almost everything and distinguishes nothing.
882fn link_rules(opts: &Emit) -> String {
883    let mut css = String::new();
884    let link = class("link", opts);
885
886    let _ = writeln!(
887        css,
888        ".{link} {{\n    color: var(--action);\n    \
889         text-decoration: underline;\n}}"
890    );
891    // The hover step is the same one every other control takes, and it is a
892    // colour rather than a surface: a link has no box to raise.
893    let _ = writeln!(
894        css,
895        "@media (hover: hover) and (pointer: fine) {{\n    .{link}:hover \
896         {{\n        color: var(--action-hover);\n    }}\n}}"
897    );
898    let _ = writeln!(
899        css,
900        ".{link}:focus-visible {{\n    outline: {} solid var(--focus-ring);\n    \
901         outline-offset: 2px;\n}}",
902        opts.focus_width
903    );
904    // A link is often a `<button>` rather than an `<a>`: a renderer picks the
905    // element from the method, so a link that writes is a button that has to
906    // stop looking like one. What that costs is named in [`reset`].
907    css.push_str(&Reset::TEXT_BUTTON.rule(&format!("button.{link}")));
908    css
909}
910
911fn token_rules(opts: &Emit) -> String {
912    let mut css = String::new();
913
914    // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
915    // and a label with an edge says it can be pressed.
916    let badge = class("badge", opts);
917    // `content-muted` literally, not `Tone::Neutral.token()`. What makes a
918    // badge quiet is `Token::Badge` answering no click, which this crate holds
919    // and `Tone` genuinely does not know. Routing it through Neutral put the
920    // claim where the evidence was not, and the bill arrived on the figure
921    // value: it took the same muting from the same call and read as its own
922    // caption. Neutral answers `content` from makeover-layout 0.36.0.
923    //
924    // A badge is a chip, wiki `table-model`: an opaque fill inside an edge, in
925    // the theme's own ink at normal weight. Coloured text was never ratified
926    // and measured 1.34:1 on goingson's warning; muted text 2.78:1 on
927    // solarized-dark. So the ink is `content` and what says which kind of
928    // token it is moves to the fill and the edge: the table's raised ground for
929    // a neutral chip, makeover's `*-surface` for a status, edged in its tone.
930    // Still no bevel: a label with a raised edge says it can be pressed.
931    let bw = opts.border_width;
932    let _ = writeln!(
933        css,
934        ".{badge} {{\n    display: inline-flex;\n    align-items: center;\n    \
935         padding: 0 var(--step-snug);\n    border: {bw} solid var(--border);\n    \
936         border-radius: var(--radius-fine);\n    background: var(--surface-raised);\n    \
937         color: var(--content);\n    font-weight: normal;\n}}"
938    );
939    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
940        let _ = writeln!(
941            css,
942            ".{badge}[data-tone=\"{0}\"] {{\n    background: var(--{0}-surface);\n    \
943             border-color: var(--{0});\n}}",
944            tone.token()
945        );
946    }
947
948    // A button carries the four tones a badge does. It had none, on the reading
949    // that a control's colour is its surface rather than its text, and that
950    // reading has one hole big enough to matter: the button that destroys
951    // something. Every consumer had written that rule itself, and a description
952    // that says `Tone::Danger` on an act had nowhere for it to land.
953    //
954    // Colour and not a fill, matching the badge. A red surface is a decision
955    // about emphasis that belongs to an app's own layer, and two of them
956    // fighting is worse than neither.
957    let button = class("button", opts);
958    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
959        let _ = writeln!(
960            css,
961            ".{button}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
962            tone.token()
963        );
964    }
965
966    // A chip holds itself down, which is `Depth::pressed` arrived at
967    // independently by two apps. `removable` is a remove affordance, so it is
968    // markup and waits for phase B.
969    let chip = class("chip", opts);
970    let unlatched = Token::Chip { removable: false };
971    css.push_str(&depth_rule(&chip, unlatched.depth(false)));
972    css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
973    css.push_str(&depth_rule(
974        &format!("{chip}.latched"),
975        unlatched.depth(true),
976    ));
977    css
978}
979
980/// The three selectors, each named by what it picks.
981///
982/// A tab comes *forward* to join the pane it opens, which is why
983/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
984/// are held in. That is the folder semantic, and it is the whole reason the
985/// three are not one member with a flag.
986///
987/// [`Selector::abutting`] is not emitted: whether the options touch is
988/// spacing, and spacing is `makeover-geometry`'s question to answer.
989///
990/// Both states emit. Naming only the chosen option leaves an unchosen one
991/// falling through to [`Depth::Flat`] with nothing drawn for it, so an app has
992/// to hand-write the recess that makes its chosen tab read as forward.
993fn selector_rules(opts: &Emit) -> String {
994    let mut css = String::new();
995    for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
996        let c = class(option_class(selector), opts);
997        css.push_str(&depth_rule(&c, selector.unchosen()));
998        css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
999        css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
1000    }
1001    css
1002}
1003
1004/// The parts of a list row.
1005///
1006/// The list is written out rather than derived because `RowPart` is
1007/// `#[non_exhaustive]`, so there is nothing to iterate. A member added upstream emits no rule until it is named here, which
1008/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
1009/// [`part_class`] carries the same list and the same obligation.
1010fn row_rules(opts: &Emit) -> String {
1011    let mut css = String::new();
1012
1013    // The container the rows sit in, giving back what a `<ul>` brought. Not a
1014    // size: there is no magnitude in it, which is the line this crate holds.
1015    css.push_str(&Reset::BULLETS.rule(&format!(".{}", class("list", opts))));
1016
1017    for part in [
1018        RowPart::Primary,
1019        RowPart::Secondary,
1020        RowPart::Meta,
1021        RowPart::Actions,
1022        RowPart::Tokens,
1023        RowPart::Proportion,
1024    ] {
1025        let c = class(part_class(part), opts);
1026
1027        // Actions carry controls rather than text, and `RowPart::intent` says
1028        // so by returning the same intent inheriting already gives. Pinning it
1029        // would be louder than saying nothing. Tokens answer alike, for their
1030        // own reason: each token carries its own tone, and a colour on the
1031        // strip would fight the things sitting in it. A proportion is the same
1032        // case again: the meter inside carries the tone.
1033        if !matches!(
1034            part,
1035            RowPart::Actions | RowPart::Tokens | RowPart::Proportion
1036        ) {
1037            let _ = writeln!(css, ".{c} {{\n    color: var(--{});\n}}", part.intent());
1038        }
1039
1040        // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
1041        // otherwise and was not honoured here from 0.23.0; makeover-layout
1042        // 0.13.0 retired the method, so there is no longer a description saying
1043        // one thing and a renderer doing another.
1044        //
1045        // The rule was `opacity: 0` gated to pointer devices, revealed on
1046        // `:hover` and on `:focus-within`. Each escape it needed was a report
1047        // that hiding was wrong for somebody: `focus-within` because tabbing
1048        // could never reach an action; the gate because a fingertip had no way
1049        // to unhide, which both webview apps had already hand-written
1050        // `opacity: 1` to undo. What was left was a control hidden from
1051        // exactly one group: people using a pointer, who are also the group
1052        // scanning a list to find out what can be done to a row.
1053        //
1054        // A settings screen is where that reads worst: the whole reason to be
1055        // on it is to remove a key, and the button doing so was invisible
1056        // until pointed at. A table cell's actions were never hidden, so the
1057        // two arrangements now agree.
1058    }
1059
1060    // A part that may take two lines. `Flow::Tight` gets no rule: one line is
1061    // what a run already does, and restating it here would put a declaration on
1062    // every part in every row to say nothing.
1063    //
1064    // This is the shape both webview apps had already written by hand and
1065    // commented -- Balanced Breakfast on a feed row's title, goingson on a
1066    // problem's body -- which is the whole argument for the description
1067    // carrying it. `-webkit-` prefixed and unprefixed together: the prefixed
1068    // trio is what every engine actually implements, and `line-clamp` is the
1069    // standard property landing behind it.
1070    let _ = writeln!(
1071        css,
1072        ".{} {{\n    display: -webkit-box;\n    -webkit-box-orient: vertical;\n    -webkit-line-clamp: {lines};\n    line-clamp: {lines};\n    overflow: hidden;\n}}",
1073        class("row-relaxed", opts),
1074        lines = Flow::Relaxed.lines()
1075    );
1076
1077    // A row inside a hierarchy: a tree, an outline, a threaded list.
1078    // `edf33114`, decided 2026-08-30 (Max). makeover-layout names the concept
1079    // as `Nesting` -- deliberately not `Depth`, which is surface bevel in that
1080    // crate -- and this is the rule.
1081    //
1082    // Measured 2026-08-30: quasi-webview has been emitting `row-nested` with
1083    // `style="--row-depth:N"` on every described hierarchy, and **no stylesheet
1084    // anywhere in the tree read any of it**. So a described outline in a
1085    // browser was a flat list with chevrons in it -- the folding worked and the
1086    // indent did not exist.
1087    //
1088    // The magnitude is a custom property with a fallback, which is this crate's
1089    // own shape: `--awaiting-gap` above is the precedent, and an app overriding
1090    // `--row-indent` is how a level becomes worth more or less. What a level IS
1091    // stays the description's; what it is WORTH is a renderer's, and a terminal
1092    // spending columns for the same fact is not disagreeing.
1093    //
1094    // Here rather than in each app, and that was a live option rather than an
1095    // oversight. `row-select`, `row-current` and `row-chosen` are app-styled by
1096    // design; the indent is not decoration, it is what the description MEANS,
1097    // and three apps agreeing about it by accident is not agreement.
1098    //
1099    // `padding` and not `margin`: a row is a box that can be selected and
1100    // hovered, and indenting with margin would take the indent out of the
1101    // highlight, so the shading under a nested row would start where its text
1102    // does rather than where its row does.
1103    let _ = writeln!(
1104        css,
1105        ".{} {{\n    padding-inline-start: calc(var(--row-depth, 0) * var(--row-indent, 1.5ch));\n}}",
1106        class("row-nested", opts)
1107    );
1108
1109    // The two halves of a branch, emitted by quasi-webview and unstyled until
1110    // now for the same reason.
1111    //
1112    // A branch row is the one a reader can fold, and the chevron is its hit
1113    // target. The chevron is drawn by the app or the description -- this says
1114    // where it sits and how big the target is, which is the accessibility fact
1115    // rather than the decorative one: a control smaller than this is one a
1116    // finger misses.
1117    let _ = writeln!(
1118        css,
1119        ".{} {{\n    display: flex;\n    align-items: baseline;\n    gap: var(--row-disclose-gap, 0.5ch);\n}}",
1120        class("row-branch", opts)
1121    );
1122    let _ = writeln!(
1123        css,
1124        ".{} {{\n    flex: none;\n    min-inline-size: var(--tap-target, 2rem);\n    min-block-size: var(--tap-target, 2rem);\n    background: none;\n    border: 0;\n    color: inherit;\n    cursor: pointer;\n}}",
1125        class("row-disclose", opts)
1126    );
1127
1128    css
1129}
1130
1131/// A row of things that share their space, and what each fallback gets here.
1132///
1133/// Ruling: wiki `layout-room-and-fallback`, Max. Rule 1 is that every described
1134/// member is in flow, and these rules are how that is kept rather than asked
1135/// for. A member taken out of flow with `position: absolute` contributes zero
1136/// width to the row it shares, so nothing can collide with it and nothing
1137/// prevents the collision.
1138///
1139/// # The floor, which is most of the fix
1140///
1141/// `.run > *` gets `min-width: min-content`. That is the derived minimum the
1142/// ruling asks for, in this renderer's own unit and stated by the browser
1143/// rather than by anybody: a member cannot be squeezed narrower than what is
1144/// in it, so members in one flow push each other instead of overlapping. It
1145/// costs no query and no number, and it is what fixes all four measured widths
1146/// whichever fallback the group declared.
1147///
1148/// # A member that asks to fill
1149///
1150/// `.run > [data-width="fill"]` gets `flex: 1 1 0`, which is the second half of
1151/// what a column has always been able to say, reaching a row of regions.
1152/// `flex-basis: 0` and not `auto` is what makes several fills divide the room
1153/// equally rather than dividing the leftovers in proportion to their contents;
1154/// equal division is [`makeover_layout::Width::Fill`]'s own stated rule. The
1155/// floor above still applies, so a fill cannot shrink under what is in it.
1156///
1157/// A member that says nothing gets nothing, because a flex item with the floor
1158/// and no grow is already content-sized. That is why the omitted value here is
1159/// `Content` while a control omits `Fill`: each position leaves out what it
1160/// already did.
1161///
1162/// # What each fallback gets, exactly
1163///
1164/// [`Fallback::Wrap`] is `flex-wrap: wrap`, which is exact. The browser wraps
1165/// the run when the members no longer fit, deciding that from their own
1166/// intrinsic widths, which is the derived minimum doing the whole job.
1167///
1168/// [`Fallback::Stack`] is wrap plus `flex: 1 1 max-content` on the members, so
1169/// a member that cannot sit beside its sibling takes a line of its own and
1170/// fills it. For the two-member run this was ruled on -- a tab strip and a
1171/// band -- that is precisely "a row becomes a column".
1172///
1173/// [`Fallback::Shed`] and [`Fallback::Menu`] get wrap, and this renderer is
1174/// honouring less than the description says. **CSS cannot express either one
1175/// without breaking the ruling's own first constraint.** Both need to know that
1176/// the run is out of room in order to take a member out of it, a container
1177/// query is the only construct that can ask, and `@container` compares against
1178/// a `<length>` -- there is no `@container (inline-size < min-content)`. So
1179/// every honest spelling of Shed here needs an authored breakpoint, which is
1180/// the thing the ruling exists to forbid, and the dishonest ones are worse: a
1181/// clamped height clips by document order rather than by [`Priority`], and
1182/// `display: none` under a viewport `@media` is the `nth-child(n+5)` bug the
1183/// vocabulary replaced.
1184///
1185/// Wrapping is the right thing to do instead. It keeps every member reachable,
1186/// which is the property that was actually broken -- goingson's new-contact
1187/// button left the viewport entirely at 560 -- and it keeps rule 1. A renderer
1188/// answering with less than was described is precedented and deliberate here:
1189/// [`makeover_layout::Region::Columns`] says a terminal stacking a board's
1190/// columns is honouring the description rather than degrading it.
1191///
1192/// The real mechanism needs the shed members to have somewhere to go, which is
1193/// markup and belongs to quasi-webview: an overflow control is a member of the
1194/// run, and the description does not yet say that a member *is* one.
1195///
1196/// # Menu, once a script is measuring
1197///
1198/// That is now built, in `quasi-webview`'s `menu.js`, and this crate's half of
1199/// it is two classes and one override. A script that has taken a menu run over
1200/// marks it `data-menu`, and a marked run goes back to `nowrap`: wrapping is
1201/// what hides the overflow condition the script is trying to measure. The
1202/// unmarked rule above is untouched, so a page that ships no script still
1203/// wraps, which is rule 1 — every member reachable — rather than a strip with
1204/// tabs squeezed off the end.
1205///
1206/// `.run-overflow` is the control the shed members move into and
1207/// `.run-overflow-items` is where they land. The geometry is this crate's the
1208/// way every other surface's is; what is *in* it is the script's, because which
1209/// members no longer fit is a measurement and not a description.
1210fn run_rules(opts: &Emit) -> String {
1211    let run = class("run", opts);
1212    let mut css = String::new();
1213
1214    // `flex-wrap: nowrap` is stated rather than left to the default, because
1215    // the fallbacks below are read as overrides of this line and a reader
1216    // should not have to know which way flexbox leans to see that.
1217    //
1218    // No gap. Spacing between members is the app's, the same way this crate
1219    // states no margins anywhere else; a gap here would be a size, and the one
1220    // hardcoded size in the mechanism is makeover-geometry's contact patch.
1221    let _ = writeln!(
1222        css,
1223        ".{run} {{\n    display: flex;\n    flex-wrap: nowrap;\n    align-items: center;\n}}"
1224    );
1225
1226    // The derived minimum, and the whole reason a member can no longer be
1227    // overlapped. `min-width: auto` is flexbox's default for a flex item and is
1228    // *not* the same thing: auto lets an item be compressed below its content
1229    // in a nowrap run, which is how a toolbar ends up drawn over a tab strip
1230    // even without anything leaving the flow.
1231    let _ = writeln!(css, ".{run} > * {{\n    min-width: min-content;\n}}");
1232
1233    // A member that absorbs what is left. `flex-basis: 0` rather than `auto` is
1234    // what makes several fills divide the room equally instead of dividing the
1235    // leftovers in proportion to what is already in them, which is
1236    // `Width::Fill`'s own rule and the one thing that type states about more
1237    // than one of them.
1238    //
1239    // The `min-width: min-content` floor above is deliberately not overridden.
1240    // A fill that could shrink below its contents would overlap its neighbour,
1241    // which is rule 1, and equal division under a floor is still equal division
1242    // everywhere the floor is not reached.
1243    //
1244    // Attribute rather than class, because the width is a fact the description
1245    // carried rather than a hook this crate invented: the same division
1246    // `data-tone` and `data-selector` are on the right side of. It beats the
1247    // `Stack` rule below on specificity whichever order they are written in,
1248    // which is what a member asking to fill should do to a blanket.
1249    let _ = writeln!(
1250        css,
1251        ".{run} > [data-width=\"fill\"] {{\n    flex: 1 1 0;\n}}"
1252    );
1253
1254    for fallback in [
1255        Fallback::Wrap,
1256        Fallback::Stack,
1257        Fallback::Shed,
1258        Fallback::Menu,
1259    ] {
1260        let name = fallback_class(fallback);
1261        let c = class(name, opts);
1262        let _ = writeln!(css, ".{c} {{\n    flex-wrap: wrap;\n}}");
1263        if matches!(fallback, Fallback::Stack) {
1264            let _ = writeln!(css, ".{c} > * {{\n    flex: 1 1 max-content;\n}}");
1265        }
1266    }
1267
1268    // A menu run a script has taken over. The mark is the script's and this is
1269    // the only rule that reads it: wrapping is what a run does when nothing is
1270    // measuring, and it is also what makes the overflow unmeasurable, since a
1271    // wrapped run always fits. The two cannot both be on.
1272    let menu = class(fallback_class(Fallback::Menu), opts);
1273    let _ = writeln!(css, ".{menu}[data-menu] {{\n    flex-wrap: nowrap;\n}}");
1274
1275    // The overflow control, and it is a member of the run like any other: in
1276    // flow, at the end, taking the width of what is in it. `relative` is what
1277    // the items hang off.
1278    let overflow = class("run-overflow", opts);
1279    let items = class("run-overflow-items", opts);
1280    let _ = writeln!(css, ".{overflow} {{\n    position: relative;\n}}");
1281
1282    // Overlaid rather than in flow, for the reason every menu is: a control
1283    // that pushed the page down when it opened would change the layout it was
1284    // opened to escape. `inset-inline-end: 0` rather than a left, so the panel
1285    // stays on the page in both writing directions.
1286    //
1287    // No width, no padding and no border. All three are sizes and sizes are
1288    // makeover-geometry's; what is stated here is placement, the surface and
1289    // the shadow that separates it from the page, which is the same division
1290    // `figure_rules` and the timeline entry make. The elevation shadow is what
1291    // an overlaid surface takes instead of an edge -- see `ELEVATION_PROPERTY`.
1292    let _ = writeln!(
1293        css,
1294        ".{items} {{\n    \
1295         position: absolute;\n    \
1296         inset-block-start: 100%;\n    \
1297         inset-inline-end: 0;\n    \
1298         z-index: 1;\n    \
1299         display: flex;\n    \
1300         flex-direction: column;\n    \
1301         align-items: stretch;\n    \
1302         background: var(--surface-raised);\n    \
1303         box-shadow: var(--elevation-overlay);\n\
1304         }}"
1305    );
1306
1307    // `hidden` is how the script closes it, and a flex display would otherwise
1308    // beat the attribute's own `display: none`.
1309    let _ = writeln!(css, ".{items}[hidden] {{\n    display: none;\n}}");
1310
1311    css
1312}
1313
1314/// Every class [`fallback_class`] can return, plus the run itself.
1315///
1316/// [`ROW_PART_CLASSES`](crate::list::ROW_PART_CLASSES)'s reasoning and the same
1317/// obligation: a `match` over a `#[non_exhaustive]` enum cannot be enumerated
1318/// from outside, so the list sits beside it and a test holds the two together.
1319/// `run` is in it because it is emitted in its own right rather than only as a
1320/// fallback's fallback.
1321pub const RUN_CLASSES: &[&str] = &[
1322    "run",
1323    "run-wrap",
1324    "run-stack",
1325    "run-shed",
1326    "run-menu",
1327    // Not returned by `fallback_class`: these two are the overflow control a
1328    // measuring renderer builds, and they are in the list because the list is
1329    // what a host seals its vocabulary against. A class emitted by a script and
1330    // missing from here is a control with no surface and no edge.
1331    "run-overflow",
1332    "run-overflow-items",
1333];
1334
1335/// The class a run carries for what it does when it is tight.
1336///
1337/// A run always carries `.run` as well, so an unrecognised fallback -- the enum
1338/// is `#[non_exhaustive]` -- lands as a plain nowrap row with the min-content
1339/// floor still under it. That is the safe failure: every member in flow and
1340/// none overlapped, which is the property, with only the rearrangement missing.
1341#[must_use]
1342pub fn fallback_class(fallback: Fallback) -> &'static str {
1343    match fallback {
1344        Fallback::Wrap => "run-wrap",
1345        Fallback::Stack => "run-stack",
1346        Fallback::Shed => "run-shed",
1347        Fallback::Menu => "run-menu",
1348        _ => "run",
1349    }
1350}
1351
1352/// The progress trough these rules fill.
1353///
1354/// [`meter::meter_html`](crate::meter::meter_html) is what fills these.
1355///
1356/// The rules stay a superset of what a description can ask for. An app drawing
1357/// its own bar keeps these classes, which is what the four goingson grew
1358/// independently were adopted onto.
1359///
1360/// The trough is a [`Depth::Well`], the same reading a text field gets:
1361/// something with its content down inside it.
1362fn progress_rules(opts: &Emit) -> String {
1363    let progress = class("progress", opts);
1364    // `progress-fill` rather than a bare `fill`: an unprefixed build claims
1365    // these names in the app's own stylesheet, and `.fill` is grabby enough to
1366    // catch things that have nothing to do with progress. goingson already
1367    // calls it `.progress-fill`, so this is also the name that deletes.
1368    let fill = class("progress-fill", opts);
1369    let mut css = depth_rule(&progress, Depth::Well);
1370
1371    // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
1372    // place this differs from the badge rules, and deliberately: a badge with
1373    // no status is a muted label, while a bar with no status is still
1374    // reporting progress, and `content-muted` would read as disabled.
1375    let _ = writeln!(
1376        css,
1377        ".{progress} > .{fill} {{\n    background: var(--action);\n}}"
1378    );
1379
1380    // A bar can be saying something, same as a badge: goingson colours subtask
1381    // progress as success and an over-estimate as danger, which is real
1382    // information rather than decoration. Emitting the tones is what lets that
1383    // survive adoption instead of staying hand-written.
1384    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1385        let _ = writeln!(
1386            css,
1387            ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n    background: var(--{0});\n}}",
1388            tone.token()
1389        );
1390    }
1391    css
1392}
1393
1394/// What a wait looks like, for the attribute that has been describing one to
1395/// nobody.
1396///
1397/// Wiki `loading-and-progress-standard`, phase 2. `data-awaiting` is emitted
1398/// as `data-awaiting="determinate"` with a `data-awaiting-amount` beside it, or
1399/// `data-awaiting="indeterminate"` alone. This is the half that styles them,
1400/// without which the two render identically.
1401///
1402/// # Why it is keyed on `aria-busy` and not on the attribute alone
1403///
1404/// `data-awaiting` is a fact about the control: pressing this waits. It is true
1405/// when the page is painted and it stays true. Whether a wait is *running* is
1406/// true only between two events, so it is the binder's to set, and `aria-busy`
1407/// is the standard spelling of it — announced as well as drawn, which a class
1408/// of our own would not be.
1409///
1410/// That also keeps this crate out of any one client library's vocabulary.
1411/// `quasi-webview` sets `aria-busy` from htmx's request events; a host driving
1412/// the same markup another way sets it the same way and gets the same drawing.
1413///
1414/// # The two drawings
1415///
1416/// One pseudo-element either way, so no renderer has to emit an extra node.
1417///
1418/// Indeterminate is the activity mark of rule 2: a small square that blinks.
1419/// Determinate is a trough with a fill, drawn as a single gradient whose stop is
1420/// `--awaiting-share`, a plain number from 0 to 1 that the binder sets from
1421/// bytes it has actually watched land. A determinate control with nothing
1422/// setting the share draws an empty trough rather than a full one, which is the
1423/// honest reading: the size is known and the delivery is not.
1424///
1425/// **What the bar may not do**, from rule 1 and from `Awaiting`'s own docs:
1426/// what is done over what there is, and never a remaining time, an arrival time
1427/// or a rate extrapolated forward. Nothing here can express one, which is
1428/// deliberate — the only input is a share of a measured payload.
1429///
1430/// # Sizes, and the deferral rule
1431///
1432/// `progress_rules` emits the tones and never the width, because the width is
1433/// not this crate's to know. A pseudo-element has no intrinsic size at all, so
1434/// the same treatment would render nothing anywhere. Both sizes are therefore
1435/// custom properties with defaults: an app that wants a different mark sets
1436/// `--awaiting-mark` and `--awaiting-bar` once, and one that says nothing gets a
1437/// mark that is visible.
1438///
1439/// # The cadence, and what happens without it
1440///
1441/// `--cadence-activity` comes from `makeover-timing` through `makeover-build`,
1442/// and is a half-period, so a full cycle is twice it. It is used bare rather
1443/// than with a fallback: a number written here would be a second heartbeat for
1444/// a mark three renderers draw.
1445///
1446/// A sheet assembled without the time axis leaves `animation-duration` invalid,
1447/// which resolves to `0s`, which runs no animation and leaves the base style —
1448/// a lit, still mark. That is also exactly what the reduced-motion block does,
1449/// since it sets the cadence to `0ms`. Both fall out of one rule because the
1450/// base style is lit and the keyframes do the dimming, which is the ordering
1451/// `makeover_timing::reduced_motion_css` asks its consumers for by name.
1452fn awaiting_rules(opts: &Emit) -> String {
1453    let mut css = String::new();
1454
1455    // Dimming rather than lighting, so a zero-length animation leaves a lit
1456    // mark rather than a blank one. See `makeover_timing::reduced_motion_css`.
1457    css.push_str(
1458        "@keyframes makeover-activity {\n    \
1459         0%, 49.99% {\n        background: var(--action);\n    }\n    \
1460         50%, 100% {\n        background: var(--surface-sunken);\n    }\n\
1461         }\n",
1462    );
1463
1464    // Nothing is drawn until something is waiting. `content` on the base rule
1465    // rather than on the busy one keeps the box the same box across the
1466    // transition, so a mark appearing does not reflow the line it is in.
1467    let _ = writeln!(
1468        css,
1469        "[data-awaiting]::after {{\n    \
1470         content: \"\";\n    \
1471         display: none;\n    \
1472         margin-inline-start: var(--awaiting-gap, 0.5ch);\n    \
1473         vertical-align: baseline;\n\
1474         }}"
1475    );
1476
1477    let _ = writeln!(
1478        css,
1479        "[data-awaiting][aria-busy=\"true\"]::after {{\n    \
1480         display: inline-block;\n    \
1481         inline-size: var(--awaiting-mark, 0.5em);\n    \
1482         block-size: var(--awaiting-mark, 0.5em);\n    \
1483         background: var(--action);\n    \
1484         opacity: 1;\n    \
1485         animation: makeover-activity calc(var(--cadence-activity) * 2) \
1486         step-end infinite;\n\
1487         }}"
1488    );
1489
1490    // The measured half. A wider box, no blink, and a gradient whose stop is
1491    // the share: the fill and the trough in one paint, so the markup stays one
1492    // pseudo-element on both branches.
1493    //
1494    // `--awaiting-share` unset is an empty trough, not a full one. A bar that
1495    // read full because nobody was counting would be the confidently-wrong
1496    // drawing rule 1 exists to forbid.
1497    //
1498    // The trough takes an edge for the reason a well does: a bar at zero share
1499    // is otherwise a rectangle of the surface it sits on, which is nothing at
1500    // all. `border_width` rather than a literal, the way `depth_rule` and
1501    // `track_rules` write theirs.
1502    let _ = writeln!(
1503        css,
1504        "[data-awaiting=\"determinate\"][aria-busy=\"true\"]::after {{\n    \
1505         inline-size: var(--awaiting-bar, 6em);\n    \
1506         animation: none;\n    \
1507         outline: {} solid var(--border);\n    \
1508         outline-offset: -{};\n    \
1509         background: linear-gradient(\n        \
1510         to inline-end,\n        \
1511         var(--action) 0 calc(var(--awaiting-share, 0) * 100%),\n        \
1512         var(--surface-sunken) 0\n    \
1513         );\n\
1514         }}",
1515        opts.border_width, opts.border_width
1516    );
1517
1518    css
1519}
1520
1521/// A strip of figures, and the two spans inside each one.
1522///
1523/// Colour only, which is the deferral rule applied to a component that badly
1524/// wants to break it. A figure reads as a figure because the value is set large
1525/// over a small caption, and that is a size: `makeover-geometry` answers how
1526/// much space and this crate answers what the thing is. Emitting `font-size`
1527/// here would be this crate naming a value, which is the one thing it is defined
1528/// by not doing, and `progress_rules` is the precedent — it emits the tones and
1529/// never the width, because the width is not its to know.
1530///
1531/// So the arrangement and the type scale are the app's, and what is generated is
1532/// the part an app cannot get right by itself: which of the two spans carries
1533/// the tone.
1534fn figure_rules(opts: &Emit) -> String {
1535    let figure = class("figure", opts);
1536    let value = class("figure-value", opts);
1537    let caption = class("figure-caption", opts);
1538    let change = class("figure-change", opts);
1539    let mut css = String::new();
1540
1541    // `content` literally. A figure's value is the thing itself, at full
1542    // weight -- wiki `three-tone-convention` classes it "active, emphasised",
1543    // and both other renderers already draw it that way (makeover-tui
1544    // `piece.rs:391` bold, makeover-immediate `widget.rs:244`). It reached
1545    // here through `Tone::Neutral.token()` and came out `content-muted`, so
1546    // the headline number sat at the colour of its own caption.
1547    let _ = writeln!(
1548        css,
1549        ".{figure} > .{value} {{\n    color: var(--content);\n}}"
1550    );
1551    let _ = writeln!(
1552        css,
1553        ".{figure} > .{caption} {{\n    color: var(--content-muted);\n}}"
1554    );
1555    let _ = writeln!(
1556        css,
1557        ".{figure} > .{change} {{\n    color: var(--content-muted);\n}}"
1558    );
1559
1560    // A toned figure tones one part and never the caption. The caption is the
1561    // noun and stays muted.
1562    //
1563    // Which part depends on whether there is a change, and that is the whole of
1564    // what 0.13.0 changed here. A figure with a delta is an ordinary number that
1565    // has moved in a direction worth reading, so the delta takes the colour and
1566    // the number stays plain; a figure without one has nowhere else to put it.
1567    // `:has` is what lets one attribute mean both, and the alternative was the
1568    // emitter deciding by writing the attribute onto a different element, which
1569    // leaves two elements able to disagree about a figure's one meaning.
1570    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1571        let _ = writeln!(
1572            css,
1573            ".{figure}[data-tone=\"{0}\"] > .{change} {{\n    color: var(--{0});\n}}",
1574            tone.token()
1575        );
1576        let _ = writeln!(
1577            css,
1578            ".{figure}[data-tone=\"{0}\"]:not(:has(> .{change})) > .{value} \
1579             {{\n    color: var(--{0});\n}}",
1580            tone.token()
1581        );
1582    }
1583    css
1584}
1585
1586/// A picture, its frame and its caption.
1587///
1588/// # The frame is a border, and this is the one place a bevel is wrong
1589///
1590/// Emitting [`Depth::Raised`] here through [`depth_rule`], the same call
1591/// `button` and `card` make, is wrong, and MNW's landing page is where it
1592/// showed: **the frames had no visible edge at all.**
1593///
1594/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow — a
1595/// 1px light run at the top-left and a dark one at the bottom-right, drawn
1596/// **inside** the element's box. On a button or a card that box is a surface
1597/// this crate owns, so an inset edge reads as the surface catching the light.
1598/// On a picture it is drawn on top of the picture, over whatever pixels the
1599/// image happens to have at its border. MNW's screenshots are light-on-light
1600/// parchment, so the light half landed on a light image and the frame
1601/// disappeared.
1602///
1603/// **You cannot bevel a surface you do not own.** A picture's content is the
1604/// app's, arrives at request time, and can be any colour, so its edge has to
1605/// sit *outside* the content rather than on it. That is a border.
1606///
1607/// The fill stays, and it is not decoration: it is what shows through a
1608/// transparent PNG and what stands in the frame's place while the image is
1609/// still loading.
1610///
1611/// This is a real limit on [`Depth`] rather than a special case. Every other
1612/// consumer of a depth draws its own surface; a picture is the first member
1613/// whose surface belongs to someone else.
1614///
1615/// # No size
1616///
1617/// `width: 100%` and nothing else. How large a picture is depends on the box it
1618/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
1619/// and a renderer that picked one would be answering for every consumer at
1620/// once. This is where `figure_rules` landed for the same reason.
1621fn picture_rules(opts: &Emit) -> String {
1622    let picture = class("picture", opts);
1623    let img = class("picture-img", opts);
1624    let caption = class("picture-caption", opts);
1625    let mut css = String::new();
1626
1627    // Block, or an inline image sits on the text baseline and carries a
1628    // descender's worth of space under it that no app ever wants and every app
1629    // deletes by hand. The border is the frame; see the type docs for why it is
1630    // not the bevel every other surface here gets.
1631    let _ = writeln!(
1632        css,
1633        ".{img} {{\n    display: block;\n    width: 100%;\n    height: auto;\n    \
1634         background: var(--{});\n    border: {} solid var(--border);\n}}",
1635        Fill::Raised.token(),
1636        opts.border_width
1637    );
1638
1639    // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
1640    // so it is the bare rule above and needs nothing here.
1641    let _ = writeln!(
1642        css,
1643        ".{img}[data-fit=\"cover\"] {{\n    height: 100%;\n    object-fit: cover;\n}}"
1644    );
1645    let _ = writeln!(
1646        css,
1647        ".{img}[data-fit=\"contain\"] {{\n    height: 100%;\n    object-fit: contain;\n}}"
1648    );
1649
1650    // A caption reads back one step, which is `figure-caption`'s answer and the
1651    // same claim: it says what the thing above it is, and it is not the thing.
1652    let _ = writeln!(
1653        css,
1654        ".{picture} > .{caption} {{\n    color: var(--content-muted);\n}}"
1655    );
1656
1657    css
1658}
1659
1660/// A region showing one child at a time, and the chrome that moves between them.
1661///
1662/// [`makeover_layout::Showing`] lets a description say that a region holds
1663/// several children and shows some of them. A renderer derives its own chrome
1664/// from that, which is what stops every renderer growing a `match` on a widget
1665/// name; these are the rules the derived chrome needs.
1666///
1667/// # Why the default is every child, and the enhancement takes them away
1668///
1669/// The controls are a lie until something binds them. A prev button rendered
1670/// into a document with no script is a control that looks live and answers
1671/// nothing, and the reader it lies to is exactly the one who cannot see the
1672/// other children either — the collapsing and the moving are the same half.
1673///
1674/// So the rules run in the direction the enhancement does. Nothing here hides a
1675/// child and nothing here shows a control. Whatever binds the region sets
1676/// `data-ready` on it, and that is what collapses the stack to one and reveals
1677/// the row that moves it. A reader with no script gets every child in order and
1678/// no controls, which is more content rather than less, and a reader with
1679/// script gets a settled page rather than a stack that jumps to one frame after
1680/// load.
1681///
1682/// MNW proved this shape by hand — a `<noscript>` stylesheet opening its
1683/// carousel back out — and it is here rather than there because the property is
1684/// the description's, not one app's.
1685///
1686/// # Not spacing
1687///
1688/// The row's gaps are `makeover-geometry`'s question and are absent for
1689/// [`row_rules`]'s reason. What is here is `display`, which carries no
1690/// magnitude, and the muted readout, which is the same claim `picture-caption`
1691/// makes: it says where you are among the children and it is not one of them.
1692fn showing_rules(opts: &Emit) -> String {
1693    let controls = class("showing", opts);
1694    let position = class("showing-position", opts);
1695    let frame = class("showing-frame", opts);
1696    let mut css = String::new();
1697
1698    // Hidden until something binds it, which is the whole argument above.
1699    let _ = writeln!(css, ".{controls} {{\n    display: none;\n}}");
1700    // Block, and nothing about how the three sit in it. A button and a span are
1701    // inline already, so they make a row without this crate saying so, and
1702    // saying so is where `align-items` and a gap would follow -- both spacing,
1703    // both `makeover-geometry`'s, and `row_rules` refuses them for the same
1704    // reason.
1705    let _ = writeln!(
1706        css,
1707        "[data-ready] > .{controls} {{\n    display: block;\n}}"
1708    );
1709
1710    // A child is in flow until the region is bound, and then only the current
1711    // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
1712    // are: one name for the state, set by whoever knows it.
1713    let _ = writeln!(
1714        css,
1715        "[data-ready] > .{frame}:not(.current) {{\n    display: none;\n}}"
1716    );
1717
1718    // Reads back one step. `picture-caption`'s rule and its reason.
1719    let _ = writeln!(css, ".{position} {{\n    color: var(--content-muted);\n}}");
1720
1721    css
1722}
1723
1724/// A time axis: the container, its gridlines and ruler, and the placed things.
1725///
1726/// [`Track`](makeover_layout::Track), the one member here whose whole point is
1727/// *position*. That makes the magnitude line this crate keeps worth restating
1728/// rather than assuming.
1729///
1730/// # Where the numbers come from
1731///
1732/// Every value that varies per item is a custom property the caller sets
1733/// inline, and every rule here reads one. `--track-at` and `--track-for` are
1734/// percentages of the span, which
1735/// [`Track::fraction`](makeover_layout::Track::fraction) computes once so three
1736/// renderers cannot disagree about it. Nothing here knows a pixel.
1737///
1738/// That is what lets the stylesheet stay static while the items move: an entry
1739/// carries `style="--track-at: 37.5%; --track-for: 4.166%"` and the rule below
1740/// turns it into a box. The alternative was emitting a rule per item, which is
1741/// a stylesheet that grows with the data.
1742///
1743/// **The height of the track is the app's**, not this crate's. 96 quarter-hour
1744/// slots at some slot height is a size, and a size is `makeover-geometry`'s
1745/// question -- the same refusal `figure_rules` and `placeholder_rules` make.
1746/// Percentages need a resolved height above them, so `.track` gets
1747/// `position: relative` and nothing else; the app says how tall a day is.
1748///
1749/// # Overlap
1750///
1751/// Two things at the same time is intrinsic to an axis and has no analogue in a
1752/// list. The description does not declare it -- `Placement::overlaps` derives it
1753/// from the times -- so what arrives here is a lane index and a lane count, and
1754/// the rule divides the width. A renderer that would rather stack them ignores
1755/// both properties and the defaults give it one full-width lane.
1756fn track_rules(opts: &Emit) -> String {
1757    let track = class("track", opts);
1758    let slot = class("track-slot", opts);
1759    let tick = class("track-tick", opts);
1760    let entry = class("track-entry", opts);
1761    let mut css = String::new();
1762
1763    // The positioning context every entry resolves against, and the whole of
1764    // what this crate says about the container. No height: see the doc above.
1765    let _ = writeln!(css, ".{track} {{\n    position: relative;\n}}");
1766
1767    // Gridlines and the ruler are the axis reading itself back, which is
1768    // `picture-caption` and `showing-position`'s claim: about the thing rather
1769    // than one of the things.
1770    //
1771    // `border_width` rather than a literal, the way `depth_rule` writes its
1772    // edge. A gridline is the one place a timeline would most naturally reach
1773    // for a hardcoded 1px, and a hardcoded 1px is this crate naming a size.
1774    let _ = writeln!(
1775        css,
1776        ".{slot} {{\n    border-top: {} solid var(--border);\n}}",
1777        opts.border_width
1778    );
1779    let _ = writeln!(css, ".{tick} {{\n    color: var(--content-muted);\n}}");
1780
1781    // The one rule that does real work. Top and height are the placement;
1782    // left and width are the lane. Both lane properties default so an entry
1783    // that names neither is full width, which is the common case and the one a
1784    // renderer gets for free.
1785    let _ = writeln!(
1786        css,
1787        ".{entry} {{\n    \
1788         position: absolute;\n    \
1789         top: var(--track-at, 0%);\n    \
1790         height: var(--track-for, 100%);\n    \
1791         left: calc(var(--track-lane, 0) / var(--track-lanes, 1) * 100%);\n    \
1792         width: calc(100% / var(--track-lanes, 1));\n\
1793         }}"
1794    );
1795
1796    css
1797}
1798
1799/// A region's stand-in, and the header of a table that can be reordered.
1800///
1801/// Both are colour and affordance only, the same place `figure_rules` lands:
1802/// emitting a type scale is not this crate's. How much room
1803/// a stand-in gets is a size — goingson has the same one at three, as
1804/// `--compact`, `--dashboard` and `--padded` — and a size is
1805/// `makeover-geometry`'s question.
1806///
1807/// The caret is the one thing here that is neither colour nor affordance, and it
1808/// is a renderer's own expression rather than a value the description named:
1809/// `aria-sort` is what the table actually says, and this turns it into something
1810/// visible for everyone not using a screen reader. A terminal draws its own; an
1811/// immediate-mode painter draws its own.
1812fn state_rules(opts: &Emit) -> String {
1813    let placeholder = class("placeholder", opts);
1814    let text = class("placeholder-text", opts);
1815    let heading = class("table-heading", opts);
1816    let mut css = String::new();
1817
1818    let _ = writeln!(
1819        css,
1820        ".{placeholder} > .{text} {{\n    color: var(--content-muted);\n}}"
1821    );
1822    // Only the failure is toned. An empty list is the normal state of a new
1823    // install, and `Readiness::tone` is what says so.
1824    let _ = writeln!(
1825        css,
1826        ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n    color: var(--{0});\n}}",
1827        Tone::Danger.token()
1828    );
1829
1830    // A header that reorders the table is a control, and the pointer is the
1831    // only part of saying so that is not the app's own type and spacing.
1832    let _ = writeln!(
1833        css,
1834        ".{heading}[data-sortable] {{\n    cursor: pointer;\n}}"
1835    );
1836    // The caret carries its own leading space, the way `makeover-tui` and
1837    // `makeover-immediate` both write `" \u{25B2}"`. It used to be emitted bare,
1838    // and both apps that adopted the vocabulary had to put the gap back in their
1839    // own stylesheets on the same afternoon -- each having to work out first that
1840    // app CSS outranks this crate's cascade layer, so adding the space the
1841    // obvious way, as `content`, silently wins over the glyph and leaves the
1842    // heading with no caret at all. A consumer should not have to know that, and
1843    // with the space emitted here there is nothing left for one to add.
1844    //
1845    // Three states, three tones, on the convention in wiki
1846    // `three-tone-convention`. A column in force is `content`; a column offering
1847    // to reorder and not doing it now is `content-secondary`, because it still
1848    // answers a press; a column that is not sortable emits no caret at all and
1849    // takes nothing. The idle arm used to hide its glyph and reserve the box,
1850    // which cost a reflow-free press and said nothing. It draws now, and the
1851    // reservation stops being a thing to get right.
1852    //
1853    // The glyph is `Sort::glyph`, escaped rather than written: a CSS `content`
1854    // string cannot carry the character literally through this file's own
1855    // escaping, and spelling it here as well would put the third copy back that
1856    // `makeover-layout` 0.27.5 exists to remove.
1857    let _ = writeln!(
1858        css,
1859        ".{heading}[data-sortable]::after \
1860         {{\n    content: \" {}\";\n    color: var(--content-secondary);\n}}",
1861        css_escape(Sort::Ascending.glyph())
1862    );
1863    for direction in [Sort::Ascending, Sort::Descending] {
1864        let _ = writeln!(
1865            css,
1866            ".{heading}[aria-sort=\"{}\"]::after \
1867             {{\n    content: \" {}\";\n    color: var(--content);\n}}",
1868            direction.as_str(),
1869            css_escape(direction.glyph())
1870        );
1871    }
1872    css
1873}
1874
1875/// The frame a table sits in.
1876///
1877/// # Why this is a CSS table and not the grid the rest of the module assumes
1878///
1879/// A grid row needs `grid-template-columns`, which has to name every column in
1880/// order, so it cannot be written without knowing the columns. That is what
1881/// [`list::narrowing_css`] is for, and it works: goingson builds `tables.css` in
1882/// its own `build.rs` out of it, and nothing here changes that.
1883///
1884/// It does not work for a table a *description* produced. Those columns are
1885/// known at render time rather than at build time, and the rules would have to
1886/// travel with the markup: a `<style>` element per table, which needs
1887/// `style-src 'unsafe-inline'` and so blocks the MNW server's standing plan to
1888/// drop it. The head is not an escape: a table swapped in by htmx after a
1889/// delete arrives as a fragment with no head at all.
1890///
1891/// A CSS table aligns its columns across rows knowing nothing about how many
1892/// there are, so there is no track list to emit and nothing per-table to carry.
1893/// The cost is that a described table cannot take a per-column fixed length,
1894/// which costs nothing today: [`Sizing`](list::Sizing) is looked up by column
1895/// name and a description carries no lengths to put in it, so every track a
1896/// described table could ask for is already content, fill or auto.
1897///
1898/// [`Priority`] hiding is unchanged in kind. It moves from a generated
1899/// `display: none` per dropped column to one rule per drop class, which is the
1900/// same fact addressed by class rather than by cutoff, and still never by
1901/// position.
1902fn table_rules(opts: &Emit) -> String {
1903    let table = class("table", opts);
1904    let head = class("table-head", opts);
1905    let row = class("table-row", opts);
1906    let heading = class("table-heading", opts);
1907    let cell = class("cell", opts);
1908    let mut css = String::new();
1909
1910    // The table model, wiki `table-model`: specimen C with D's header strip, as
1911    // Max picked it off rendered specimens. The table paints its own raised
1912    // ground inside a hairline frame, so the row tones hold whatever it sits
1913    // on. Text is the note size, 14px at the default base.
1914    let bw = opts.border_width;
1915    let _ = writeln!(
1916        css,
1917        ".{table} {{\n    display: table;\n    width: 100%;\n    \
1918         border-collapse: collapse;\n    border: {bw} solid var(--row-rule);\n    \
1919         background: var(--surface-raised);\n    font-size: var(--text-note);\n}}"
1920    );
1921    let _ = writeln!(css, ".{head},\n.{row} {{\n    display: table-row;\n}}");
1922    // A minimum rather than a height, since a table row grows to fit its
1923    // tallest cell: a cell holding more than a line grows the row.
1924    let _ = writeln!(css, ".{table} .{row} {{\n    height: var(--row-block);\n}}");
1925
1926    // The header strip. Its ink goes on the heading row and is inherited,
1927    // because `state_rules` colours the sort caret on `.table-heading::after`
1928    // and a colour on the heading itself would override it. `content-secondary`
1929    // rather than muted: the strip separates the header now, so the label does
1930    // not have to stay quiet by being pale. The edge sits under the strip, as
1931    // in the specimen. Tracking is typography's to own and nothing in the
1932    // family owns it yet, so it is a property with the specimen's value behind it.
1933    let _ = writeln!(
1934        css,
1935        ".{table} .{head} {{\n    color: var(--content-secondary);\n}}"
1936    );
1937    let _ = writeln!(
1938        css,
1939        ".{table} .{heading} {{\n    background: var(--surface-sunken);\n    \
1940         border-bottom: {bw} solid var(--bevel-dark);\n    font-size: var(--text-fine);\n    \
1941         font-weight: bold;\n    letter-spacing: var(--table-heading-tracking, 0.06em);\n    \
1942         text-transform: uppercase;\n    text-align: start;\n    vertical-align: bottom;\n    \
1943         white-space: nowrap;\n    padding: var(--gap-peer) var(--gap-group);\n}}"
1944    );
1945
1946    // Rows: a hairline between rows, a stripe on alternate rows, and a hover,
1947    // at every row count. Between rows and not above the first, where the
1948    // header's edge already draws the line.
1949    let _ = writeln!(
1950        css,
1951        ".{table} .{row} > .{cell} {{\n    padding: var(--gap-bound) var(--gap-group);\n    \
1952         vertical-align: middle;\n}}"
1953    );
1954    let _ = writeln!(
1955        css,
1956        ".{table} .{row} + .{row} > .{cell} {{\n    border-top: {bw} solid var(--row-rule);\n}}"
1957    );
1958    // Parity of rows, never position of columns: the stripe alternates by what
1959    // a row is, and `of .{row}` keeps a header row out of the count.
1960    let _ = writeln!(
1961        css,
1962        ".{table} .{row}:nth-child(even of .{row}) {{\n    background: var(--row-stripe);\n}}"
1963    );
1964    let _ = writeln!(
1965        css,
1966        "@media (hover: hover) and (pointer: fine) {{\n    \
1967         .{table} .{row}:hover {{\n        background: var(--row-hover);\n    }}\n}}"
1968    );
1969
1970    let [
1971        kind_identifier,
1972        kind_date,
1973        kind_number,
1974        kind_status,
1975        kind_actions,
1976        kind_code,
1977    ] = [
1978        "kind-identifier",
1979        "kind-date",
1980        "kind-number",
1981        "kind-status",
1982        "kind-actions",
1983        "kind-code",
1984    ]
1985    .map(|name| class(name, opts));
1986    // Column kinds, wiki `table-model`. The class is on the heading and on
1987    // every cell. A heading takes the column's alignment and nowrap, so it lines
1988    // up with what is under it, and keeps the header's own type: the face and
1989    // figures a kind sets go on its cells. Prose has no class and no rule.
1990    let _ = writeln!(
1991        css,
1992        ".{table} .{cell}.{kind_identifier} {{\n    font-family: var(--font-mono);\n    \
1993         font-size: var(--text-fine);\n    overflow-wrap: anywhere;\n}}"
1994    );
1995    let _ = writeln!(
1996        css,
1997        ".{table} .{kind_date} {{\n    white-space: nowrap;\n}}\n\
1998         .{table} .{cell}.{kind_date} {{\n    font-variant-numeric: tabular-nums;\n}}"
1999    );
2000    let _ = writeln!(
2001        css,
2002        ".{table} .{kind_number} {{\n    white-space: nowrap;\n    text-align: end;\n}}\n\
2003         .{table} .{cell}.{kind_number} {{\n    font-variant-numeric: tabular-nums;\n}}"
2004    );
2005    let _ = writeln!(
2006        css,
2007        ".{table} .{kind_status} {{\n    white-space: nowrap;\n}}"
2008    );
2009    let _ = writeln!(
2010        css,
2011        ".{table} .{kind_actions} {{\n    white-space: nowrap;\n    width: 1%;\n    \
2012         text-align: end;\n}}"
2013    );
2014    let _ = writeln!(
2015        css,
2016        ".{table} .{cell}.{kind_code} {{\n    font-family: var(--font-mono);\n    white-space: pre;\n}}"
2017    );
2018    // A table holding code is read as code: one row per source line, where a
2019    // stripe, a padded block and a 45px row each break the reading. So it
2020    // keeps the frame and the header and drops the record treatment. Keyed on
2021    // the kind being present, which the table's own markup already says.
2022    let code = format!(".{table}:has(.{kind_code})");
2023    let _ = writeln!(
2024        css,
2025        "{code} .{row} {{\n    height: auto;\n}}\n\
2026         {code} .{row} > .{cell} {{\n    padding-block: 0;\n    border-top: 0;\n    \
2027         vertical-align: baseline;\n}}\n\
2028         {code} .{row}:nth-child(even of .{row}) {{\n    background: none;\n}}"
2029    );
2030    let _ = writeln!(
2031        css,
2032        "@media (hover: hover) and (pointer: fine) {{\n    \
2033         {code} .{row}:hover {{\n        background: none;\n    }}\n}}"
2034    );
2035    // Scoped under `.{table}` rather than keyed on the classes alone. The
2036    // table model is what a cell takes *by being in a table*, and only there:
2037    // goingson's task headings are `.table-heading` inside a CSS grid, so the
2038    // unscoped rule reached them, and the sort caret and the sortable cursor
2039    // -- which `state_rules` keys on `.table-heading` and rightly still does
2040    // -- came with a `display` the grid had to blockify away.
2041    //
2042    // It costs no markup anywhere: quasi-webview always nests the heading
2043    // inside the table (`quasi-webview/src/node.rs:1591`, `:1605`, `:1615`).
2044    let _ = writeln!(
2045        css,
2046        ".{table} .{heading},\n.{table} .{cell} {{\n    display: table-cell;\n}}"
2047    );
2048
2049    // A content column shrinks to what is in it. `width: 1%` is how a CSS table
2050    // is told that: auto layout hands the slack to the columns that asked for
2051    // room, and a column asking for almost none gets what it needs and no more.
2052    // The `nowrap` is what stops it being given less by wrapping.
2053    let _ = writeln!(
2054        css,
2055        ".{} {{\n    white-space: nowrap;\n    width: 1%;\n}}",
2056        class("cell-content", opts)
2057    );
2058
2059    // A fixed column has no length to be fixed to. The description carries none
2060    // and `Sizing` is not reachable from here, so it behaves as content: the
2061    // honest answer to a width nobody supplied, and the same one `Sizing::track`
2062    // gives it.
2063    let _ = writeln!(
2064        css,
2065        ".{} {{\n    white-space: nowrap;\n}}",
2066        class("cell-fixed", opts)
2067    );
2068
2069    // Optional columns go at the narrowest class, secondary ones go with them,
2070    // which is the cutoff walk `kept_at` describes said as two media queries.
2071    // Essential columns have no rule at all, because never dropping is what not
2072    // being mentioned already means.
2073    //
2074    // Scoped under `.{table}` for the same reason the cell's `display` is, and
2075    // because of it: `.table .cell` sits at (0,2,0), so a bare `.cell-drops-*`
2076    // at (0,1,0) lost to it in every table and no column ever dropped. At equal
2077    // specificity the drop comes later in the sheet and wins.
2078    for (size, drops) in [
2079        (
2080            SizeClass::Compact,
2081            &["cell-drops-first", "cell-drops-next"][..],
2082        ),
2083        (SizeClass::Medium, &["cell-drops-first"][..]),
2084    ] {
2085        let selectors: Vec<String> = drops
2086            .iter()
2087            .map(|drop| format!(".{table} .{}", class(drop, opts)))
2088            .collect();
2089        css.push_str(&gated(
2090            Some(&size.media_condition()),
2091            &format!("{} {{\n    display: none;\n}}\n", selectors.join(",\n")),
2092        ));
2093    }
2094
2095    // What is inside a cell, which the table side could not say until
2096    // makeover-layout 0.14.0. Every cell was one `.cell` and one content
2097    // colour, so a button in a cell was painted as text -- the drift
2098    // `RowPart::intent` has prevented for list rows since 0.2.0 and prevented
2099    // for nothing here.
2100    //
2101    // The colour goes on `.cell-value` rather than on `.cell`, and that
2102    // placement is the whole fix. On the container it would cascade into the
2103    // tokens and the controls sitting beside the text, which is the bug said
2104    // in one rule; on the part that is text, it reaches text and stops.
2105    for part in [
2106        CellPart::Value,
2107        CellPart::Tokens,
2108        CellPart::Actions,
2109        CellPart::Link,
2110    ] {
2111        // Two of the four inherit: a token carries its own tone and an action
2112        // is a control rather than text. A link is text, the title of its row,
2113        // so it takes its intent like a value does. Left to inherit, it took
2114        // nothing: the colour is on `.cell-value` rather than on `.cell`, and an
2115        // anchor with no colour of its own draws in the browser's link blue.
2116        //
2117        // Written as a skip-list rather than as a match on Value, so a member
2118        // added upstream gets its intent emitted rather than being silently
2119        // dropped. That is the same trade `part_class`'s fallback makes: land
2120        // plainly, never land as nothing.
2121        if !matches!(part, CellPart::Tokens | CellPart::Actions) {
2122            // The underline says "this goes somewhere" in running text. In a
2123            // table the row already says it, by being the thing that activates.
2124            let underline = if part == CellPart::Link {
2125                "\n    text-decoration: none;"
2126            } else {
2127                ""
2128            };
2129            let _ = writeln!(
2130                css,
2131                ".{} {{\n    color: var(--{});{underline}\n}}",
2132                class(cell_part_class(part), opts),
2133                part.intent()
2134            );
2135        }
2136    }
2137
2138    css
2139}
2140
2141/// The component layer: every named thing phase A emits.
2142///
2143/// No scrollbar track. It was on the phase A list and came off: eight lines of
2144/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
2145/// would want handed to it, so it stays with the apps.
2146#[must_use]
2147pub fn component_rules(opts: &Emit) -> String {
2148    let mut css = String::new();
2149    css.push_str(&surface_rules(opts));
2150    css.push_str(&link_rules(opts));
2151    css.push_str(&token_rules(opts));
2152    css.push_str(&selector_rules(opts));
2153    css.push_str(&row_rules(opts));
2154    css.push_str(&run_rules(opts));
2155    css.push_str(&progress_rules(opts));
2156    css.push_str(&chart::rules(opts));
2157    css.push_str(&awaiting_rules(opts));
2158    css.push_str(&figure_rules(opts));
2159    css.push_str(&picture_rules(opts));
2160    css.push_str(&showing_rules(opts));
2161    css.push_str(&track_rules(opts));
2162    css.push_str(&state_rules(opts));
2163    css.push_str(&table_rules(opts));
2164    css.push_str(&facet::facet_rules(opts));
2165    css.push_str(&form::editor_rules(opts));
2166    css.push_str(&form::suggestion_rules(opts));
2167    css.push_str(&form::unit_rules(opts));
2168    css.push_str(&form::option_detail_rules(opts));
2169    css.push_str(&form::note_rules(opts));
2170    css.push_str(&leaving_rules());
2171    css
2172}
2173
2174/// How a transient notice goes away.
2175///
2176/// `makeover-timing` says that `Intent::Dismiss` is how long a notice lives
2177/// *before it starts to leave*, and that the leaving itself is `Motion::Fade`.
2178/// `makeover-build` writes `--motion-fade` into every consumer's `timing.css`,
2179/// and this is the rule that reads it. Removing the node the moment the dismiss
2180/// is up skips the leaving entirely.
2181///
2182/// # Why an attribute and not a class
2183///
2184/// [`Emit`]'s prefix moves every class this crate writes, so a class here would
2185/// have to be resolved through `class()` by whoever sets it -- and the party
2186/// setting it is a script, which has no prefix to hand. `data-leaving` is
2187/// outside that namespace, so a renderer can set it from JavaScript with no
2188/// coordination.
2189///
2190/// The transition sits on the notice and the opacity on the leaving state, so
2191/// the element is transitionable before the attribute arrives; a transition
2192/// declared in the same rule as the value it changes has nothing to animate
2193/// from.
2194///
2195/// # Reduced motion is handled by the token, not by a second rule here
2196///
2197/// `timing.css` already zeroes `--motion-fade` under `prefers-reduced-motion`.
2198/// The reader who asked for less motion gets an instant change rather than a
2199/// fade, and the renderer that sets the attribute must still remove the node on
2200/// a timer rather than on `transitionend` -- a zero-length transition may fire
2201/// no event at all, and a node waiting on one that never comes stays forever.
2202///
2203/// The fallback is `0ms` and not a guessed duration: a page with no timing
2204/// sheet has not opted into this vocabulary, and the honest answer there is the
2205/// behaviour it had before, which is the notice going away at once.
2206fn leaving_rules() -> String {
2207    let mut css = String::new();
2208    let _ = writeln!(
2209        css,
2210        "[data-notice] {{\n    transition: opacity var(--motion-fade, 0ms) \
2211         ease-out;\n}}"
2212    );
2213    let _ = writeln!(css, "[data-notice][data-leaving] {{\n    opacity: 0;\n}}");
2214    css
2215}
2216
2217/// The whole phase-A stylesheet: properties, depth rules and components, in
2218/// [`CSS_LAYER`], under a generated-file banner.
2219///
2220/// The banner sits outside the layer, because a comment participates in no
2221/// cascade and a reader opening the file should see what it is before seeing
2222/// an at-rule.
2223#[must_use]
2224pub fn stylesheet(opts: &Emit) -> String {
2225    let body = in_css_layer(&format!(
2226        ":root {{\n{}}}\n\n{}\n{}",
2227        bevel_properties(opts),
2228        depth_rules(opts),
2229        component_rules(opts)
2230    ));
2231    // Counted from the body rather than through `vocabulary::names`, which
2232    // calls back into here.
2233    let classes = vocabulary::classes_in_css(&body).len();
2234    let version = VERSION;
2235    format!(
2236        "/* Generated by makeover-webview {version} from makeover-layout, \
2237         {classes} classes.\n   \
2238         Do not edit. The version and the count are here because a stale\n   \
2239         lockfile fails silently: an older emitter writes a well-formed sheet\n   \
2240         with components missing, and nothing else in the file says so. If\n   \
2241         this version trails what the manifest asks for, re-resolve.\n\n   \
2242         Depth is a fill and an edge together; naming them apart is what let\n   \
2243         them disagree. See the crate's README and wiki note makeover-layout.\n\n   \
2244         Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n   \
2245         order once in your own stylesheet, or this layer's position is decided\n   \
2246         by whichever generated file the browser happens to see first:\n\n   \
2247         @layer {CSS_LAYER}, base, components, responsive; */\n{body}"
2248    )
2249}
2250
2251#[cfg(test)]
2252mod tests;