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