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//! # Phase B: the markup, one description at a time
36//!
37//! [`form`] renders [`makeover_layout::Field`], which is the half of phase B
38//! whose description is settled. It emits strings, because both apps
39//! interpolate their fields into larger string-built forms and returning nodes
40//! would rewrite those too. It owns its own escaping, on the reasoning in that
41//! module: a Rust encoder can cover element text and attribute values with one
42//! function, where the apps need four and have to choose correctly at every
43//! call site.
44//!
45//! [`list`] is the other half: column tracks, the narrowing rules, and the cell
46//! containers a row is made of. It stops at the cell boundary and does not
47//! render what goes inside one, on the reasoning in that module. So phase B is
48//! now the frame around content in both directions, and what an app still owns
49//! is the content itself.
50//!
51//! # What phase A settled, and what it costs
52//!
53//! Decided 2026-07-29 against goingson's `styles.css` rather than against a
54//! component list. The useful finding there was that `.btn` (line 644),
55//! `.card` (768) and `.tag, .badge` (882) each hand-write the same
56//! composition, so three quarters of phase A is one rule with several names.
57//!
58//! Two of the four decisions change how goingson looks, and adoption should
59//! not be described as a pure deletion:
60//!
61//! - **Pressed carries its fill.** [`interactive_rules`] emits
62//!   [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
63//!   will press to `--surface-well`, and hovers to `--surface-overlay` today
64//!   and will hover to `--hover-surface`. Since `surface-well` inverts by theme
65//!   where `surface-sunken` does not, a dark theme presses *lighter* than it
66//!   hovers. That falls out of `makeover`'s own derivation, which says outright
67//!   that `surface-sunken` cannot serve as a well, so if it reads wrong the
68//!   answer is there and not here.
69//! - **Badges go flat.** See [`token_rules`].
70//!
71//! The other two: the progress trough is renderer-local and the scrollbar
72//! track was dropped ([`component_rules`]), and no class prefix ships by
73//! default, so adoption means deleting the app's hand-written rule in the same
74//! commit that adds the generated one. `.card`, `.badge` and the tab classes
75//! all already exist in goingson, and while both rules exist the cascade order
76//! decides which wins. That is the one real risk in adopting this, and it is
77//! why the migration lands per component rather than in one commit.
78//!
79//! # 0.10.0: the states this crate used to leave to its consumers
80//!
81//! [`interactive_rules`] emitted hover and pressed and stopped, because
82//! `makeover-layout` modelled no interaction state. Focus and disabled were
83//! therefore unsayable, and every app completed the primitive from outside the
84//! only way that works: by out-specifying a rule it does not own. goingson
85//! carries 19 such rules and the MNW server 21, and the three focus rings do
86//! not match each other.
87//!
88//! That also blocked the cascade-layer work outright. An app that declares
89//! `@layer` puts its own rules in a named layer, and unlayered declarations
90//! outrank every named layer regardless of specificity, so all of those
91//! overrides lose in the commit that adopts layers. They cannot simply be
92//! deleted, because they are the only thing supplying the missing states.
93//! Emitting the states here is what turns that adoption into a deletion.
94//!
95//! Four states now, in emission order, and the order is load-bearing: they are
96//! all specificity (0,2,0), so disabled beats hover by coming last and by
97//! nothing else. Nothing here reaches for `:not(:disabled)`, which would raise
98//! a selector this crate will shortly be wrapping in its own layer.
99//!
100//! Hover additionally sits inside a capability query now. `makeover-touch`
101//! answers whether a fingertip has hover and `makeover-geometry` spells the
102//! condition; this crate asks and does not decide. goingson's section 60 exists
103//! solely to take the hover state back on touch, which is a fight it should
104//! never have been handed.
105//!
106//! # 0.11.0: the layer contract
107//!
108//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
109//! lives in `makeover-geometry` because that is the one crate every CSS emitter
110//! in the family already depends on). `makeover-geometry` 0.6.0 does the same
111//! for `geometry.css`.
112//!
113//! The cascade resolves origin and importance, then layer, then specificity,
114//! then source order, and **unlayered normal declarations outrank every named
115//! layer**. So before this, an app that declared `@layer base, components,
116//! responsive` put every rule it owns into a named layer and lost all of them to
117//! this unlayered file, regardless of specificity and regardless of loading
118//! last. Nothing errors when that happens: the CSS is valid, the minifier is
119//! happy, and buttons and badges look subtly wrong.
120//!
121//! That is why the layer belongs here rather than in each app. An app cannot fix
122//! it from its own stylesheet, because the fix is to layer the file it does not
123//! own.
124//!
125//! **What it flips**, and the reason each app wants a look when it bumps the
126//! pin: a generated rule that currently beats an app rule by being more specific
127//! stops beating it. The direction is always "the app wins", which is what the
128//! apps already assume, but a hand-written rule an app thought was dead can come
129//! back to life.
130//!
131//! An app should declare the order once, or the layer's position is decided by
132//! whichever generated file the browser happens to see first:
133//!
134//! ```css
135//! @layer makeover, base, components, responsive;
136//! ```
137//!
138//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
139//! from this crate's pieces. goingson builds `tables.css` in its own `build.rs`
140//! out of [`list::narrowing_css`] and [`list::grid_template_columns`], and those
141//! rules are as generated as the ones here, so they belong in the same layer and
142//! this crate cannot put them there on the app's behalf.
143//!
144//! # 0.12.0: the ring gets its own width
145//!
146//! [`focus_rule`] reused [`Emit::border_width`] and emitted a 1px ring. That was
147//! an implementation convenience dressed as consistency with the invalid-field
148//! ring: a bevel and a focus indicator answer different questions, and only one
149//! of them has to be noticed from across a desk.
150//!
151//! Caught while adopting 0.11.0 into goingson, by the check the adoption tasks
152//! ask for. Every consumer had already written its own ring and all three chose
153//! at least 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
154//! goingson 2px on three rules and 3px on the one covering twelve selectors. The
155//! design system was the only thing in the tree saying 1px, so deleting the app
156//! rules in favour of it would have thinned the focus indicator everywhere.
157//!
158//! [`Emit::focus_width`] now carries it, defaulting to `2px`, and the offset is
159//! the same magnitude with its sign off the depth. Both values are the measured
160//! consensus rather than a new opinion.
161//!
162//! # 0.17.0: the depth classes stop being controls
163//!
164//! [`depth_rules`] gave `.raised` the whole interactive set. A depth is a
165//! statement about shape, so that left the vocabulary with no raised surface
166//! that is merely an object, and an app wanting one had two moves: write its
167//! own class from tokens, or take a control class and cancel the control half.
168//! goingson took the second, in three variants over sixteen elements
169//! (`.card--static` at 14 call sites, `.card--muted` at 2, `.card--shell` at 1),
170//! each re-asserting the resting fill and bevel on `:hover` and `:active`.
171//!
172//! Measured before changing it: `.raised` is emitted into goingson, Balanced
173//! Breakfast and the MNW server, and none of the three has a single call site.
174//! The states were unasked-for everywhere at once, and dropping them costs no
175//! migration anywhere.
176//!
177//! `.card` and `.button` are unchanged. They are the same depth *and* controls,
178//! and they take their states from [`surface_rules`], which is where a state
179//! belongs: on the thing that claims to answer a pointer.
180//!
181//! # Substitution, three ways
182//!
183//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
184//! answers that differently, which is the evidence that dropping
185//! `Fill::fallback` from the description was right:
186//!
187//! - `makeover-immediate` substitutes the page in Rust.
188//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
189//!   terminal would quantise the two together.
190//! - here, CSS already has the mechanism: `var(--surface-well,
191//!   var(--surface-page))` falls back in the browser, and nothing in Rust
192//!   decides anything.
193
194#![forbid(unsafe_code)]
195
196pub mod figure;
197pub mod form;
198pub mod list;
199pub mod meter;
200pub mod placeholder;
201
202use crate::list::part_class;
203use makeover_geometry::{Density, SizeClass};
204// Re-exported rather than redefined. An app assembling its own stylesheet out
205// of this crate's pieces needs the same layer name, and most such apps depend
206// on this crate and not on `makeover-geometry` directly: goingson builds
207// `tables.css` in its own build.rs from [`list::narrowing_css`], and those
208// rules are as generated as the ones here.
209pub use makeover_geometry::{CSS_LAYER, in_css_layer};
210use makeover_layout::{Bevel, Depth, Fill, Intent, RowPart, Selector, State, Token, Tone};
211use makeover_touch::Affordance;
212use std::fmt::Write as _;
213
214/// How the emitted CSS is shaped.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct Emit {
217    /// Bevel thickness, as a CSS length.
218    ///
219    /// A value, so it arrives from the caller: border widths belong to
220    /// `makeover-geometry` and will come from there once it carries them.
221    pub border_width: &'static str,
222    /// Focus ring thickness, as a CSS length.
223    ///
224    /// Separate from [`border_width`](Self::border_width), which it reused
225    /// until 0.12.0. That reuse was an implementation convenience dressed as
226    /// consistency, and it emitted a 1px ring: a bevel and a focus indicator
227    /// are answering different questions, and only one of them has to be
228    /// noticed from across a desk.
229    ///
230    /// The default is the measured consensus rather than a new opinion. Every
231    /// consumer had already written its own ring and all three chose at least
232    /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
233    /// goingson 2px on three rules and 3px on the one covering twelve
234    /// selectors. The design system was the only thing in the tree saying 1px.
235    pub focus_width: &'static str,
236    /// Prefix for emitted class names, without the leading dot.
237    pub class_prefix: &'static str,
238}
239
240impl Default for Emit {
241    fn default() -> Self {
242        Self {
243            border_width: "1px",
244            focus_width: "2px",
245            class_prefix: "",
246        }
247    }
248}
249
250/// The CSS custom property holding a bevel's composition.
251#[must_use]
252pub fn bevel_var(bevel: Bevel) -> &'static str {
253    match bevel {
254        Bevel::Raised => "--bevel-raised",
255        Bevel::Inset => "--bevel-inset",
256    }
257}
258
259/// A `var()` reference to a fill intent, with the browser's own fallback where
260/// the intent may be absent.
261///
262/// The fallback is CSS syntax, not a decision made here. That is the whole
263/// difference between this renderer and the other two.
264#[must_use]
265pub fn fill_var(fill: Fill) -> String {
266    match fill {
267        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
268        other => format!("var(--{})", other.token()),
269    }
270}
271
272/// The two-tone edge as a `box-shadow` value.
273///
274/// Two inset shadows, one per corner pair: the light one offset down and
275/// right so it lands on the top and left edges, the dark one the other way.
276/// The same assignment `makeover-immediate` draws with polylines and
277/// `makeover-tui` draws with box-drawing characters.
278#[must_use]
279pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
280    let (top_left, bottom_right) = bevel.edges();
281    let w = opts.border_width;
282    format!(
283        "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
284        top_left.token(),
285        bottom_right.token()
286    )
287}
288
289/// The custom properties both bevels resolve through.
290///
291/// Emitted as properties rather than inlined into every rule because that is
292/// what the apps already do, and because a consumer that wants the edge
293/// without the fill reads the property directly.
294#[must_use]
295pub fn bevel_properties(opts: &Emit) -> String {
296    let mut css = String::new();
297    for bevel in [Bevel::Raised, Bevel::Inset] {
298        let _ = writeln!(
299            css,
300            "    {}: {};",
301            bevel_var(bevel),
302            bevel_shadow(bevel, opts)
303        );
304    }
305    css
306}
307
308/// The class name for a depth.
309#[must_use]
310pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
311    let name = match depth {
312        Depth::Flat => return None,
313        Depth::Raised => "raised",
314        Depth::Well => "well",
315        Depth::Sunken => "sunken",
316        // A depth added to the description since this renderer was last
317        // built. No class, on the same footing as Flat: emitting a name
318        // whose rule body we cannot write would put a class in the markup
319        // that the stylesheet never defines.
320        _ => return None,
321    };
322    Some(format!("{}{name}", opts.class_prefix))
323}
324
325/// A prefixed class name.
326fn class(name: &str, opts: &Emit) -> String {
327    format!("{}{name}", opts.class_prefix)
328}
329
330/// The fill and edge declarations for a depth, as a rule body.
331///
332/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
333/// Callers lean on the emptiness to skip the rule rather than emit a class that
334/// sets nothing: a class that sets no properties is a class that means "I
335/// thought about this", which is what comments are for.
336///
337/// The two halves are emitted independently because [`Depth::Sunken`] has a
338/// fill and no bevel. Requiring both, which this did before makeover-layout
339/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
340/// mean unpaired: both halves still come off one `Depth`, so they cannot
341/// disagree about what the region is.
342#[must_use]
343pub fn depth_declarations(depth: Depth) -> String {
344    let mut css = String::new();
345    if let Some(fill) = depth.fill() {
346        let _ = writeln!(css, "    background: {};", fill_var(fill));
347    }
348    if let Some(bevel) = depth.bevel() {
349        let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
350    }
351    css
352}
353
354/// One rule giving a selector a depth, or nothing when the depth declares
355/// nothing.
356#[must_use]
357pub fn depth_rule(selector: &str, depth: Depth) -> String {
358    let body = depth_declarations(depth);
359    if body.is_empty() {
360        return String::new();
361    }
362    format!(".{selector} {{\n{body}}}\n")
363}
364
365/// The media condition a hover rule has to sit inside, or `None` if hover is
366/// unconditional.
367///
368/// Two crates answer this and neither answer is made here. `makeover-touch`
369/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
370/// that capability is spelled as a media condition. Asking both is what stops
371/// this renderer minting a third opinion, which is what all three apps did:
372/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
373/// alone, and the MNW server had no gate at all.
374///
375/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
376/// member, which reports as much through `reads_size`. Passing Compact is not
377/// a claim about width; the test below pins that every class agrees.
378fn hover_condition() -> Option<&'static str> {
379    if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
380        // A fingertip grew a hover state. Nothing to gate, and this renderer
381        // should not invent a reason to gate anyway.
382        None
383    } else {
384        Some(Density::Pointer.media_condition())
385    }
386}
387
388/// Put a rule inside a media query, or leave it alone.
389fn gated(condition: Option<&str>, rule: &str) -> String {
390    let Some(condition) = condition else {
391        return rule.to_string();
392    };
393    let mut css = format!("@media {condition} {{\n");
394    for line in rule.lines() {
395        // Blank lines stay blank. Indenting one leaves trailing whitespace,
396        // which is the sort of thing a formatter later reverts and calls a diff.
397        if line.is_empty() {
398            css.push('\n');
399        } else {
400            let _ = writeln!(css, "    {line}");
401        }
402    }
403    css.push_str("}\n");
404    css
405}
406
407/// The keyboard focus ring, placed by the depth it lands on.
408///
409/// One ring for the whole system, because a focus ring's job is to be
410/// recognised and three apps having three of them is the failure. What varies
411/// is where it sits, and that comes off [`Depth`] rather than off a per-
412/// component choice: a well takes the ring inside its own edge, and anything
413/// standing proud of the page takes it outside.
414///
415/// `outline` rather than the composed `box-shadow` the invalid-field ring at
416/// [`field_rules`] uses, and deliberately the one place the two rings are built
417/// differently. A `box-shadow` ring has to restate the bevel beside it, because
418/// `box-shadow` is not additive and a lone ring silently drops the well out
419/// from under the element. That restatement is a second copy of the depth,
420/// living in a different function from the first, and it is exactly the
421/// duplication `Depth` exists to prevent. `outline` occupies its own property,
422/// so the bevel survives untouched and there is nothing to keep in agreement.
423/// They render the same: both are a flush ring one border-width wide.
424#[must_use]
425pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
426    let w = opts.focus_width;
427    // Same magnitude either way, and only the sign comes off the depth. Both
428    // values are what the consumers had already converged on independently:
429    // 2px out is what all three wrote, and 2px in is the MNW server's own
430    // answer for the one inset ring it had.
431    let offset = match depth.bevel() {
432        // Inside the well, clear of its edge rather than painted over it.
433        Some(Bevel::Inset) => format!("calc(-1 * {w})"),
434        // Raised, or no edge at all. Outside, standing off by its own width.
435        _ => w.to_string(),
436    };
437    format!(
438        ".{selector}:focus-visible {{\n    outline: {w} solid var(--{});\n    outline-offset: {offset};\n}}\n",
439        State::Focus.token()
440    )
441}
442
443/// Present, visible, and not answering.
444///
445/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
446/// only matches form elements and half the things this crate emits are not
447/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
448/// the accessible state is the pattern [`field_rules`] already establishes for
449/// `aria-invalid`, on the reasoning that one fact read by both the styling and
450/// the accessibility tree cannot drift from itself.
451///
452/// The rest depth is re-asserted rather than assumed, because this rule has to
453/// beat the hover and pressed rules above it. It does that on source order at
454/// equal specificity, not by out-specifying them: every rule this function's
455/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
456/// one of them and have to be unpicked when this output moves inside its own
457/// cascade layer.
458#[must_use]
459pub fn disabled_rule(selector: &str, depth: Depth) -> String {
460    format!(
461        ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{}    color: var(--{});\n    cursor: not-allowed;\n}}\n",
462        depth_declarations(depth),
463        State::Disabled.token()
464    )
465}
466
467/// Every state a selector that answers a click implies: hover, pressed, focus
468/// and disabled, in that order.
469///
470/// Order is the whole cascade mechanism here. All four selectors are
471/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
472/// and by nothing else.
473///
474/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
475/// only the edge is what left goingson hand-writing `background:
476/// var(--surface-sunken)` on three separate rules, and a fill that does not
477/// travel with its edge is precisely the disagreement `Depth` exists to make
478/// unrepresentable. So the pressed fill comes from the description
479/// (`--surface-well`) rather than from whatever each app reached for.
480///
481/// Hover has no member in the description and is renderer policy: a terminal
482/// and an immediate-mode painter have no hover to express. It resolves against
483/// `--hover-surface`, which `makeover` already derives and which nothing
484/// consumed until now. What it *is* gated on is capability, via
485/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
486/// goingson's section 60 exists solely to take back the hover state this
487/// function had just handed it, by out-specifying a rule it does not own.
488///
489/// `depth` is the selector's **rest** depth, used to place the focus ring and
490/// to restore the surface under a disabled control. The pressed rule keeps
491/// inverting from [`Depth::Raised`] regardless, which is what every caller got
492/// before this parameter existed: a tab's unchosen depth is
493/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
494/// from the rest depth would leave a tab with no press at all.
495#[must_use]
496pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
497    let mut css = gated(
498        hover_condition(),
499        &format!(".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n"),
500    );
501    css.push_str(&depth_rule(
502        &format!("{selector}:active"),
503        Depth::Raised.pressed(),
504    ));
505    css.push_str(&focus_rule(selector, depth, opts));
506    css.push_str(&disabled_rule(selector, depth));
507    css
508}
509
510/// One rule per depth: its fill and its edge, together.
511///
512/// A depth and nothing else. `.raised` says a surface sits on what is behind
513/// it, which is a statement about the shape and not about what happens when a
514/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
515/// named surfaces are where interaction lives: `.card` and `.button` are the
516/// same depth *and* controls, and they get their states from
517/// [`surface_rules`].
518///
519/// This class carried the interactive set until 0.17.0, which left the
520/// vocabulary with no raised surface that is merely an object. Consumers that
521/// needed one took a control class and cancelled half of it instead: sixteen
522/// elements in goingson across three `.card--*` variants, each re-asserting the
523/// resting fill and bevel on `:hover` and `:active`. Nothing anywhere used
524/// `.raised` itself, so the states were unasked-for in every consumer at once.
525#[must_use]
526pub fn depth_rules(opts: &Emit) -> String {
527    let mut css = String::new();
528    for depth in [Depth::Raised, Depth::Well] {
529        let Some(class) = depth_class(depth, opts) else {
530            continue;
531        };
532        css.push_str(&depth_rule(&class, depth));
533    }
534    css
535}
536
537/// The three surfaces that are a depth with a name.
538///
539/// `button` and `card` are both [`Depth::Raised`], and `field` is a
540/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
541/// gives a text field. Their bodies come out identical by construction rather
542/// than by hand: three hand-written copies in goingson's stylesheet is what
543/// phase A deletes, and generating them from one call is what stops them
544/// drifting apart again.
545fn surface_rules(opts: &Emit) -> String {
546    let mut css = String::new();
547    for name in ["button", "card"] {
548        let c = class(name, opts);
549        css.push_str(&depth_rule(&c, Depth::Raised));
550        css.push_str(&interactive_rules(&c, Depth::Raised, opts));
551    }
552
553    let field = class("field", opts);
554    css.push_str(&depth_rule(&field, Depth::Well));
555
556    // A field takes focus and refuses input like everything else here, and got
557    // neither until now, which is why all three apps hand-write a focus ring
558    // for it and no two of them match. No hover or pressed: a text field does
559    // not light up under the pointer and does not invert when clicked, so the
560    // two states `interactive_rules` would add are the two it does not have.
561    css.push_str(&focus_rule(&field, Depth::Well, opts));
562    css.push_str(&disabled_rule(&field, Depth::Well));
563
564    // Keyed on the ARIA attribute rather than on a class, so the visual state
565    // and the accessible state cannot drift apart: there is one fact and both
566    // read it. goingson already drove its invalid styling this way and was
567    // right to; the `.invalid` class this emitted before 0.5.0 was a second
568    // place to forget.
569    //
570    // The ring composes *after* the bevel rather than replacing it. box-shadow
571    // is not additive, so a lone ring silently dropped the well out from under
572    // an invalid field. Flat and unlit: this edge is saying "wrong", and
573    // lighting one side would have it say "raised" at the same time.
574    let _ = writeln!(
575        css,
576        ".{field}[aria-invalid=\"true\"] {{\n    box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
577        bevel_var(Bevel::Inset),
578        opts.border_width
579    );
580    css
581}
582
583/// Badges and chips.
584///
585/// The one place phase A changes how goingson looks rather than only where its
586/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
587/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
588/// carrying the raised bevel. Splitting that means reading every call site to
589/// decide which of the two it always was.
590///
591/// What a badge does carry is a [`Tone`], the intent family it shares with
592/// notices and nothing else. Neutral is the bare class rather than a variant,
593/// because it is the absence of a status and not a status called "none".
594fn token_rules(opts: &Emit) -> String {
595    let mut css = String::new();
596
597    // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
598    // and a label with an edge says it can be pressed.
599    let badge = class("badge", opts);
600    let _ = writeln!(
601        css,
602        ".{badge} {{\n    color: var(--{});\n}}",
603        Tone::Neutral.token()
604    );
605    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
606        let _ = writeln!(
607            css,
608            ".{badge}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
609            tone.token()
610        );
611    }
612
613    // A chip holds itself down, which is `Depth::pressed` arrived at
614    // independently by two apps. `removable` is a remove affordance, so it is
615    // markup and waits for phase B.
616    let chip = class("chip", opts);
617    let unlatched = Token::Chip { removable: false };
618    css.push_str(&depth_rule(&chip, unlatched.depth(false)));
619    css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
620    css.push_str(&depth_rule(
621        &format!("{chip}.latched"),
622        unlatched.depth(true),
623    ));
624    css
625}
626
627/// The three selectors, each named by what it picks.
628///
629/// A tab comes *forward* to join the pane it opens, which is why
630/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
631/// are held in. That is the folder semantic, and it is the whole reason the
632/// three are not one member with a flag.
633///
634/// [`Selector::abutting`] is not emitted: whether the options touch is
635/// spacing, and spacing is `makeover-geometry`'s question to answer.
636///
637/// Both states emit as of makeover-layout 0.3.0. Before it the description
638/// named only the chosen option, so an unchosen one fell through to
639/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
640/// strip hand-writing the recess that makes its chosen tab read as forward.
641fn selector_rules(opts: &Emit) -> String {
642    let mut css = String::new();
643    for (selector, name) in [
644        (Selector::Tabs, "tab"),
645        (Selector::Segmented, "segment"),
646        (Selector::Toggle, "toggle"),
647    ] {
648        let c = class(name, opts);
649        css.push_str(&depth_rule(&c, selector.unchosen()));
650        css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
651        css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
652    }
653    css
654}
655
656/// The parts of a list row.
657///
658/// The list is written out rather than derived because `RowPart` is
659/// `#[non_exhaustive]` as of makeover-layout 0.9.0, so there is nothing to
660/// iterate. A member added upstream emits no rule until it is named here, which
661/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
662/// [`part_class`] carries the same list and the same obligation.
663fn row_rules(opts: &Emit) -> String {
664    let mut css = String::new();
665    let row = class("row", opts);
666    for part in [
667        RowPart::Primary,
668        RowPart::Secondary,
669        RowPart::Meta,
670        RowPart::Actions,
671        RowPart::Tokens,
672        RowPart::Proportion,
673    ] {
674        let c = class(part_class(part), opts);
675
676        // Actions carry controls rather than text, and `RowPart::intent` says
677        // so by returning the same intent inheriting already gives. Pinning it
678        // would be louder than saying nothing. Tokens answer alike, for their
679        // own reason: each token carries its own tone, and a colour on the
680        // strip would fight the things sitting in it. A proportion is the same
681        // case again: the meter inside carries the tone.
682        if !matches!(
683            part,
684            RowPart::Actions | RowPart::Tokens | RowPart::Proportion
685        ) {
686            let _ = writeln!(css, ".{c} {{\n    color: var(--{});\n}}", part.intent());
687        }
688
689        if part.revealed_on_hover() {
690            // Hidden rather than absent: the row must not change height when
691            // the pointer arrives. `focus-within` carries the keyboard, which
692            // hover on its own would lock out.
693            //
694            // Transparent rather than `visibility: hidden`, which was the first
695            // form and defeated the very escape above: a `visibility: hidden`
696            // element is out of the focus order and out of the accessibility
697            // tree, so tabbing could never reach an action and could never
698            // trigger the row's `focus-within`. goingson had reached the same
699            // opacity form independently, on its own comment "always in the DOM
700            // for keyboard and screen readers".
701            //
702            // `pointer-events` rides along because opacity leaves the hit area
703            // behind: without it a renderer with no hover carries an invisible
704            // tappable control. Keyboard focus is unaffected by it.
705            // The hide is gated too, which it was not in 0.10.0, and that was
706            // an incomplete capability answer rather than a deliberate one.
707            // Ungated, a fingertip got actions hidden with no hover to bring
708            // them back, so both webview apps hand-wrote the same
709            // `opacity: 1` to undo it: goingson in its touch block and
710            // Balanced Breakfast in its own. A primitive that owns the hiding
711            // owes the answer for the device that cannot unhide, and the
712            // answer both consumers already reached is not to hide at all.
713            css.push_str(&gated(
714                hover_condition(),
715                &format!(".{c} {{\n    opacity: 0;\n    pointer-events: none;\n}}\n"),
716            ));
717
718            // The two halves split here, where they used to be one selector
719            // list. Hover-to-reveal is the literal case `Affordance::Hover`
720            // was written from, and on a touchscreen it does not fail
721            // gracefully: the actions are simply unreachable, because there
722            // is no pointer to bring them back. So the hover half is gated
723            // and the app owes those rows another way in.
724            //
725            // `focus-within` stays outside the query. A touchscreen device
726            // with a keyboard attached is a real thing, and it is the one
727            // path to these actions that survives the gate.
728            let revealed = "    opacity: 1;\n    pointer-events: auto;\n";
729            css.push_str(&gated(
730                hover_condition(),
731                &format!(".{row}:hover .{c} {{\n{revealed}}}\n"),
732            ));
733            let _ = write!(css, ".{row}:focus-within .{c} {{\n{revealed}}}\n");
734        }
735    }
736    css
737}
738
739/// The progress trough these rules fill.
740///
741/// This was renderer-local chrome with nothing behind it until makeover-layout
742/// 0.10.0, which is the unusual order: the tones below were emitted for every
743/// bar in the tree while the only way to describe one was to concatenate the
744/// numbers into a heading. `Meter` is the word that arrived late, and
745/// [`meter::meter_html`](crate::meter::meter_html) is what now fills these.
746///
747/// The rules stay a superset of what a description can ask for. An app drawing
748/// its own bar keeps these classes, which is what the four goingson grew
749/// independently were adopted onto.
750///
751/// The trough is a [`Depth::Well`], the same reading a text field gets:
752/// something with its content down inside it.
753fn progress_rules(opts: &Emit) -> String {
754    let progress = class("progress", opts);
755    // `progress-fill` rather than a bare `fill`: an unprefixed build claims
756    // these names in the app's own stylesheet, and `.fill` is grabby enough to
757    // catch things that have nothing to do with progress. goingson already
758    // calls it `.progress-fill`, so this is also the name that deletes.
759    let fill = class("progress-fill", opts);
760    let mut css = depth_rule(&progress, Depth::Well);
761
762    // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
763    // place this differs from the badge rules, and deliberately: a badge with
764    // no status is a muted label, while a bar with no status is still
765    // reporting progress, and `content-muted` would read as disabled.
766    let _ = writeln!(
767        css,
768        ".{progress} > .{fill} {{\n    background: var(--action);\n}}"
769    );
770
771    // A bar can be saying something, same as a badge: goingson colours subtask
772    // progress as success and an over-estimate as danger, which is real
773    // information rather than decoration. Emitting the tones is what lets that
774    // survive adoption instead of staying hand-written.
775    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
776        let _ = writeln!(
777            css,
778            ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n    background: var(--{0});\n}}",
779            tone.token()
780        );
781    }
782    css
783}
784
785/// A strip of figures, and the two spans inside each one.
786///
787/// Colour only, which is the deferral rule applied to a component that badly
788/// wants to break it. A figure reads as a figure because the value is set large
789/// over a small caption, and that is a size: `makeover-geometry` answers how
790/// much space and this crate answers what the thing is. Emitting `font-size`
791/// here would be this crate naming a value, which is the one thing it is defined
792/// by not doing, and `progress_rules` is the precedent — it emits the tones and
793/// never the width, because the width is not its to know.
794///
795/// So the arrangement and the type scale are the app's, and what is generated is
796/// the part an app cannot get right by itself: which of the two spans carries
797/// the tone.
798fn figure_rules(opts: &Emit) -> String {
799    let figure = class("figure", opts);
800    let value = class("figure-value", opts);
801    let caption = class("figure-caption", opts);
802    let mut css = String::new();
803
804    let _ = writeln!(
805        css,
806        ".{figure} > .{value} {{\n    color: var(--{});\n}}",
807        Tone::Neutral.token()
808    );
809    let _ = writeln!(
810        css,
811        ".{figure} > .{caption} {{\n    color: var(--content-muted);\n}}"
812    );
813
814    // A toned figure tones the value and never the caption. The caption is the
815    // noun and stays muted; the number is the thing that is saying something.
816    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
817        let _ = writeln!(
818            css,
819            ".{figure}[data-tone=\"{0}\"] > .{value} {{\n    color: var(--{0});\n}}",
820            tone.token()
821        );
822    }
823    css
824}
825
826/// A region's stand-in, and the header of a table that can be reordered.
827///
828/// Both are 0.12.0 members and both are colour and affordance only, which is
829/// where `figure_rules` landed after trying to emit a type scale. How much room
830/// a stand-in gets is a size — goingson has the same one at three, as
831/// `--compact`, `--dashboard` and `--padded` — and a size is
832/// `makeover-geometry`'s question.
833///
834/// The caret is the one thing here that is neither colour nor affordance, and it
835/// is a renderer's own expression rather than a value the description named:
836/// `aria-sort` is what the table actually says, and this turns it into something
837/// visible for everyone not using a screen reader. A terminal draws its own; an
838/// immediate-mode painter draws its own.
839fn state_rules(opts: &Emit) -> String {
840    let placeholder = class("placeholder", opts);
841    let text = class("placeholder-text", opts);
842    let heading = class("table-heading", opts);
843    let mut css = String::new();
844
845    let _ = writeln!(
846        css,
847        ".{placeholder} > .{text} {{\n    color: var(--content-muted);\n}}"
848    );
849    // Only the failure is toned. An empty list is the normal state of a new
850    // install, and `Readiness::tone` is what says so.
851    let _ = writeln!(
852        css,
853        ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n    color: var(--{0});\n}}",
854        Tone::Danger.token()
855    );
856
857    // A header that reorders the table is a control, and the pointer is the
858    // only part of saying so that is not the app's own type and spacing.
859    let _ = writeln!(
860        css,
861        ".{heading}[data-sortable] {{\n    cursor: pointer;\n}}"
862    );
863    for (direction, caret) in [("ascending", "\\2191"), ("descending", "\\2193")] {
864        let _ = writeln!(
865            css,
866            ".{heading}[aria-sort=\"{direction}\"]::after {{\n    content: \"{caret}\";\n}}"
867        );
868    }
869    css
870}
871
872/// The component layer: every named thing phase A emits.
873///
874/// No scrollbar track. It was on the phase A list and came off: eight lines of
875/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
876/// would want handed to it, so it stays with the apps.
877#[must_use]
878pub fn component_rules(opts: &Emit) -> String {
879    let mut css = String::new();
880    css.push_str(&surface_rules(opts));
881    css.push_str(&token_rules(opts));
882    css.push_str(&selector_rules(opts));
883    css.push_str(&row_rules(opts));
884    css.push_str(&progress_rules(opts));
885    css.push_str(&figure_rules(opts));
886    css.push_str(&state_rules(opts));
887    css
888}
889
890/// The whole phase-A stylesheet: properties, depth rules and components, in
891/// [`CSS_LAYER`], under a generated-file banner.
892///
893/// The banner sits outside the layer, because a comment participates in no
894/// cascade and a reader opening the file should see what it is before seeing
895/// an at-rule.
896#[must_use]
897pub fn stylesheet(opts: &Emit) -> String {
898    format!(
899        "/* Generated by makeover-webview from makeover-layout. Do not edit.\n   \
900         Depth is a fill and an edge together; naming them apart is what let\n   \
901         them disagree. See the crate's README and wiki note makeover-layout.\n\n   \
902         Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n   \
903         order once in your own stylesheet, or this layer's position is decided\n   \
904         by whichever generated file the browser happens to see first:\n\n   \
905         @layer {CSS_LAYER}, base, components, responsive; */\n{}",
906        in_css_layer(&format!(
907            ":root {{\n{}}}\n\n{}\n{}",
908            bevel_properties(opts),
909            depth_rules(opts),
910            component_rules(opts)
911        ))
912    )
913}
914
915#[cfg(test)]
916mod tests {
917    use super::*;
918    use makeover_layout::Edge;
919
920    #[test]
921    fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
922        // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
923        // deletion, not a redesign, or nobody will take it.
924        let opts = Emit::default();
925        assert_eq!(
926            bevel_shadow(Bevel::Raised, &opts),
927            "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
928        );
929        assert_eq!(
930            bevel_shadow(Bevel::Inset, &opts),
931            "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
932        );
933    }
934
935    #[test]
936    fn no_colour_ever_reaches_the_output() {
937        let css = stylesheet(&Emit::default());
938        assert!(!css.contains('#'), "a hex literal escaped into the CSS");
939        assert!(
940            !css.contains("rgb"),
941            "a colour function escaped into the CSS"
942        );
943        // Every colour is named, never resolved.
944        assert!(css.contains("var(--surface-raised)"));
945        assert!(css.contains("var(--bevel-light)"));
946    }
947
948    #[test]
949    fn a_well_falls_back_through_css_rather_than_through_rust() {
950        assert_eq!(
951            fill_var(Fill::Well),
952            "var(--surface-well, var(--surface-page))"
953        );
954        // Nothing else needs one.
955        assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
956        assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
957    }
958
959    #[test]
960    fn raised_and_well_do_not_collapse_onto_each_other() {
961        let css = depth_rules(&Emit::default());
962        assert!(css.contains(".raised {"));
963        assert!(css.contains(".well {"));
964        assert!(css.contains("var(--bevel-raised)"));
965        assert!(css.contains("var(--bevel-inset)"));
966    }
967
968    #[test]
969    fn the_cascade_carries_the_pressed_state() {
970        let css = surface_rules(&Emit::default());
971        // The one thing this renderer gets free that the other two resolve by
972        // hand, eighteen call sites deep in audiofiles' case. Asserted on a
973        // named surface: pressing belongs to the control, not to the depth.
974        assert!(css.contains(".card:active {"));
975        assert!(css.contains(".button:active {"));
976    }
977
978    #[test]
979    fn the_depth_class_is_a_surface_and_not_a_control() {
980        let css = depth_rules(&Emit::default());
981        // The static surface the vocabulary was missing. Sixteen goingson
982        // elements wore .card and cancelled its hover and press to get this,
983        // because a raised object that is not pressable had no other spelling.
984        for state in [":hover", ":active", ":focus-visible", ":disabled"] {
985            assert!(
986                !css.contains(&format!(".raised{state}")),
987                "the depth class claimed {state}: {css}"
988            );
989        }
990        assert!(css.contains("var(--bevel-raised)"), "still raised: {css}");
991    }
992
993    #[test]
994    fn pressing_moves_the_fill_and_not_only_the_edge() {
995        // The decision-1 guard, and the regression that mattered: emitting the
996        // bevel flip alone is what left goingson hand-writing `background:
997        // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
998        // of the three could be deleted.
999        let pressed = interactive_rules("button", Depth::Raised, &Emit::default());
1000        assert!(pressed.contains(".button:active {"));
1001        assert!(
1002            pressed.contains("background: var(--surface-well, var(--surface-page))"),
1003            "pressed dropped its fill: {pressed}"
1004        );
1005        assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
1006    }
1007
1008    #[test]
1009    fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
1010        // goingson presses to --surface-sunken. The description says a pressed
1011        // raised region reads as a well, and makeover says outright that
1012        // surface-sunken cannot serve as one, so the app is the thing that
1013        // moves.
1014        //
1015        // Scoped to the pressed rules rather than to the whole sheet: since
1016        // makeover-layout 0.3.0 an unchosen tab is legitimately
1017        // --surface-sunken, so the token appearing somewhere in the output no
1018        // longer means the app's choice leaked in.
1019        let css = stylesheet(&Emit::default());
1020        let mut checked = 0;
1021        for rule in css.split("}\n") {
1022            if !rule.contains(":active") {
1023                continue;
1024            }
1025            checked += 1;
1026            assert!(
1027                !rule.contains("surface-sunken"),
1028                "a pressed rule took the app's fill: {rule}"
1029            );
1030        }
1031        assert!(checked > 0, "no pressed rules found to check");
1032        assert_eq!(
1033            Depth::Raised.pressed().fill(),
1034            Some(Fill::Well),
1035            "the description changed under us"
1036        );
1037    }
1038
1039    #[test]
1040    fn the_whole_stylesheet_is_emitted_in_the_family_layer() {
1041        // The point of 0.11.0. Unlayered normal declarations outrank every
1042        // named layer, so an app declaring `@layer base, components` loses
1043        // every rule it owns to this file until this file is layered too.
1044        let css = stylesheet(&Emit::default());
1045        assert!(css.contains(&format!("@layer {CSS_LAYER} {{")));
1046
1047        // Exactly one layer block, and nothing outside it but the banner.
1048        assert_eq!(css.matches("@layer").count(), 2, "banner names it once");
1049        let opened = css.find("@layer makeover {").expect("layer opens");
1050        for (i, line) in css.lines().enumerate() {
1051            let before_layer = css.lines().take(i).map(str::len).sum::<usize>() < opened;
1052            if before_layer || line.is_empty() {
1053                continue;
1054            }
1055            assert!(
1056                line.starts_with("    ") || line == "}" || line.starts_with("   "),
1057                "line outside the layer: {line:?}"
1058            );
1059        }
1060    }
1061
1062    #[test]
1063    fn the_generated_sheet_carries_no_trailing_whitespace() {
1064        // A checked-in generated file that a formatter wants to rewrite is a
1065        // diff every time somebody saves it.
1066        let css = stylesheet(&Emit::default());
1067        for (i, line) in css.lines().enumerate() {
1068            assert_eq!(line, line.trim_end(), "trailing whitespace on line {i}");
1069        }
1070    }
1071
1072    #[test]
1073    fn the_banner_tells_an_app_how_to_order_the_layer() {
1074        // Without a declared order the layer's position depends on which
1075        // generated file the browser sees first, which is not a contract.
1076        let css = stylesheet(&Emit::default());
1077        assert!(css.contains("@layer makeover, base, components, responsive;"));
1078        // And the banner is outside the layer, not a rule inside it.
1079        assert!(css.starts_with("/* Generated by makeover-webview"));
1080    }
1081
1082    #[test]
1083    fn a_primitive_owns_every_state_it_implies() {
1084        // The whole point of 0.10.0. Anything emitting a hover rule owes the
1085        // other three, or the consuming app supplies them by out-specifying a
1086        // rule it does not own: 19 such rules in goingson, 21 in the MNW
1087        // server, and three focus rings that do not match.
1088        let css = stylesheet(&Emit::default());
1089        for selector in ["button", "card", "chip", "tab", "segment", "toggle"] {
1090            assert!(css.contains(&format!(".{selector}:hover {{")), "{selector}");
1091            assert!(
1092                css.contains(&format!(".{selector}:active {{")),
1093                "{selector}"
1094            );
1095            assert!(
1096                css.contains(&format!(".{selector}:focus-visible {{")),
1097                "{selector} has no focus ring"
1098            );
1099            assert!(
1100                css.contains(&format!(".{selector}:disabled,")),
1101                "{selector} has no disabled state"
1102            );
1103        }
1104    }
1105
1106    #[test]
1107    fn a_field_takes_focus_and_refuses_input_without_taking_a_hover() {
1108        // A text field does not light up under the pointer, so it gets the two
1109        // states it has and not the two it does not.
1110        let css = stylesheet(&Emit::default());
1111        assert!(css.contains(".field:focus-visible {"));
1112        assert!(css.contains(".field:disabled,"));
1113        assert!(!css.contains(".field:hover {"));
1114        assert!(!css.contains(".field:active {"));
1115    }
1116
1117    #[test]
1118    fn disabled_is_emitted_after_hover_so_source_order_settles_it() {
1119        // Every one of these selectors is specificity (0,2,0), so nothing but
1120        // order decides which wins. A disabled button taking the hover fill is
1121        // the exact bug goingson's `.button:disabled:hover` was written to fix,
1122        // and the reason it had to reach (0,3,0) to do it.
1123        let css = interactive_rules("button", Depth::Raised, &Emit::default());
1124        let hover = css.find(":hover").expect("hover");
1125        let active = css.find(":active").expect("active");
1126        let focus = css.find(":focus-visible").expect("focus");
1127        let disabled = css.find(":disabled").expect("disabled");
1128        assert!(hover < active && active < focus && focus < disabled);
1129
1130        // And it restores the surface, or the hover fill survives underneath.
1131        let tail = &css[disabled..];
1132        assert!(tail.contains("background: var(--surface-raised)"));
1133    }
1134
1135    #[test]
1136    fn a_disabled_state_reaches_things_that_cannot_be_disabled() {
1137        // `:disabled` matches form elements only, and a chip is a div. Keying
1138        // on the ARIA attribute too is the pattern the invalid field already
1139        // set: one fact, read by the styling and the accessibility tree alike.
1140        let css = disabled_rule("chip", Depth::Raised);
1141        assert!(css.contains(".chip:disabled,"));
1142        assert!(css.contains(".chip[aria-disabled=\"true\"]"));
1143        assert!(css.contains("cursor: not-allowed"));
1144    }
1145
1146    #[test]
1147    fn the_focus_ring_does_not_disturb_the_bevel_it_lands_on() {
1148        // `outline` has its own property, so unlike the invalid ring there is
1149        // no bevel to restate beside it and nothing to keep in agreement.
1150        let opts = Emit::default();
1151        let css = focus_rule("button", Depth::Raised, &opts);
1152        assert!(css.contains("outline: 2px solid var(--focus-ring)"));
1153        assert!(!css.contains("box-shadow"), "the ring restated the bevel");
1154    }
1155
1156    #[test]
1157    fn a_well_takes_the_ring_inside_and_a_raised_surface_outside() {
1158        // One ring, placed by depth. The offset comes off `Depth::bevel` and
1159        // not off a per-component choice, which is what gave three apps three
1160        // different rings.
1161        let opts = Emit::default();
1162        assert!(focus_rule("field", Depth::Well, &opts).contains("outline-offset: calc(-1 * 2px)"));
1163        assert!(focus_rule("button", Depth::Raised, &opts).contains("outline-offset: 2px"));
1164        // Nothing to sit inside of, so it sits outside.
1165        assert!(focus_rule("badge", Depth::Sunken, &opts).contains("outline-offset: 2px"));
1166
1167        // And the ring is not the bevel. Reusing border_width emitted a 1px
1168        // ring that every consumer had already overridden.
1169        assert_ne!(opts.focus_width, opts.border_width);
1170    }
1171
1172    #[test]
1173    fn hover_is_gated_on_capability_and_the_keyboard_path_is_not() {
1174        // goingson's section 60 exists only to take back the hover state this
1175        // crate handed it. Gating at the source is what deletes that section
1176        // in all three apps rather than having each fight for it.
1177        let css = stylesheet(&Emit::default());
1178        let condition = format!("@media {}", Density::Pointer.media_condition());
1179        assert!(css.contains(&condition));
1180
1181        // The row reveal splits: hover inside the query, focus-within outside,
1182        // or a touchscreen with a keyboard loses its only way to the actions.
1183        // Compared by indentation rather than by brace-hunting, because both
1184        // sit inside the cascade layer now and every brace is nested.
1185        let indent = |needle: &str| {
1186            let line = css
1187                .lines()
1188                .find(|l| l.contains(needle))
1189                .unwrap_or_else(|| panic!("no line for {needle}"));
1190            line.len() - line.trim_start().len()
1191        };
1192        let hover = indent(".row:hover .row-actions");
1193        let keyboard = indent(".row:focus-within .row-actions");
1194        // The hide is gated with the reveal. Ungated it leaves a fingertip
1195        // with actions it cannot bring back, which is what both webview apps
1196        // were undoing by hand.
1197        let hide = css
1198            .lines()
1199            .position(|l| l.trim() == ".row-actions {")
1200            .expect("hide rule");
1201        let query = css
1202            .lines()
1203            .take(hide)
1204            .enumerate()
1205            .filter(|(_, l)| l.trim_start().starts_with("@media"))
1206            .map(|(i, _)| i)
1207            .last()
1208            .expect("a query precedes it");
1209        assert!(hide - query < 3, "the hide is not inside the query");
1210        assert!(
1211            hover > keyboard,
1212            "hover reveal must be nested inside the capability query and the \
1213             keyboard reveal must not be: hover indent {hover}, keyboard {keyboard}"
1214        );
1215    }
1216
1217    #[test]
1218    fn the_capability_answer_is_asked_for_and_not_assumed() {
1219        // Both halves come from the crates that own them. If `makeover-touch`
1220        // ever says a fingertip has hover, this stops gating on its own.
1221        assert!(!Affordance::Hover.available(Density::Touch, SizeClass::Compact));
1222        assert!(Affordance::Hover.available(Density::Pointer, SizeClass::Compact));
1223        assert_eq!(hover_condition(), Some(Density::Pointer.media_condition()));
1224
1225        // And the size class passed to that call is not a claim about width.
1226        assert!(Affordance::Hover.reads_density());
1227        for size in [SizeClass::Compact, SizeClass::Medium, SizeClass::Expanded] {
1228            assert!(!Affordance::Hover.available(Density::Touch, size));
1229        }
1230    }
1231
1232    #[test]
1233    fn hover_resolves_against_the_token_makeover_already_derives() {
1234        let css = interactive_rules("card", Depth::Raised, &Emit::default());
1235        assert!(css.contains(".card:hover {"));
1236        assert!(css.contains("background: var(--hover-surface)"));
1237        // Not the app's choice, which was --surface-overlay.
1238        assert!(!css.contains("surface-overlay"));
1239    }
1240
1241    #[test]
1242    fn a_badge_gets_no_edge_and_no_fill() {
1243        // Decision 2, and the one visible redesign in phase A. Token::Badge is
1244        // Flat: an edge on a label says it can be pressed.
1245        let css = token_rules(&Emit::default());
1246        let badge = css
1247            .lines()
1248            .skip_while(|l| !l.starts_with(".badge {"))
1249            .take_while(|l| !l.starts_with('}'))
1250            .collect::<Vec<_>>()
1251            .join("\n");
1252        assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
1253        assert!(!badge.contains("background"), "badge kept a fill: {badge}");
1254        assert_eq!(Token::Badge.depth(false), Depth::Flat);
1255        assert_eq!(Token::Badge.depth(true), Depth::Flat);
1256    }
1257
1258    #[test]
1259    fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
1260        let css = token_rules(&Emit::default());
1261        // Neutral is the absence of a status, not a status named "none".
1262        assert!(css.contains(".badge {\n    color: var(--content-muted);"));
1263        assert!(!css.contains("data-tone=\"content-muted\""));
1264        for tone in ["info", "success", "warning", "danger"] {
1265            assert!(
1266                css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
1267                "missing tone {tone}"
1268            );
1269            assert!(css.contains(&format!("color: var(--{tone})")));
1270        }
1271    }
1272
1273    #[test]
1274    fn a_chip_is_raised_and_latches_into_a_well() {
1275        let css = token_rules(&Emit::default());
1276        assert!(css.contains(".chip {"));
1277        assert!(css.contains(".chip.latched {"));
1278        assert!(css.contains(".chip:active {"));
1279        // The whole difference from a badge: it answers a click.
1280        assert!(Token::Chip { removable: false }.interactive());
1281        assert!(!Token::Badge.interactive());
1282    }
1283
1284    #[test]
1285    fn only_a_tab_comes_forward_when_chosen() {
1286        // The folder semantic. Collapsing the three selectors would lose it.
1287        let css = selector_rules(&Emit::default());
1288        assert!(css.contains(".tab.chosen {"));
1289        assert!(css.contains(".segment.chosen {"));
1290        assert!(css.contains(".toggle.chosen {"));
1291        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1292        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1293        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1294
1295        let tab = css
1296            .lines()
1297            .skip_while(|l| !l.starts_with(".tab.chosen {"))
1298            .take_while(|l| !l.starts_with('}'))
1299            .collect::<Vec<_>>()
1300            .join("\n");
1301        assert!(
1302            tab.contains("var(--bevel-raised)"),
1303            "tab was held in: {tab}"
1304        );
1305    }
1306
1307    #[test]
1308    fn an_unchosen_tab_recedes_without_looking_picked() {
1309        let css = selector_rules(&Emit::default());
1310        // Recessed by colour and given no edge. An edge would make every option
1311        // look picked; flat would leave the chosen one nothing to come forward
1312        // from, which is the gap makeover-layout 0.3.0 closed.
1313        assert!(
1314            css.contains(".tab {\n    background: var(--surface-sunken);\n}"),
1315            "unchosen tab is not recessed: {css}"
1316        );
1317        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1318        assert!(css.contains(".tab:hover {"));
1319    }
1320
1321    #[test]
1322    fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
1323        // The inverse of the tab, and why the three selectors are not one
1324        // member with a flag.
1325        let css = selector_rules(&Emit::default());
1326        assert!(css.contains(".segment {\n    background: var(--surface-raised);"));
1327        assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
1328        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1329    }
1330
1331    #[test]
1332    fn row_actions_are_revealed_without_moving_the_row() {
1333        let css = row_rules(&Emit::default());
1334        assert!(css.contains(".row-actions {\n        opacity: 0;"));
1335        // Not display:none, which would reflow the row under the pointer.
1336        assert!(!css.contains("display: none"));
1337        // Hover alone would lock the keyboard out.
1338        assert!(css.contains(".row:focus-within .row-actions"));
1339        assert!(RowPart::Actions.revealed_on_hover());
1340    }
1341
1342    #[test]
1343    fn a_hidden_row_action_is_still_focusable_and_not_tappable() {
1344        let css = row_rules(&Emit::default());
1345        // `visibility: hidden` takes the actions out of the focus order, so the
1346        // `focus-within` reveal above could never fire from an action itself.
1347        assert!(!css.contains("visibility:"));
1348        // Opacity leaves the hit area behind, so the pair travels together or
1349        // the row carries an invisible tappable control.
1350        assert!(
1351            css.contains(
1352                ".row-actions {\n        opacity: 0;\n        pointer-events: none;\n    }"
1353            )
1354        );
1355        assert!(css.contains("opacity: 1;\n    pointer-events: auto;"));
1356
1357        // And on a device with no hover the row carries no such control at
1358        // all, because the hide never applies there. That is what the comment
1359        // above used to be asking for and could not get: the hide is inside
1360        // the capability query with the reveal.
1361        let hide = css.find(".row-actions {").expect("hide rule");
1362        let query = css[..hide].rfind("@media").expect("a query precedes it");
1363        assert!(
1364            css[query..hide].find('}').is_none(),
1365            "the hide escaped the query"
1366        );
1367    }
1368
1369    #[test]
1370    fn the_three_text_parts_take_their_intents_and_actions_inherits() {
1371        let css = row_rules(&Emit::default());
1372        assert!(css.contains(".row-primary {\n    color: var(--content);"));
1373        assert!(css.contains(".row-secondary {\n    color: var(--content-secondary);"));
1374        assert!(css.contains(".row-meta {\n    color: var(--content-muted);"));
1375        // Actions carry controls, not text. Pinning the colour it would inherit
1376        // anyway is louder than saying nothing.
1377        assert!(!css.contains(".row-actions {\n    color:"));
1378    }
1379
1380    #[test]
1381    fn the_token_strip_takes_no_colour_of_its_own() {
1382        // makeover-layout 0.9.0. A token carries its own tone, so a colour on
1383        // the strip would be a rule fighting the things sitting in it -- the
1384        // same reasoning as actions, reached for a different reason.
1385        let css = row_rules(&Emit::default());
1386        assert!(!css.contains(".row-tokens {\n    color:"));
1387    }
1388
1389    #[test]
1390    fn an_unknown_row_part_renders_plainly_rather_than_failing_to_build() {
1391        // What `#[non_exhaustive]` bought and what it cost. `part_class` can no
1392        // longer be exhaustive, so a member added upstream lands as a bare
1393        // class with no rule instead of stopping the build. Asserting the
1394        // fallback exists is what keeps it from being written as `unreachable!`
1395        // by someone who reads the match as closed.
1396        assert_eq!(part_class(RowPart::Tokens), "row-tokens");
1397        assert_eq!(part_class(RowPart::Meta), "row-meta");
1398    }
1399
1400    #[test]
1401    fn the_progress_trough_is_a_well() {
1402        let css = progress_rules(&Emit::default());
1403        assert!(css.contains(".progress {"));
1404        assert!(css.contains("box-shadow: var(--bevel-inset)"));
1405        assert!(css.contains(".progress > .progress-fill {"));
1406        assert!(css.contains("background: var(--action)"));
1407        // A bare `.fill` would catch things that have nothing to do with
1408        // progress once the sheet lands unprefixed.
1409        assert!(!css.contains("> .fill "));
1410    }
1411
1412    #[test]
1413    fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
1414        let css = progress_rules(&Emit::default());
1415        // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
1416        // status is still reporting progress, and muted would read as disabled.
1417        assert!(css.contains(".progress > .progress-fill {\n    background: var(--action);"));
1418        assert!(!css.contains("progress-fill {\n    color: var(--content-muted)"));
1419        for tone in ["info", "success", "warning", "danger"] {
1420            assert!(
1421                css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
1422                "missing progress tone {tone}"
1423            );
1424        }
1425        // goingson's two live cases, which is why the tones are emitted at all.
1426        assert!(css.contains("[data-tone=\"success\"] {\n    background: var(--success);"));
1427        assert!(css.contains("[data-tone=\"danger\"] {\n    background: var(--danger);"));
1428    }
1429
1430    #[test]
1431    fn no_scrollbar_track_is_emitted() {
1432        // Decision 3's negative half. It was on the phase A list and came off;
1433        // this is what stops it drifting back in.
1434        let css = stylesheet(&Emit::default());
1435        assert!(!css.contains("scrollbar"));
1436        assert!(!css.contains("::-webkit"));
1437    }
1438
1439    #[test]
1440    fn an_invalid_field_is_ringed_without_being_lit() {
1441        let css = surface_rules(&Emit::default());
1442        assert!(css.contains(".field {"));
1443        // The ARIA attribute, not a class: one fact, read by both the visual
1444        // and the accessible state, so they cannot drift.
1445        assert!(css.contains(".field[aria-invalid=\"true\"] {"));
1446        assert!(!css.contains(".field.invalid"));
1447        // A flat ring: this edge says "wrong", and a two-tone bevel would have
1448        // it say "raised" at the same time.
1449        assert!(css.contains("0 0 0 1px var(--danger)"));
1450    }
1451
1452    #[test]
1453    fn an_invalid_field_keeps_the_well_underneath_it() {
1454        // box-shadow is not additive. A lone ring replaces the bevel and drops
1455        // the well out from under the field, which is what this emitted before
1456        // 0.5.0 and is the whole reason the rule composes.
1457        let css = surface_rules(&Emit::default());
1458        let invalid = css
1459            .lines()
1460            .skip_while(|l| !l.starts_with(".field[aria-invalid"))
1461            .take_while(|l| !l.starts_with('}'))
1462            .collect::<Vec<_>>()
1463            .join("\n");
1464        assert!(
1465            invalid.contains("var(--bevel-inset)"),
1466            "the well was dropped: {invalid}"
1467        );
1468        assert!(invalid.contains("var(--danger)"));
1469    }
1470
1471    #[test]
1472    fn button_and_card_come_out_identical_by_construction() {
1473        // The duplication phase A deletes. They are the same composition, so
1474        // the only honest way to emit both is from one call.
1475        let opts = Emit::default();
1476        let css = surface_rules(&opts);
1477        assert_eq!(
1478            depth_declarations(Depth::Raised),
1479            depth_declarations(Depth::Raised)
1480        );
1481        assert!(css.contains(".button {"));
1482        assert!(css.contains(".card {"));
1483        assert_eq!(
1484            interactive_rules("button", Depth::Raised, &Emit::default()).replace("button", "card"),
1485            interactive_rules("card", Depth::Raised, &Emit::default())
1486        );
1487    }
1488
1489    #[test]
1490    fn a_prefix_reaches_the_component_classes_too() {
1491        let opts = Emit {
1492            class_prefix: "mo-",
1493            ..Emit::default()
1494        };
1495        let css = stylesheet(&opts);
1496        for name in [
1497            "mo-button",
1498            "mo-card",
1499            "mo-field",
1500            "mo-badge",
1501            "mo-chip",
1502            "mo-tab",
1503            "mo-row-primary",
1504            "mo-progress",
1505            "mo-progress-fill",
1506        ] {
1507            assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
1508        }
1509        // The bare names must be gone entirely, or a prefixed build still
1510        // collides with the app's own stylesheet.
1511        assert!(!css.contains(".button {"));
1512        assert!(!css.contains(".card {"));
1513        assert!(!css.contains(".badge {"));
1514    }
1515
1516    #[test]
1517    fn the_whole_sheet_still_names_every_colour() {
1518        // The crate's founding property, asserted over the component layer and
1519        // not only the primitives.
1520        let css = stylesheet(&Emit::default());
1521        assert!(!css.contains('#'));
1522        assert!(!css.contains("rgb"));
1523        for line in css.lines() {
1524            // Declarations only: a selector or an at-rule can carry a colon of
1525            // its own (`:root`, `:hover`, `@media (hover: hover)`) and declares
1526            // nothing. Keyed on the trailing semicolon rather than on leading
1527            // indentation, which only ever worked as a proxy for nesting depth
1528            // and stopped when the sheet gained a cascade layer around it.
1529            let trimmed = line.trim();
1530            if !trimmed.ends_with(';') {
1531                continue;
1532            }
1533            let Some((_, value)) = trimmed.split_once(": ") else {
1534                continue;
1535            };
1536            if value.contains("var(--") {
1537                continue;
1538            }
1539            // Everything left has to be a keyword, a number or a
1540            // caller-supplied length, never a colour.
1541            //
1542            // The length arm is what the comment above always claimed and the
1543            // list never covered: `border_width` arrives from `Emit` and lands
1544            // bare in the focus ring's offset, where the bevel had only ever
1545            // used it inside an `inset` shadow.
1546            let opts = Emit::default();
1547            assert!(
1548                value.contains("inset")
1549                    || value.contains(opts.border_width)
1550                    || value.contains(opts.focus_width)
1551                    // 0.12.0's two: a sortable header is a control and says so
1552                    // with the pointer, and the caret is this renderer's own
1553                    // expression of `aria-sort`. Neither is a colour, which is
1554                    // what this test is actually about, and neither is a size,
1555                    // which is the other thing this crate must not name.
1556                    || value.starts_with("\"\\2")
1557                    || matches!(
1558                        value.trim_end_matches(';'),
1559                        "0" | "1" | "none" | "auto" | "not-allowed" | "pointer"
1560                    ),
1561                "unrecognised literal value: {line}"
1562            );
1563        }
1564    }
1565
1566    #[test]
1567    fn flat_emits_nothing_at_all() {
1568        assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
1569        assert!(!depth_rules(&Emit::default()).contains("flat"));
1570    }
1571
1572    #[test]
1573    fn a_prefix_namespaces_every_class() {
1574        let opts = Emit {
1575            class_prefix: "mo-",
1576            ..Emit::default()
1577        };
1578        let css = depth_rules(&opts);
1579        assert!(css.contains(".mo-raised {"));
1580        assert!(css.contains(".mo-well {"));
1581        assert!(!css.contains(".raised {"));
1582    }
1583
1584    #[test]
1585    fn the_border_width_is_the_callers() {
1586        let opts = Emit {
1587            border_width: "2px",
1588            ..Emit::default()
1589        };
1590        assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
1591    }
1592
1593    #[test]
1594    fn edges_agree_with_the_description() {
1595        // Not a tautology: it is the guard that a CSS-shaped convenience never
1596        // quietly reverses which side is lit.
1597        let (tl, br) = Bevel::Raised.edges();
1598        assert_eq!(tl.token(), Edge::Light.token());
1599        assert_eq!(br.token(), Edge::Dark.token());
1600    }
1601}