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