Skip to main content

makeover_webview/
lib.rs

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