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 only
19//!
20//! This emits component CSS and no markup, deliberately. GoingsOn has 145
21//! `innerHTML` sites and Balanced Breakfast 175 `createElement` sites; moving
22//! markup is a migration, while adopting a generated stylesheet is a deletion.
23//! The apps keep every line of their markup and gain the classes.
24//!
25//! The bevel properties are byte-identical to what both apps already
26//! hand-write, which is asserted below.
27//!
28//! # What phase A settled, and what it costs
29//!
30//! Decided 2026-07-29 against goingson's `styles.css` rather than against a
31//! component list. The useful finding there was that `.btn` (line 644),
32//! `.card` (768) and `.tag, .badge` (882) each hand-write the same
33//! composition, so three quarters of phase A is one rule with several names.
34//!
35//! Two of the four decisions change how goingson looks, and adoption should
36//! not be described as a pure deletion:
37//!
38//! - **Pressed carries its fill.** [`interactive_rules`] emits
39//!   [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
40//!   will press to `--surface-well`, and hovers to `--surface-overlay` today
41//!   and will hover to `--hover-surface`. Since `surface-well` inverts by theme
42//!   where `surface-sunken` does not, a dark theme presses *lighter* than it
43//!   hovers. That falls out of `makeover`'s own derivation, which says outright
44//!   that `surface-sunken` cannot serve as a well, so if it reads wrong the
45//!   answer is there and not here.
46//! - **Badges go flat.** See [`token_rules`].
47//!
48//! The other two: the progress trough is renderer-local and the scrollbar
49//! track was dropped ([`component_rules`]), and no class prefix ships by
50//! default, so adoption means deleting the app's hand-written rule in the same
51//! commit that adds the generated one. `.card`, `.badge` and the tab classes
52//! all already exist in goingson, and while both rules exist the cascade order
53//! decides which wins. That is the one real risk in adopting this, and it is
54//! why the migration lands per component rather than in one commit.
55//!
56//! # Substitution, three ways
57//!
58//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
59//! answers that differently, which is the evidence that dropping
60//! `Fill::fallback` from the description was right:
61//!
62//! - `makeover-immediate` substitutes the page in Rust.
63//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
64//!   terminal would quantise the two together.
65//! - here, CSS already has the mechanism: `var(--surface-well,
66//!   var(--surface-page))` falls back in the browser, and nothing in Rust
67//!   decides anything.
68
69#![forbid(unsafe_code)]
70
71use makeover_layout::{Bevel, Depth, Fill, Intent, RowPart, Selector, Token, Tone};
72use std::fmt::Write as _;
73
74/// How the emitted CSS is shaped.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Emit {
77    /// Bevel thickness, as a CSS length.
78    ///
79    /// A value, so it arrives from the caller: border widths belong to
80    /// `makeover-geometry` and will come from there once it carries them.
81    pub border_width: &'static str,
82    /// Prefix for emitted class names, without the leading dot.
83    pub class_prefix: &'static str,
84}
85
86impl Default for Emit {
87    fn default() -> Self {
88        Self {
89            border_width: "1px",
90            class_prefix: "",
91        }
92    }
93}
94
95/// The CSS custom property holding a bevel's composition.
96#[must_use]
97pub fn bevel_var(bevel: Bevel) -> &'static str {
98    match bevel {
99        Bevel::Raised => "--bevel-raised",
100        Bevel::Inset => "--bevel-inset",
101    }
102}
103
104/// A `var()` reference to a fill intent, with the browser's own fallback where
105/// the intent may be absent.
106///
107/// The fallback is CSS syntax, not a decision made here. That is the whole
108/// difference between this renderer and the other two.
109#[must_use]
110pub fn fill_var(fill: Fill) -> String {
111    match fill {
112        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
113        other => format!("var(--{})", other.token()),
114    }
115}
116
117/// The two-tone edge as a `box-shadow` value.
118///
119/// Two inset shadows, one per corner pair: the light one offset down and
120/// right so it lands on the top and left edges, the dark one the other way.
121/// The same assignment `makeover-immediate` draws with polylines and
122/// `makeover-tui` draws with box-drawing characters.
123#[must_use]
124pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
125    let (top_left, bottom_right) = bevel.edges();
126    let w = opts.border_width;
127    format!(
128        "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
129        top_left.token(),
130        bottom_right.token()
131    )
132}
133
134/// The custom properties both bevels resolve through.
135///
136/// Emitted as properties rather than inlined into every rule because that is
137/// what the apps already do, and because a consumer that wants the edge
138/// without the fill reads the property directly.
139#[must_use]
140pub fn bevel_properties(opts: &Emit) -> String {
141    let mut css = String::new();
142    for bevel in [Bevel::Raised, Bevel::Inset] {
143        let _ = writeln!(
144            css,
145            "    {}: {};",
146            bevel_var(bevel),
147            bevel_shadow(bevel, opts)
148        );
149    }
150    css
151}
152
153/// The class name for a depth.
154#[must_use]
155pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
156    let name = match depth {
157        Depth::Flat => return None,
158        Depth::Raised => "raised",
159        Depth::Well => "well",
160        Depth::Sunken => "sunken",
161    };
162    Some(format!("{}{name}", opts.class_prefix))
163}
164
165/// A prefixed class name.
166fn class(name: &str, opts: &Emit) -> String {
167    format!("{}{name}", opts.class_prefix)
168}
169
170/// The fill and edge declarations for a depth, as a rule body.
171///
172/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
173/// Callers lean on the emptiness to skip the rule rather than emit a class that
174/// sets nothing: a class that sets no properties is a class that means "I
175/// thought about this", which is what comments are for.
176///
177/// The two halves are emitted independently because [`Depth::Sunken`] has a
178/// fill and no bevel. Requiring both, which this did before makeover-layout
179/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
180/// mean unpaired: both halves still come off one `Depth`, so they cannot
181/// disagree about what the region is.
182#[must_use]
183pub fn depth_declarations(depth: Depth) -> String {
184    let mut css = String::new();
185    if let Some(fill) = depth.fill() {
186        let _ = writeln!(css, "    background: {};", fill_var(fill));
187    }
188    if let Some(bevel) = depth.bevel() {
189        let _ = writeln!(css, "    box-shadow: var({});", bevel_var(bevel));
190    }
191    css
192}
193
194/// One rule giving a selector a depth, or nothing when the depth declares
195/// nothing.
196#[must_use]
197pub fn depth_rule(selector: &str, depth: Depth) -> String {
198    let body = depth_declarations(depth);
199    if body.is_empty() {
200        return String::new();
201    }
202    format!(".{selector} {{\n{body}}}\n")
203}
204
205/// Hover and pressed, for a selector that answers a click.
206///
207/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
208/// only the edge is what left goingson hand-writing `background:
209/// var(--surface-sunken)` on three separate rules, and a fill that does not
210/// travel with its edge is precisely the disagreement `Depth` exists to make
211/// unrepresentable. So the pressed fill comes from the description
212/// (`--surface-well`) rather than from whatever each app reached for.
213///
214/// Hover has no member in the description and is renderer policy: a terminal
215/// and an immediate-mode painter have no hover to express. It resolves against
216/// `--hover-surface`, which `makeover` already derives and which nothing
217/// consumed until now.
218#[must_use]
219pub fn interactive_rules(selector: &str) -> String {
220    format!(
221        ".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n{}",
222        depth_rule(&format!("{selector}:active"), Depth::Raised.pressed())
223    )
224}
225
226/// One rule per depth: its fill and its edge, together.
227///
228/// A pressed rule rides along with the raised one, because the cascade can
229/// carry a state that an immediate-mode renderer has to resolve per call site.
230/// That is the one thing this renderer gets for free and the others do not.
231#[must_use]
232pub fn depth_rules(opts: &Emit) -> String {
233    let mut css = String::new();
234    for depth in [Depth::Raised, Depth::Well] {
235        let Some(class) = depth_class(depth, opts) else {
236            continue;
237        };
238        css.push_str(&depth_rule(&class, depth));
239    }
240    if let Some(raised) = depth_class(Depth::Raised, opts) {
241        css.push_str(&interactive_rules(&raised));
242    }
243    css
244}
245
246/// The three surfaces that are a depth with a name.
247///
248/// `button` and `card` are both [`Depth::Raised`], and `field` is a
249/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
250/// gives a text field. Their bodies come out identical by construction rather
251/// than by hand: three hand-written copies in goingson's stylesheet is what
252/// phase A deletes, and generating them from one call is what stops them
253/// drifting apart again.
254fn surface_rules(opts: &Emit) -> String {
255    let mut css = String::new();
256    for name in ["button", "card"] {
257        let c = class(name, opts);
258        css.push_str(&depth_rule(&c, Depth::Raised));
259        css.push_str(&interactive_rules(&c));
260    }
261
262    let field = class("field", opts);
263    css.push_str(&depth_rule(&field, Depth::Well));
264
265    // Keyed on the ARIA attribute rather than on a class, so the visual state
266    // and the accessible state cannot drift apart: there is one fact and both
267    // read it. goingson already drove its invalid styling this way and was
268    // right to; the `.invalid` class this emitted before 0.5.0 was a second
269    // place to forget.
270    //
271    // The ring composes *after* the bevel rather than replacing it. box-shadow
272    // is not additive, so a lone ring silently dropped the well out from under
273    // an invalid field. Flat and unlit: this edge is saying "wrong", and
274    // lighting one side would have it say "raised" at the same time.
275    let _ = writeln!(
276        css,
277        ".{field}[aria-invalid=\"true\"] {{\n    box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
278        bevel_var(Bevel::Inset),
279        opts.border_width
280    );
281    css
282}
283
284/// Badges and chips.
285///
286/// The one place phase A changes how goingson looks rather than only where its
287/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
288/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
289/// carrying the raised bevel. Splitting that means reading every call site to
290/// decide which of the two it always was.
291///
292/// What a badge does carry is a [`Tone`], the intent family it shares with
293/// notices and nothing else. Neutral is the bare class rather than a variant,
294/// because it is the absence of a status and not a status called "none".
295fn token_rules(opts: &Emit) -> String {
296    let mut css = String::new();
297
298    // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
299    // and a label with an edge says it can be pressed.
300    let badge = class("badge", opts);
301    let _ = writeln!(
302        css,
303        ".{badge} {{\n    color: var(--{});\n}}",
304        Tone::Neutral.token()
305    );
306    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
307        let _ = writeln!(
308            css,
309            ".{badge}[data-tone=\"{0}\"] {{\n    color: var(--{0});\n}}",
310            tone.token()
311        );
312    }
313
314    // A chip holds itself down, which is `Depth::pressed` arrived at
315    // independently by two apps. `removable` is a remove affordance, so it is
316    // markup and waits for phase B.
317    let chip = class("chip", opts);
318    let unlatched = Token::Chip { removable: false };
319    css.push_str(&depth_rule(&chip, unlatched.depth(false)));
320    css.push_str(&interactive_rules(&chip));
321    css.push_str(&depth_rule(
322        &format!("{chip}.latched"),
323        unlatched.depth(true),
324    ));
325    css
326}
327
328/// The three selectors, each named by what it picks.
329///
330/// A tab comes *forward* to join the pane it opens, which is why
331/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
332/// are held in. That is the folder semantic, and it is the whole reason the
333/// three are not one member with a flag.
334///
335/// [`Selector::abutting`] is not emitted: whether the options touch is
336/// spacing, and spacing is `makeover-geometry`'s question to answer.
337///
338/// Both states emit as of makeover-layout 0.3.0. Before it the description
339/// named only the chosen option, so an unchosen one fell through to
340/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
341/// strip hand-writing the recess that makes its chosen tab read as forward.
342fn selector_rules(opts: &Emit) -> String {
343    let mut css = String::new();
344    for (selector, name) in [
345        (Selector::Tabs, "tab"),
346        (Selector::Segmented, "segment"),
347        (Selector::Toggle, "toggle"),
348    ] {
349        let c = class(name, opts);
350        css.push_str(&depth_rule(&c, selector.unchosen()));
351        css.push_str(&interactive_rules(&c));
352        css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
353    }
354    css
355}
356
357/// The four parts of a list row.
358fn row_rules(opts: &Emit) -> String {
359    let mut css = String::new();
360    let row = class("row", opts);
361    for part in [
362        RowPart::Primary,
363        RowPart::Secondary,
364        RowPart::Meta,
365        RowPart::Actions,
366    ] {
367        let name = match part {
368            RowPart::Primary => "row-primary",
369            RowPart::Secondary => "row-secondary",
370            RowPart::Meta => "row-meta",
371            RowPart::Actions => "row-actions",
372        };
373        let c = class(name, opts);
374
375        // Actions carry controls rather than text, and `RowPart::intent` says
376        // so by returning the same intent inheriting already gives. Pinning it
377        // would be louder than saying nothing.
378        if !matches!(part, RowPart::Actions) {
379            let _ = writeln!(css, ".{c} {{\n    color: var(--{});\n}}", part.intent());
380        }
381
382        if part.revealed_on_hover() {
383            // Hidden rather than absent: the row must not change height when
384            // the pointer arrives. `focus-within` carries the keyboard, which
385            // hover on its own would lock out.
386            //
387            // Transparent rather than `visibility: hidden`, which was the first
388            // form and defeated the very escape above: a `visibility: hidden`
389            // element is out of the focus order and out of the accessibility
390            // tree, so tabbing could never reach an action and could never
391            // trigger the row's `focus-within`. goingson had reached the same
392            // opacity form independently, on its own comment "always in the DOM
393            // for keyboard and screen readers".
394            //
395            // `pointer-events` rides along because opacity leaves the hit area
396            // behind: without it a renderer with no hover carries an invisible
397            // tappable control. Keyboard focus is unaffected by it.
398            let _ = writeln!(
399                css,
400                ".{c} {{\n    opacity: 0;\n    pointer-events: none;\n}}"
401            );
402            let _ = writeln!(
403                css,
404                ".{row}:hover .{c},\n.{row}:focus-within .{c} {{\n    opacity: 1;\n    pointer-events: auto;\n}}"
405            );
406        }
407    }
408    css
409}
410
411/// The progress trough, which has nothing behind it in the description.
412///
413/// Renderer-local chrome, on the same licence the skeletons hold as the
414/// webview's expression of `Readiness::Pending`: a determinate bar is a shape
415/// CSS draws readily and a terminal would rather not be told about. It earns
416/// the place empirically, goingson having grown four independent progress bars
417/// before anything named one.
418///
419/// The trough is a [`Depth::Well`], the same reading a text field gets:
420/// something with its content down inside it.
421fn progress_rules(opts: &Emit) -> String {
422    let progress = class("progress", opts);
423    // `progress-fill` rather than a bare `fill`: an unprefixed build claims
424    // these names in the app's own stylesheet, and `.fill` is grabby enough to
425    // catch things that have nothing to do with progress. goingson already
426    // calls it `.progress-fill`, so this is also the name that deletes.
427    let fill = class("progress-fill", opts);
428    let mut css = depth_rule(&progress, Depth::Well);
429
430    // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
431    // place this differs from the badge rules, and deliberately: a badge with
432    // no status is a muted label, while a bar with no status is still
433    // reporting progress, and `content-muted` would read as disabled.
434    let _ = writeln!(
435        css,
436        ".{progress} > .{fill} {{\n    background: var(--action);\n}}"
437    );
438
439    // A bar can be saying something, same as a badge: goingson colours subtask
440    // progress as success and an over-estimate as danger, which is real
441    // information rather than decoration. Emitting the tones is what lets that
442    // survive adoption instead of staying hand-written.
443    for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
444        let _ = writeln!(
445            css,
446            ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n    background: var(--{0});\n}}",
447            tone.token()
448        );
449    }
450    css
451}
452
453/// The component layer: every named thing phase A emits.
454///
455/// No scrollbar track. It was on the phase A list and came off: eight lines of
456/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
457/// would want handed to it, so it stays with the apps.
458#[must_use]
459pub fn component_rules(opts: &Emit) -> String {
460    let mut css = String::new();
461    css.push_str(&surface_rules(opts));
462    css.push_str(&token_rules(opts));
463    css.push_str(&selector_rules(opts));
464    css.push_str(&row_rules(opts));
465    css.push_str(&progress_rules(opts));
466    css
467}
468
469/// The whole phase-A stylesheet: properties, depth rules and components, with
470/// a generated-file banner.
471#[must_use]
472pub fn stylesheet(opts: &Emit) -> String {
473    format!(
474        "/* Generated by makeover-webview from makeover-layout. Do not edit.\n   \
475         Depth is a fill and an edge together; naming them apart is what let\n   \
476         them disagree. See the crate's README and wiki note makeover-layout. */\n\
477         :root {{\n{}}}\n\n{}\n{}",
478        bevel_properties(opts),
479        depth_rules(opts),
480        component_rules(opts)
481    )
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487    use makeover_layout::Edge;
488
489    #[test]
490    fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
491        // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
492        // deletion, not a redesign, or nobody will take it.
493        let opts = Emit::default();
494        assert_eq!(
495            bevel_shadow(Bevel::Raised, &opts),
496            "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
497        );
498        assert_eq!(
499            bevel_shadow(Bevel::Inset, &opts),
500            "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
501        );
502    }
503
504    #[test]
505    fn no_colour_ever_reaches_the_output() {
506        let css = stylesheet(&Emit::default());
507        assert!(!css.contains('#'), "a hex literal escaped into the CSS");
508        assert!(
509            !css.contains("rgb"),
510            "a colour function escaped into the CSS"
511        );
512        // Every colour is named, never resolved.
513        assert!(css.contains("var(--surface-raised)"));
514        assert!(css.contains("var(--bevel-light)"));
515    }
516
517    #[test]
518    fn a_well_falls_back_through_css_rather_than_through_rust() {
519        assert_eq!(
520            fill_var(Fill::Well),
521            "var(--surface-well, var(--surface-page))"
522        );
523        // Nothing else needs one.
524        assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
525        assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
526    }
527
528    #[test]
529    fn raised_and_well_do_not_collapse_onto_each_other() {
530        let css = depth_rules(&Emit::default());
531        assert!(css.contains(".raised {"));
532        assert!(css.contains(".well {"));
533        assert!(css.contains("var(--bevel-raised)"));
534        assert!(css.contains("var(--bevel-inset)"));
535    }
536
537    #[test]
538    fn the_cascade_carries_the_pressed_state() {
539        let css = depth_rules(&Emit::default());
540        // The one thing this renderer gets free that the other two resolve by
541        // hand, eighteen call sites deep in audiofiles' case.
542        assert!(css.contains(".raised:active {"));
543    }
544
545    #[test]
546    fn pressing_moves_the_fill_and_not_only_the_edge() {
547        // The decision-1 guard, and the regression that mattered: emitting the
548        // bevel flip alone is what left goingson hand-writing `background:
549        // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
550        // of the three could be deleted.
551        let pressed = interactive_rules("button");
552        assert!(pressed.contains(".button:active {"));
553        assert!(
554            pressed.contains("background: var(--surface-well, var(--surface-page))"),
555            "pressed dropped its fill: {pressed}"
556        );
557        assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
558    }
559
560    #[test]
561    fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
562        // goingson presses to --surface-sunken. The description says a pressed
563        // raised region reads as a well, and makeover says outright that
564        // surface-sunken cannot serve as one, so the app is the thing that
565        // moves.
566        //
567        // Scoped to the pressed rules rather than to the whole sheet: since
568        // makeover-layout 0.3.0 an unchosen tab is legitimately
569        // --surface-sunken, so the token appearing somewhere in the output no
570        // longer means the app's choice leaked in.
571        let css = stylesheet(&Emit::default());
572        let mut checked = 0;
573        for rule in css.split("}\n") {
574            if !rule.contains(":active") {
575                continue;
576            }
577            checked += 1;
578            assert!(
579                !rule.contains("surface-sunken"),
580                "a pressed rule took the app's fill: {rule}"
581            );
582        }
583        assert!(checked > 0, "no pressed rules found to check");
584        assert_eq!(
585            Depth::Raised.pressed().fill(),
586            Some(Fill::Well),
587            "the description changed under us"
588        );
589    }
590
591    #[test]
592    fn hover_resolves_against_the_token_makeover_already_derives() {
593        let css = interactive_rules("card");
594        assert!(css.contains(".card:hover {"));
595        assert!(css.contains("background: var(--hover-surface)"));
596        // Not the app's choice, which was --surface-overlay.
597        assert!(!css.contains("surface-overlay"));
598    }
599
600    #[test]
601    fn a_badge_gets_no_edge_and_no_fill() {
602        // Decision 2, and the one visible redesign in phase A. Token::Badge is
603        // Flat: an edge on a label says it can be pressed.
604        let css = token_rules(&Emit::default());
605        let badge = css
606            .lines()
607            .skip_while(|l| !l.starts_with(".badge {"))
608            .take_while(|l| !l.starts_with('}'))
609            .collect::<Vec<_>>()
610            .join("\n");
611        assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
612        assert!(!badge.contains("background"), "badge kept a fill: {badge}");
613        assert_eq!(Token::Badge.depth(false), Depth::Flat);
614        assert_eq!(Token::Badge.depth(true), Depth::Flat);
615    }
616
617    #[test]
618    fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
619        let css = token_rules(&Emit::default());
620        // Neutral is the absence of a status, not a status named "none".
621        assert!(css.contains(".badge {\n    color: var(--content-muted);"));
622        assert!(!css.contains("data-tone=\"content-muted\""));
623        for tone in ["info", "success", "warning", "danger"] {
624            assert!(
625                css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
626                "missing tone {tone}"
627            );
628            assert!(css.contains(&format!("color: var(--{tone})")));
629        }
630    }
631
632    #[test]
633    fn a_chip_is_raised_and_latches_into_a_well() {
634        let css = token_rules(&Emit::default());
635        assert!(css.contains(".chip {"));
636        assert!(css.contains(".chip.latched {"));
637        assert!(css.contains(".chip:active {"));
638        // The whole difference from a badge: it answers a click.
639        assert!(Token::Chip { removable: false }.interactive());
640        assert!(!Token::Badge.interactive());
641    }
642
643    #[test]
644    fn only_a_tab_comes_forward_when_chosen() {
645        // The folder semantic. Collapsing the three selectors would lose it.
646        let css = selector_rules(&Emit::default());
647        assert!(css.contains(".tab.chosen {"));
648        assert!(css.contains(".segment.chosen {"));
649        assert!(css.contains(".toggle.chosen {"));
650        assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
651        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
652        assert_eq!(Selector::Toggle.chosen(), Depth::Well);
653
654        let tab = css
655            .lines()
656            .skip_while(|l| !l.starts_with(".tab.chosen {"))
657            .take_while(|l| !l.starts_with('}'))
658            .collect::<Vec<_>>()
659            .join("\n");
660        assert!(tab.contains("var(--bevel-raised)"), "tab was held in: {tab}");
661    }
662
663    #[test]
664    fn an_unchosen_tab_recedes_without_looking_picked() {
665        let css = selector_rules(&Emit::default());
666        // Recessed by colour and given no edge. An edge would make every option
667        // look picked; flat would leave the chosen one nothing to come forward
668        // from, which is the gap makeover-layout 0.3.0 closed.
669        assert!(
670            css.contains(".tab {\n    background: var(--surface-sunken);\n}"),
671            "unchosen tab is not recessed: {css}"
672        );
673        assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
674        assert!(css.contains(".tab:hover {"));
675    }
676
677    #[test]
678    fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
679        // The inverse of the tab, and why the three selectors are not one
680        // member with a flag.
681        let css = selector_rules(&Emit::default());
682        assert!(css.contains(".segment {\n    background: var(--surface-raised);"));
683        assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
684        assert_eq!(Selector::Segmented.chosen(), Depth::Well);
685    }
686
687    #[test]
688    fn row_actions_are_revealed_without_moving_the_row() {
689        let css = row_rules(&Emit::default());
690        assert!(css.contains(".row-actions {\n    opacity: 0;"));
691        // Not display:none, which would reflow the row under the pointer.
692        assert!(!css.contains("display: none"));
693        // Hover alone would lock the keyboard out.
694        assert!(css.contains(".row:focus-within .row-actions"));
695        assert!(RowPart::Actions.revealed_on_hover());
696    }
697
698    #[test]
699    fn a_hidden_row_action_is_still_focusable_and_not_tappable() {
700        let css = row_rules(&Emit::default());
701        // `visibility: hidden` takes the actions out of the focus order, so the
702        // `focus-within` reveal above could never fire from an action itself.
703        assert!(!css.contains("visibility:"));
704        // Opacity leaves the hit area behind; the row must not carry an
705        // invisible tappable control where there is no hover to reveal it.
706        assert!(css.contains(".row-actions {\n    opacity: 0;\n    pointer-events: none;\n}"));
707        assert!(css.contains("opacity: 1;\n    pointer-events: auto;"));
708    }
709
710    #[test]
711    fn the_three_text_parts_take_their_intents_and_actions_inherits() {
712        let css = row_rules(&Emit::default());
713        assert!(css.contains(".row-primary {\n    color: var(--content);"));
714        assert!(css.contains(".row-secondary {\n    color: var(--content-secondary);"));
715        assert!(css.contains(".row-meta {\n    color: var(--content-muted);"));
716        // Actions carry controls, not text. Pinning the colour it would inherit
717        // anyway is louder than saying nothing.
718        assert!(!css.contains(".row-actions {\n    color:"));
719    }
720
721    #[test]
722    fn the_progress_trough_is_a_well() {
723        let css = progress_rules(&Emit::default());
724        assert!(css.contains(".progress {"));
725        assert!(css.contains("box-shadow: var(--bevel-inset)"));
726        assert!(css.contains(".progress > .progress-fill {"));
727        assert!(css.contains("background: var(--action)"));
728        // A bare `.fill` would catch things that have nothing to do with
729        // progress once the sheet lands unprefixed.
730        assert!(!css.contains("> .fill "));
731    }
732
733    #[test]
734    fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
735        let css = progress_rules(&Emit::default());
736        // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
737        // status is still reporting progress, and muted would read as disabled.
738        assert!(css.contains(".progress > .progress-fill {\n    background: var(--action);"));
739        assert!(!css.contains("progress-fill {\n    color: var(--content-muted)"));
740        for tone in ["info", "success", "warning", "danger"] {
741            assert!(
742                css.contains(&format!(
743                    ".progress > .progress-fill[data-tone=\"{tone}\"]"
744                )),
745                "missing progress tone {tone}"
746            );
747        }
748        // goingson's two live cases, which is why the tones are emitted at all.
749        assert!(css.contains("[data-tone=\"success\"] {\n    background: var(--success);"));
750        assert!(css.contains("[data-tone=\"danger\"] {\n    background: var(--danger);"));
751    }
752
753    #[test]
754    fn no_scrollbar_track_is_emitted() {
755        // Decision 3's negative half. It was on the phase A list and came off;
756        // this is what stops it drifting back in.
757        let css = stylesheet(&Emit::default());
758        assert!(!css.contains("scrollbar"));
759        assert!(!css.contains("::-webkit"));
760    }
761
762    #[test]
763    fn an_invalid_field_is_ringed_without_being_lit() {
764        let css = surface_rules(&Emit::default());
765        assert!(css.contains(".field {"));
766        // The ARIA attribute, not a class: one fact, read by both the visual
767        // and the accessible state, so they cannot drift.
768        assert!(css.contains(".field[aria-invalid=\"true\"] {"));
769        assert!(!css.contains(".field.invalid"));
770        // A flat ring: this edge says "wrong", and a two-tone bevel would have
771        // it say "raised" at the same time.
772        assert!(css.contains("0 0 0 1px var(--danger)"));
773    }
774
775    #[test]
776    fn an_invalid_field_keeps_the_well_underneath_it() {
777        // box-shadow is not additive. A lone ring replaces the bevel and drops
778        // the well out from under the field, which is what this emitted before
779        // 0.5.0 and is the whole reason the rule composes.
780        let css = surface_rules(&Emit::default());
781        let invalid = css
782            .lines()
783            .skip_while(|l| !l.starts_with(".field[aria-invalid"))
784            .take_while(|l| !l.starts_with('}'))
785            .collect::<Vec<_>>()
786            .join("\n");
787        assert!(
788            invalid.contains("var(--bevel-inset)"),
789            "the well was dropped: {invalid}"
790        );
791        assert!(invalid.contains("var(--danger)"));
792    }
793
794    #[test]
795    fn button_and_card_come_out_identical_by_construction() {
796        // The duplication phase A deletes. They are the same composition, so
797        // the only honest way to emit both is from one call.
798        let opts = Emit::default();
799        let css = surface_rules(&opts);
800        assert_eq!(
801            depth_declarations(Depth::Raised),
802            depth_declarations(Depth::Raised)
803        );
804        assert!(css.contains(".button {"));
805        assert!(css.contains(".card {"));
806        assert_eq!(
807            interactive_rules("button").replace("button", "card"),
808            interactive_rules("card")
809        );
810    }
811
812    #[test]
813    fn a_prefix_reaches_the_component_classes_too() {
814        let opts = Emit {
815            class_prefix: "mo-",
816            ..Emit::default()
817        };
818        let css = stylesheet(&opts);
819        for name in [
820            "mo-button",
821            "mo-card",
822            "mo-field",
823            "mo-badge",
824            "mo-chip",
825            "mo-tab",
826            "mo-row-primary",
827            "mo-progress",
828            "mo-progress-fill",
829        ] {
830            assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
831        }
832        // The bare names must be gone entirely, or a prefixed build still
833        // collides with the app's own stylesheet.
834        assert!(!css.contains(".button {"));
835        assert!(!css.contains(".card {"));
836        assert!(!css.contains(".badge {"));
837    }
838
839    #[test]
840    fn the_whole_sheet_still_names_every_colour() {
841        // The crate's founding property, asserted over the component layer and
842        // not only the primitives.
843        let css = stylesheet(&Emit::default());
844        assert!(!css.contains('#'));
845        assert!(!css.contains("rgb"));
846        for line in css.lines() {
847            // Declarations only: a selector or an at-rule can carry a colon of
848            // its own (`:root`, `:hover`) and declares nothing.
849            let declaration = line.strip_prefix("    ").map(str::trim);
850            let Some(Some((_, value))) = declaration.map(|d| d.split_once(": ")) else {
851                continue;
852            };
853            if value.contains("var(--") {
854                continue;
855            }
856            // Everything left has to be a keyword, a number or a
857            // caller-supplied length, never a colour.
858            assert!(
859                value.contains("inset")
860                    || matches!(value.trim_end_matches(';'), "0" | "1" | "none" | "auto"),
861                "unrecognised literal value: {line}"
862            );
863        }
864    }
865
866    #[test]
867    fn flat_emits_nothing_at_all() {
868        assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
869        assert!(!depth_rules(&Emit::default()).contains("flat"));
870    }
871
872    #[test]
873    fn a_prefix_namespaces_every_class() {
874        let opts = Emit {
875            class_prefix: "mo-",
876            ..Emit::default()
877        };
878        let css = depth_rules(&opts);
879        assert!(css.contains(".mo-raised {"));
880        assert!(css.contains(".mo-well {"));
881        assert!(!css.contains(".raised {"));
882    }
883
884    #[test]
885    fn the_border_width_is_the_callers() {
886        let opts = Emit {
887            border_width: "2px",
888            ..Emit::default()
889        };
890        assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
891    }
892
893    #[test]
894    fn edges_agree_with_the_description() {
895        // Not a tautology: it is the guard that a CSS-shaped convenience never
896        // quietly reverses which side is lit.
897        let (tl, br) = Bevel::Raised.edges();
898        assert_eq!(tl.token(), Edge::Light.token());
899        assert_eq!(br.token(), Edge::Dark.token());
900    }
901}