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