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