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