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