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 // The hide is gated too, which it was not in 0.10.0, and that was
664 // an incomplete capability answer rather than a deliberate one.
665 // Ungated, a fingertip got actions hidden with no hover to bring
666 // them back, so both webview apps hand-wrote the same
667 // `opacity: 1` to undo it: goingson in its touch block and
668 // Balanced Breakfast in its own. A primitive that owns the hiding
669 // owes the answer for the device that cannot unhide, and the
670 // answer both consumers already reached is not to hide at all.
671 css.push_str(&gated(
672 hover_condition(),
673 &format!(".{c} {{\n opacity: 0;\n pointer-events: none;\n}}\n"),
674 ));
675
676 // The two halves split here, where they used to be one selector
677 // list. Hover-to-reveal is the literal case `Affordance::Hover`
678 // was written from, and on a touchscreen it does not fail
679 // gracefully: the actions are simply unreachable, because there
680 // is no pointer to bring them back. So the hover half is gated
681 // and the app owes those rows another way in.
682 //
683 // `focus-within` stays outside the query. A touchscreen device
684 // with a keyboard attached is a real thing, and it is the one
685 // path to these actions that survives the gate.
686 let revealed = " opacity: 1;\n pointer-events: auto;\n";
687 css.push_str(&gated(
688 hover_condition(),
689 &format!(".{row}:hover .{c} {{\n{revealed}}}\n"),
690 ));
691 let _ = write!(css, ".{row}:focus-within .{c} {{\n{revealed}}}\n");
692 }
693 }
694 css
695}
696
697/// The progress trough, which has nothing behind it in the description.
698///
699/// Renderer-local chrome, on the same licence the skeletons hold as the
700/// webview's expression of `Readiness::Pending`: a determinate bar is a shape
701/// CSS draws readily and a terminal would rather not be told about. It earns
702/// the place empirically, goingson having grown four independent progress bars
703/// before anything named one.
704///
705/// The trough is a [`Depth::Well`], the same reading a text field gets:
706/// something with its content down inside it.
707fn progress_rules(opts: &Emit) -> String {
708 let progress = class("progress", opts);
709 // `progress-fill` rather than a bare `fill`: an unprefixed build claims
710 // these names in the app's own stylesheet, and `.fill` is grabby enough to
711 // catch things that have nothing to do with progress. goingson already
712 // calls it `.progress-fill`, so this is also the name that deletes.
713 let fill = class("progress-fill", opts);
714 let mut css = depth_rule(&progress, Depth::Well);
715
716 // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
717 // place this differs from the badge rules, and deliberately: a badge with
718 // no status is a muted label, while a bar with no status is still
719 // reporting progress, and `content-muted` would read as disabled.
720 let _ = writeln!(
721 css,
722 ".{progress} > .{fill} {{\n background: var(--action);\n}}"
723 );
724
725 // A bar can be saying something, same as a badge: goingson colours subtask
726 // progress as success and an over-estimate as danger, which is real
727 // information rather than decoration. Emitting the tones is what lets that
728 // survive adoption instead of staying hand-written.
729 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
730 let _ = writeln!(
731 css,
732 ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n background: var(--{0});\n}}",
733 tone.token()
734 );
735 }
736 css
737}
738
739/// The component layer: every named thing phase A emits.
740///
741/// No scrollbar track. It was on the phase A list and came off: eight lines of
742/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
743/// would want handed to it, so it stays with the apps.
744#[must_use]
745pub fn component_rules(opts: &Emit) -> String {
746 let mut css = String::new();
747 css.push_str(&surface_rules(opts));
748 css.push_str(&token_rules(opts));
749 css.push_str(&selector_rules(opts));
750 css.push_str(&row_rules(opts));
751 css.push_str(&progress_rules(opts));
752 css
753}
754
755/// The whole phase-A stylesheet: properties, depth rules and components, in
756/// [`CSS_LAYER`], under a generated-file banner.
757///
758/// The banner sits outside the layer, because a comment participates in no
759/// cascade and a reader opening the file should see what it is before seeing
760/// an at-rule.
761#[must_use]
762pub fn stylesheet(opts: &Emit) -> String {
763 format!(
764 "/* Generated by makeover-webview from makeover-layout. Do not edit.\n \
765 Depth is a fill and an edge together; naming them apart is what let\n \
766 them disagree. See the crate's README and wiki note makeover-layout.\n\n \
767 Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n \
768 order once in your own stylesheet, or this layer's position is decided\n \
769 by whichever generated file the browser happens to see first:\n\n \
770 @layer {CSS_LAYER}, base, components, responsive; */\n{}",
771 in_css_layer(&format!(
772 ":root {{\n{}}}\n\n{}\n{}",
773 bevel_properties(opts),
774 depth_rules(opts),
775 component_rules(opts)
776 ))
777 )
778}
779
780#[cfg(test)]
781mod tests {
782 use super::*;
783 use makeover_layout::Edge;
784
785 #[test]
786 fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
787 // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
788 // deletion, not a redesign, or nobody will take it.
789 let opts = Emit::default();
790 assert_eq!(
791 bevel_shadow(Bevel::Raised, &opts),
792 "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
793 );
794 assert_eq!(
795 bevel_shadow(Bevel::Inset, &opts),
796 "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
797 );
798 }
799
800 #[test]
801 fn no_colour_ever_reaches_the_output() {
802 let css = stylesheet(&Emit::default());
803 assert!(!css.contains('#'), "a hex literal escaped into the CSS");
804 assert!(
805 !css.contains("rgb"),
806 "a colour function escaped into the CSS"
807 );
808 // Every colour is named, never resolved.
809 assert!(css.contains("var(--surface-raised)"));
810 assert!(css.contains("var(--bevel-light)"));
811 }
812
813 #[test]
814 fn a_well_falls_back_through_css_rather_than_through_rust() {
815 assert_eq!(
816 fill_var(Fill::Well),
817 "var(--surface-well, var(--surface-page))"
818 );
819 // Nothing else needs one.
820 assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
821 assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
822 }
823
824 #[test]
825 fn raised_and_well_do_not_collapse_onto_each_other() {
826 let css = depth_rules(&Emit::default());
827 assert!(css.contains(".raised {"));
828 assert!(css.contains(".well {"));
829 assert!(css.contains("var(--bevel-raised)"));
830 assert!(css.contains("var(--bevel-inset)"));
831 }
832
833 #[test]
834 fn the_cascade_carries_the_pressed_state() {
835 let css = depth_rules(&Emit::default());
836 // The one thing this renderer gets free that the other two resolve by
837 // hand, eighteen call sites deep in audiofiles' case.
838 assert!(css.contains(".raised:active {"));
839 }
840
841 #[test]
842 fn pressing_moves_the_fill_and_not_only_the_edge() {
843 // The decision-1 guard, and the regression that mattered: emitting the
844 // bevel flip alone is what left goingson hand-writing `background:
845 // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
846 // of the three could be deleted.
847 let pressed = interactive_rules("button", Depth::Raised, &Emit::default());
848 assert!(pressed.contains(".button:active {"));
849 assert!(
850 pressed.contains("background: var(--surface-well, var(--surface-page))"),
851 "pressed dropped its fill: {pressed}"
852 );
853 assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
854 }
855
856 #[test]
857 fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
858 // goingson presses to --surface-sunken. The description says a pressed
859 // raised region reads as a well, and makeover says outright that
860 // surface-sunken cannot serve as one, so the app is the thing that
861 // moves.
862 //
863 // Scoped to the pressed rules rather than to the whole sheet: since
864 // makeover-layout 0.3.0 an unchosen tab is legitimately
865 // --surface-sunken, so the token appearing somewhere in the output no
866 // longer means the app's choice leaked in.
867 let css = stylesheet(&Emit::default());
868 let mut checked = 0;
869 for rule in css.split("}\n") {
870 if !rule.contains(":active") {
871 continue;
872 }
873 checked += 1;
874 assert!(
875 !rule.contains("surface-sunken"),
876 "a pressed rule took the app's fill: {rule}"
877 );
878 }
879 assert!(checked > 0, "no pressed rules found to check");
880 assert_eq!(
881 Depth::Raised.pressed().fill(),
882 Some(Fill::Well),
883 "the description changed under us"
884 );
885 }
886
887 #[test]
888 fn the_whole_stylesheet_is_emitted_in_the_family_layer() {
889 // The point of 0.11.0. Unlayered normal declarations outrank every
890 // named layer, so an app declaring `@layer base, components` loses
891 // every rule it owns to this file until this file is layered too.
892 let css = stylesheet(&Emit::default());
893 assert!(css.contains(&format!("@layer {CSS_LAYER} {{")));
894
895 // Exactly one layer block, and nothing outside it but the banner.
896 assert_eq!(css.matches("@layer").count(), 2, "banner names it once");
897 let opened = css.find("@layer makeover {").expect("layer opens");
898 for (i, line) in css.lines().enumerate() {
899 let before_layer = css.lines().take(i).map(str::len).sum::<usize>() < opened;
900 if before_layer || line.is_empty() {
901 continue;
902 }
903 assert!(
904 line.starts_with(" ") || line == "}" || line.starts_with(" "),
905 "line outside the layer: {line:?}"
906 );
907 }
908 }
909
910 #[test]
911 fn the_generated_sheet_carries_no_trailing_whitespace() {
912 // A checked-in generated file that a formatter wants to rewrite is a
913 // diff every time somebody saves it.
914 let css = stylesheet(&Emit::default());
915 for (i, line) in css.lines().enumerate() {
916 assert_eq!(line, line.trim_end(), "trailing whitespace on line {i}");
917 }
918 }
919
920 #[test]
921 fn the_banner_tells_an_app_how_to_order_the_layer() {
922 // Without a declared order the layer's position depends on which
923 // generated file the browser sees first, which is not a contract.
924 let css = stylesheet(&Emit::default());
925 assert!(css.contains("@layer makeover, base, components, responsive;"));
926 // And the banner is outside the layer, not a rule inside it.
927 assert!(css.starts_with("/* Generated by makeover-webview"));
928 }
929
930 #[test]
931 fn a_primitive_owns_every_state_it_implies() {
932 // The whole point of 0.10.0. Anything emitting a hover rule owes the
933 // other three, or the consuming app supplies them by out-specifying a
934 // rule it does not own: 19 such rules in goingson, 21 in the MNW
935 // server, and three focus rings that do not match.
936 let css = stylesheet(&Emit::default());
937 for selector in ["button", "card", "chip", "tab", "segment", "toggle"] {
938 assert!(css.contains(&format!(".{selector}:hover {{")), "{selector}");
939 assert!(css.contains(&format!(".{selector}:active {{")), "{selector}");
940 assert!(
941 css.contains(&format!(".{selector}:focus-visible {{")),
942 "{selector} has no focus ring"
943 );
944 assert!(
945 css.contains(&format!(".{selector}:disabled,")),
946 "{selector} has no disabled state"
947 );
948 }
949 }
950
951 #[test]
952 fn a_field_takes_focus_and_refuses_input_without_taking_a_hover() {
953 // A text field does not light up under the pointer, so it gets the two
954 // states it has and not the two it does not.
955 let css = stylesheet(&Emit::default());
956 assert!(css.contains(".field:focus-visible {"));
957 assert!(css.contains(".field:disabled,"));
958 assert!(!css.contains(".field:hover {"));
959 assert!(!css.contains(".field:active {"));
960 }
961
962 #[test]
963 fn disabled_is_emitted_after_hover_so_source_order_settles_it() {
964 // Every one of these selectors is specificity (0,2,0), so nothing but
965 // order decides which wins. A disabled button taking the hover fill is
966 // the exact bug goingson's `.button:disabled:hover` was written to fix,
967 // and the reason it had to reach (0,3,0) to do it.
968 let css = interactive_rules("button", Depth::Raised, &Emit::default());
969 let hover = css.find(":hover").expect("hover");
970 let active = css.find(":active").expect("active");
971 let focus = css.find(":focus-visible").expect("focus");
972 let disabled = css.find(":disabled").expect("disabled");
973 assert!(hover < active && active < focus && focus < disabled);
974
975 // And it restores the surface, or the hover fill survives underneath.
976 let tail = &css[disabled..];
977 assert!(tail.contains("background: var(--surface-raised)"));
978 }
979
980 #[test]
981 fn a_disabled_state_reaches_things_that_cannot_be_disabled() {
982 // `:disabled` matches form elements only, and a chip is a div. Keying
983 // on the ARIA attribute too is the pattern the invalid field already
984 // set: one fact, read by the styling and the accessibility tree alike.
985 let css = disabled_rule("chip", Depth::Raised);
986 assert!(css.contains(".chip:disabled,"));
987 assert!(css.contains(".chip[aria-disabled=\"true\"]"));
988 assert!(css.contains("cursor: not-allowed"));
989 }
990
991 #[test]
992 fn the_focus_ring_does_not_disturb_the_bevel_it_lands_on() {
993 // `outline` has its own property, so unlike the invalid ring there is
994 // no bevel to restate beside it and nothing to keep in agreement.
995 let opts = Emit::default();
996 let css = focus_rule("button", Depth::Raised, &opts);
997 assert!(css.contains("outline: 2px solid var(--focus-ring)"));
998 assert!(!css.contains("box-shadow"), "the ring restated the bevel");
999 }
1000
1001 #[test]
1002 fn a_well_takes_the_ring_inside_and_a_raised_surface_outside() {
1003 // One ring, placed by depth. The offset comes off `Depth::bevel` and
1004 // not off a per-component choice, which is what gave three apps three
1005 // different rings.
1006 let opts = Emit::default();
1007 assert!(focus_rule("field", Depth::Well, &opts).contains("outline-offset: calc(-1 * 2px)"));
1008 assert!(focus_rule("button", Depth::Raised, &opts).contains("outline-offset: 2px"));
1009 // Nothing to sit inside of, so it sits outside.
1010 assert!(focus_rule("badge", Depth::Sunken, &opts).contains("outline-offset: 2px"));
1011
1012 // And the ring is not the bevel. Reusing border_width emitted a 1px
1013 // ring that every consumer had already overridden.
1014 assert_ne!(opts.focus_width, opts.border_width);
1015 }
1016
1017 #[test]
1018 fn hover_is_gated_on_capability_and_the_keyboard_path_is_not() {
1019 // goingson's section 60 exists only to take back the hover state this
1020 // crate handed it. Gating at the source is what deletes that section
1021 // in all three apps rather than having each fight for it.
1022 let css = stylesheet(&Emit::default());
1023 let condition = format!("@media {}", Density::Pointer.media_condition());
1024 assert!(css.contains(&condition));
1025
1026 // The row reveal splits: hover inside the query, focus-within outside,
1027 // or a touchscreen with a keyboard loses its only way to the actions.
1028 // Compared by indentation rather than by brace-hunting, because both
1029 // sit inside the cascade layer now and every brace is nested.
1030 let indent = |needle: &str| {
1031 let line = css
1032 .lines()
1033 .find(|l| l.contains(needle))
1034 .unwrap_or_else(|| panic!("no line for {needle}"));
1035 line.len() - line.trim_start().len()
1036 };
1037 let hover = indent(".row:hover .row-actions");
1038 let keyboard = indent(".row:focus-within .row-actions");
1039 // The hide is gated with the reveal. Ungated it leaves a fingertip
1040 // with actions it cannot bring back, which is what both webview apps
1041 // were undoing by hand.
1042 let hide = css
1043 .lines()
1044 .position(|l| l.trim() == ".row-actions {")
1045 .expect("hide rule");
1046 let query = css
1047 .lines()
1048 .take(hide)
1049 .enumerate()
1050 .filter(|(_, l)| l.trim_start().starts_with("@media"))
1051 .map(|(i, _)| i)
1052 .last()
1053 .expect("a query precedes it");
1054 assert!(hide - query < 3, "the hide is not inside the query");
1055 assert!(
1056 hover > keyboard,
1057 "hover reveal must be nested inside the capability query and the \
1058 keyboard reveal must not be: hover indent {hover}, keyboard {keyboard}"
1059 );
1060 }
1061
1062 #[test]
1063 fn the_capability_answer_is_asked_for_and_not_assumed() {
1064 // Both halves come from the crates that own them. If `makeover-touch`
1065 // ever says a fingertip has hover, this stops gating on its own.
1066 assert!(!Affordance::Hover.available(Density::Touch, SizeClass::Compact));
1067 assert!(Affordance::Hover.available(Density::Pointer, SizeClass::Compact));
1068 assert_eq!(hover_condition(), Some(Density::Pointer.media_condition()));
1069
1070 // And the size class passed to that call is not a claim about width.
1071 assert!(Affordance::Hover.reads_density());
1072 for size in [SizeClass::Compact, SizeClass::Medium, SizeClass::Expanded] {
1073 assert!(!Affordance::Hover.available(Density::Touch, size));
1074 }
1075 }
1076
1077 #[test]
1078 fn hover_resolves_against_the_token_makeover_already_derives() {
1079 let css = interactive_rules("card", Depth::Raised, &Emit::default());
1080 assert!(css.contains(".card:hover {"));
1081 assert!(css.contains("background: var(--hover-surface)"));
1082 // Not the app's choice, which was --surface-overlay.
1083 assert!(!css.contains("surface-overlay"));
1084 }
1085
1086 #[test]
1087 fn a_badge_gets_no_edge_and_no_fill() {
1088 // Decision 2, and the one visible redesign in phase A. Token::Badge is
1089 // Flat: an edge on a label says it can be pressed.
1090 let css = token_rules(&Emit::default());
1091 let badge = css
1092 .lines()
1093 .skip_while(|l| !l.starts_with(".badge {"))
1094 .take_while(|l| !l.starts_with('}'))
1095 .collect::<Vec<_>>()
1096 .join("\n");
1097 assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
1098 assert!(!badge.contains("background"), "badge kept a fill: {badge}");
1099 assert_eq!(Token::Badge.depth(false), Depth::Flat);
1100 assert_eq!(Token::Badge.depth(true), Depth::Flat);
1101 }
1102
1103 #[test]
1104 fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
1105 let css = token_rules(&Emit::default());
1106 // Neutral is the absence of a status, not a status named "none".
1107 assert!(css.contains(".badge {\n color: var(--content-muted);"));
1108 assert!(!css.contains("data-tone=\"content-muted\""));
1109 for tone in ["info", "success", "warning", "danger"] {
1110 assert!(
1111 css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
1112 "missing tone {tone}"
1113 );
1114 assert!(css.contains(&format!("color: var(--{tone})")));
1115 }
1116 }
1117
1118 #[test]
1119 fn a_chip_is_raised_and_latches_into_a_well() {
1120 let css = token_rules(&Emit::default());
1121 assert!(css.contains(".chip {"));
1122 assert!(css.contains(".chip.latched {"));
1123 assert!(css.contains(".chip:active {"));
1124 // The whole difference from a badge: it answers a click.
1125 assert!(Token::Chip { removable: false }.interactive());
1126 assert!(!Token::Badge.interactive());
1127 }
1128
1129 #[test]
1130 fn only_a_tab_comes_forward_when_chosen() {
1131 // The folder semantic. Collapsing the three selectors would lose it.
1132 let css = selector_rules(&Emit::default());
1133 assert!(css.contains(".tab.chosen {"));
1134 assert!(css.contains(".segment.chosen {"));
1135 assert!(css.contains(".toggle.chosen {"));
1136 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
1137 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1138 assert_eq!(Selector::Toggle.chosen(), Depth::Well);
1139
1140 let tab = css
1141 .lines()
1142 .skip_while(|l| !l.starts_with(".tab.chosen {"))
1143 .take_while(|l| !l.starts_with('}'))
1144 .collect::<Vec<_>>()
1145 .join("\n");
1146 assert!(
1147 tab.contains("var(--bevel-raised)"),
1148 "tab was held in: {tab}"
1149 );
1150 }
1151
1152 #[test]
1153 fn an_unchosen_tab_recedes_without_looking_picked() {
1154 let css = selector_rules(&Emit::default());
1155 // Recessed by colour and given no edge. An edge would make every option
1156 // look picked; flat would leave the chosen one nothing to come forward
1157 // from, which is the gap makeover-layout 0.3.0 closed.
1158 assert!(
1159 css.contains(".tab {\n background: var(--surface-sunken);\n}"),
1160 "unchosen tab is not recessed: {css}"
1161 );
1162 assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
1163 assert!(css.contains(".tab:hover {"));
1164 }
1165
1166 #[test]
1167 fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
1168 // The inverse of the tab, and why the three selectors are not one
1169 // member with a flag.
1170 let css = selector_rules(&Emit::default());
1171 assert!(css.contains(".segment {\n background: var(--surface-raised);"));
1172 assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
1173 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
1174 }
1175
1176 #[test]
1177 fn row_actions_are_revealed_without_moving_the_row() {
1178 let css = row_rules(&Emit::default());
1179 assert!(css.contains(".row-actions {\n opacity: 0;"));
1180 // Not display:none, which would reflow the row under the pointer.
1181 assert!(!css.contains("display: none"));
1182 // Hover alone would lock the keyboard out.
1183 assert!(css.contains(".row:focus-within .row-actions"));
1184 assert!(RowPart::Actions.revealed_on_hover());
1185 }
1186
1187 #[test]
1188 fn a_hidden_row_action_is_still_focusable_and_not_tappable() {
1189 let css = row_rules(&Emit::default());
1190 // `visibility: hidden` takes the actions out of the focus order, so the
1191 // `focus-within` reveal above could never fire from an action itself.
1192 assert!(!css.contains("visibility:"));
1193 // Opacity leaves the hit area behind, so the pair travels together or
1194 // the row carries an invisible tappable control.
1195 assert!(css.contains(".row-actions {\n opacity: 0;\n pointer-events: none;\n }"));
1196 assert!(css.contains("opacity: 1;\n pointer-events: auto;"));
1197
1198 // And on a device with no hover the row carries no such control at
1199 // all, because the hide never applies there. That is what the comment
1200 // above used to be asking for and could not get: the hide is inside
1201 // the capability query with the reveal.
1202 let hide = css.find(".row-actions {").expect("hide rule");
1203 let query = css[..hide].rfind("@media").expect("a query precedes it");
1204 assert!(css[query..hide].find('}').is_none(), "the hide escaped the query");
1205 }
1206
1207 #[test]
1208 fn the_three_text_parts_take_their_intents_and_actions_inherits() {
1209 let css = row_rules(&Emit::default());
1210 assert!(css.contains(".row-primary {\n color: var(--content);"));
1211 assert!(css.contains(".row-secondary {\n color: var(--content-secondary);"));
1212 assert!(css.contains(".row-meta {\n color: var(--content-muted);"));
1213 // Actions carry controls, not text. Pinning the colour it would inherit
1214 // anyway is louder than saying nothing.
1215 assert!(!css.contains(".row-actions {\n color:"));
1216 }
1217
1218 #[test]
1219 fn the_progress_trough_is_a_well() {
1220 let css = progress_rules(&Emit::default());
1221 assert!(css.contains(".progress {"));
1222 assert!(css.contains("box-shadow: var(--bevel-inset)"));
1223 assert!(css.contains(".progress > .progress-fill {"));
1224 assert!(css.contains("background: var(--action)"));
1225 // A bare `.fill` would catch things that have nothing to do with
1226 // progress once the sheet lands unprefixed.
1227 assert!(!css.contains("> .fill "));
1228 }
1229
1230 #[test]
1231 fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
1232 let css = progress_rules(&Emit::default());
1233 // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
1234 // status is still reporting progress, and muted would read as disabled.
1235 assert!(css.contains(".progress > .progress-fill {\n background: var(--action);"));
1236 assert!(!css.contains("progress-fill {\n color: var(--content-muted)"));
1237 for tone in ["info", "success", "warning", "danger"] {
1238 assert!(
1239 css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
1240 "missing progress tone {tone}"
1241 );
1242 }
1243 // goingson's two live cases, which is why the tones are emitted at all.
1244 assert!(css.contains("[data-tone=\"success\"] {\n background: var(--success);"));
1245 assert!(css.contains("[data-tone=\"danger\"] {\n background: var(--danger);"));
1246 }
1247
1248 #[test]
1249 fn no_scrollbar_track_is_emitted() {
1250 // Decision 3's negative half. It was on the phase A list and came off;
1251 // this is what stops it drifting back in.
1252 let css = stylesheet(&Emit::default());
1253 assert!(!css.contains("scrollbar"));
1254 assert!(!css.contains("::-webkit"));
1255 }
1256
1257 #[test]
1258 fn an_invalid_field_is_ringed_without_being_lit() {
1259 let css = surface_rules(&Emit::default());
1260 assert!(css.contains(".field {"));
1261 // The ARIA attribute, not a class: one fact, read by both the visual
1262 // and the accessible state, so they cannot drift.
1263 assert!(css.contains(".field[aria-invalid=\"true\"] {"));
1264 assert!(!css.contains(".field.invalid"));
1265 // A flat ring: this edge says "wrong", and a two-tone bevel would have
1266 // it say "raised" at the same time.
1267 assert!(css.contains("0 0 0 1px var(--danger)"));
1268 }
1269
1270 #[test]
1271 fn an_invalid_field_keeps_the_well_underneath_it() {
1272 // box-shadow is not additive. A lone ring replaces the bevel and drops
1273 // the well out from under the field, which is what this emitted before
1274 // 0.5.0 and is the whole reason the rule composes.
1275 let css = surface_rules(&Emit::default());
1276 let invalid = css
1277 .lines()
1278 .skip_while(|l| !l.starts_with(".field[aria-invalid"))
1279 .take_while(|l| !l.starts_with('}'))
1280 .collect::<Vec<_>>()
1281 .join("\n");
1282 assert!(
1283 invalid.contains("var(--bevel-inset)"),
1284 "the well was dropped: {invalid}"
1285 );
1286 assert!(invalid.contains("var(--danger)"));
1287 }
1288
1289 #[test]
1290 fn button_and_card_come_out_identical_by_construction() {
1291 // The duplication phase A deletes. They are the same composition, so
1292 // the only honest way to emit both is from one call.
1293 let opts = Emit::default();
1294 let css = surface_rules(&opts);
1295 assert_eq!(
1296 depth_declarations(Depth::Raised),
1297 depth_declarations(Depth::Raised)
1298 );
1299 assert!(css.contains(".button {"));
1300 assert!(css.contains(".card {"));
1301 assert_eq!(
1302 interactive_rules("button", Depth::Raised, &Emit::default()).replace("button", "card"),
1303 interactive_rules("card", Depth::Raised, &Emit::default())
1304 );
1305 }
1306
1307 #[test]
1308 fn a_prefix_reaches_the_component_classes_too() {
1309 let opts = Emit {
1310 class_prefix: "mo-",
1311 ..Emit::default()
1312 };
1313 let css = stylesheet(&opts);
1314 for name in [
1315 "mo-button",
1316 "mo-card",
1317 "mo-field",
1318 "mo-badge",
1319 "mo-chip",
1320 "mo-tab",
1321 "mo-row-primary",
1322 "mo-progress",
1323 "mo-progress-fill",
1324 ] {
1325 assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
1326 }
1327 // The bare names must be gone entirely, or a prefixed build still
1328 // collides with the app's own stylesheet.
1329 assert!(!css.contains(".button {"));
1330 assert!(!css.contains(".card {"));
1331 assert!(!css.contains(".badge {"));
1332 }
1333
1334 #[test]
1335 fn the_whole_sheet_still_names_every_colour() {
1336 // The crate's founding property, asserted over the component layer and
1337 // not only the primitives.
1338 let css = stylesheet(&Emit::default());
1339 assert!(!css.contains('#'));
1340 assert!(!css.contains("rgb"));
1341 for line in css.lines() {
1342 // Declarations only: a selector or an at-rule can carry a colon of
1343 // its own (`:root`, `:hover`, `@media (hover: hover)`) and declares
1344 // nothing. Keyed on the trailing semicolon rather than on leading
1345 // indentation, which only ever worked as a proxy for nesting depth
1346 // and stopped when the sheet gained a cascade layer around it.
1347 let trimmed = line.trim();
1348 if !trimmed.ends_with(';') {
1349 continue;
1350 }
1351 let Some((_, value)) = trimmed.split_once(": ") else {
1352 continue;
1353 };
1354 if value.contains("var(--") {
1355 continue;
1356 }
1357 // Everything left has to be a keyword, a number or a
1358 // caller-supplied length, never a colour.
1359 //
1360 // The length arm is what the comment above always claimed and the
1361 // list never covered: `border_width` arrives from `Emit` and lands
1362 // bare in the focus ring's offset, where the bevel had only ever
1363 // used it inside an `inset` shadow.
1364 let opts = Emit::default();
1365 assert!(
1366 value.contains("inset")
1367 || value.contains(opts.border_width)
1368 || value.contains(opts.focus_width)
1369 || matches!(
1370 value.trim_end_matches(';'),
1371 "0" | "1" | "none" | "auto" | "not-allowed"
1372 ),
1373 "unrecognised literal value: {line}"
1374 );
1375 }
1376 }
1377
1378 #[test]
1379 fn flat_emits_nothing_at_all() {
1380 assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
1381 assert!(!depth_rules(&Emit::default()).contains("flat"));
1382 }
1383
1384 #[test]
1385 fn a_prefix_namespaces_every_class() {
1386 let opts = Emit {
1387 class_prefix: "mo-",
1388 ..Emit::default()
1389 };
1390 let css = depth_rules(&opts);
1391 assert!(css.contains(".mo-raised {"));
1392 assert!(css.contains(".mo-well {"));
1393 assert!(!css.contains(".raised {"));
1394 }
1395
1396 #[test]
1397 fn the_border_width_is_the_callers() {
1398 let opts = Emit {
1399 border_width: "2px",
1400 ..Emit::default()
1401 };
1402 assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
1403 }
1404
1405 #[test]
1406 fn edges_agree_with_the_description() {
1407 // Not a tautology: it is the guard that a CSS-shaped convenience never
1408 // quietly reverses which side is lit.
1409 let (tl, br) = Bevel::Raised.edges();
1410 assert_eq!(tl.token(), Edge::Light.token());
1411 assert_eq!(br.token(), Edge::Dark.token());
1412 }
1413}