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