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