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