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