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