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