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