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