Skip to main content

makeover_webview/
lib.rs

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