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//! # Substitution, three ways
76//!
77//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
78//! answers that differently, which is the evidence that dropping
79//! `Fill::fallback` from the description was right:
80//!
81//! - `makeover-immediate` substitutes the page in Rust.
82//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
83//! terminal would quantise the two together.
84//! - here, CSS already has the mechanism: `var(--surface-well,
85//! var(--surface-page))` falls back in the browser, and nothing in Rust
86//! decides anything.
87
88#![forbid(unsafe_code)]
89
90pub mod form;
91pub mod list;
92
93use makeover_layout::{Bevel, Depth, Fill, Intent, RowPart, Selector, Token, Tone};
94use std::fmt::Write as _;
95
96/// How the emitted CSS is shaped.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Emit {
99 /// Bevel thickness, as a CSS length.
100 ///
101 /// A value, so it arrives from the caller: border widths belong to
102 /// `makeover-geometry` and will come from there once it carries them.
103 pub border_width: &'static str,
104 /// Prefix for emitted class names, without the leading dot.
105 pub class_prefix: &'static str,
106}
107
108impl Default for Emit {
109 fn default() -> Self {
110 Self {
111 border_width: "1px",
112 class_prefix: "",
113 }
114 }
115}
116
117/// The CSS custom property holding a bevel's composition.
118#[must_use]
119pub fn bevel_var(bevel: Bevel) -> &'static str {
120 match bevel {
121 Bevel::Raised => "--bevel-raised",
122 Bevel::Inset => "--bevel-inset",
123 }
124}
125
126/// A `var()` reference to a fill intent, with the browser's own fallback where
127/// the intent may be absent.
128///
129/// The fallback is CSS syntax, not a decision made here. That is the whole
130/// difference between this renderer and the other two.
131#[must_use]
132pub fn fill_var(fill: Fill) -> String {
133 match fill {
134 Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
135 other => format!("var(--{})", other.token()),
136 }
137}
138
139/// The two-tone edge as a `box-shadow` value.
140///
141/// Two inset shadows, one per corner pair: the light one offset down and
142/// right so it lands on the top and left edges, the dark one the other way.
143/// The same assignment `makeover-immediate` draws with polylines and
144/// `makeover-tui` draws with box-drawing characters.
145#[must_use]
146pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
147 let (top_left, bottom_right) = bevel.edges();
148 let w = opts.border_width;
149 format!(
150 "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
151 top_left.token(),
152 bottom_right.token()
153 )
154}
155
156/// The custom properties both bevels resolve through.
157///
158/// Emitted as properties rather than inlined into every rule because that is
159/// what the apps already do, and because a consumer that wants the edge
160/// without the fill reads the property directly.
161#[must_use]
162pub fn bevel_properties(opts: &Emit) -> String {
163 let mut css = String::new();
164 for bevel in [Bevel::Raised, Bevel::Inset] {
165 let _ = writeln!(
166 css,
167 " {}: {};",
168 bevel_var(bevel),
169 bevel_shadow(bevel, opts)
170 );
171 }
172 css
173}
174
175/// The class name for a depth.
176#[must_use]
177pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
178 let name = match depth {
179 Depth::Flat => return None,
180 Depth::Raised => "raised",
181 Depth::Well => "well",
182 Depth::Sunken => "sunken",
183 // A depth added to the description since this renderer was last
184 // built. No class, on the same footing as Flat: emitting a name
185 // whose rule body we cannot write would put a class in the markup
186 // that the stylesheet never defines.
187 _ => return None,
188 };
189 Some(format!("{}{name}", opts.class_prefix))
190}
191
192/// A prefixed class name.
193fn class(name: &str, opts: &Emit) -> String {
194 format!("{}{name}", opts.class_prefix)
195}
196
197/// The fill and edge declarations for a depth, as a rule body.
198///
199/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
200/// Callers lean on the emptiness to skip the rule rather than emit a class that
201/// sets nothing: a class that sets no properties is a class that means "I
202/// thought about this", which is what comments are for.
203///
204/// The two halves are emitted independently because [`Depth::Sunken`] has a
205/// fill and no bevel. Requiring both, which this did before makeover-layout
206/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
207/// mean unpaired: both halves still come off one `Depth`, so they cannot
208/// disagree about what the region is.
209#[must_use]
210pub fn depth_declarations(depth: Depth) -> String {
211 let mut css = String::new();
212 if let Some(fill) = depth.fill() {
213 let _ = writeln!(css, " background: {};", fill_var(fill));
214 }
215 if let Some(bevel) = depth.bevel() {
216 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
217 }
218 css
219}
220
221/// One rule giving a selector a depth, or nothing when the depth declares
222/// nothing.
223#[must_use]
224pub fn depth_rule(selector: &str, depth: Depth) -> String {
225 let body = depth_declarations(depth);
226 if body.is_empty() {
227 return String::new();
228 }
229 format!(".{selector} {{\n{body}}}\n")
230}
231
232/// Hover and pressed, for a selector that answers a click.
233///
234/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
235/// only the edge is what left goingson hand-writing `background:
236/// var(--surface-sunken)` on three separate rules, and a fill that does not
237/// travel with its edge is precisely the disagreement `Depth` exists to make
238/// unrepresentable. So the pressed fill comes from the description
239/// (`--surface-well`) rather than from whatever each app reached for.
240///
241/// Hover has no member in the description and is renderer policy: a terminal
242/// and an immediate-mode painter have no hover to express. It resolves against
243/// `--hover-surface`, which `makeover` already derives and which nothing
244/// consumed until now.
245#[must_use]
246pub fn interactive_rules(selector: &str) -> String {
247 format!(
248 ".{selector}:hover {{\n background: var(--hover-surface);\n}}\n{}",
249 depth_rule(&format!("{selector}:active"), Depth::Raised.pressed())
250 )
251}
252
253/// One rule per depth: its fill and its edge, together.
254///
255/// A pressed rule rides along with the raised one, because the cascade can
256/// carry a state that an immediate-mode renderer has to resolve per call site.
257/// That is the one thing this renderer gets for free and the others do not.
258#[must_use]
259pub fn depth_rules(opts: &Emit) -> String {
260 let mut css = String::new();
261 for depth in [Depth::Raised, Depth::Well] {
262 let Some(class) = depth_class(depth, opts) else {
263 continue;
264 };
265 css.push_str(&depth_rule(&class, depth));
266 }
267 if let Some(raised) = depth_class(Depth::Raised, opts) {
268 css.push_str(&interactive_rules(&raised));
269 }
270 css
271}
272
273/// The three surfaces that are a depth with a name.
274///
275/// `button` and `card` are both [`Depth::Raised`], and `field` is a
276/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
277/// gives a text field. Their bodies come out identical by construction rather
278/// than by hand: three hand-written copies in goingson's stylesheet is what
279/// phase A deletes, and generating them from one call is what stops them
280/// drifting apart again.
281fn surface_rules(opts: &Emit) -> String {
282 let mut css = String::new();
283 for name in ["button", "card"] {
284 let c = class(name, opts);
285 css.push_str(&depth_rule(&c, Depth::Raised));
286 css.push_str(&interactive_rules(&c));
287 }
288
289 let field = class("field", opts);
290 css.push_str(&depth_rule(&field, Depth::Well));
291
292 // Keyed on the ARIA attribute rather than on a class, so the visual state
293 // and the accessible state cannot drift apart: there is one fact and both
294 // read it. goingson already drove its invalid styling this way and was
295 // right to; the `.invalid` class this emitted before 0.5.0 was a second
296 // place to forget.
297 //
298 // The ring composes *after* the bevel rather than replacing it. box-shadow
299 // is not additive, so a lone ring silently dropped the well out from under
300 // an invalid field. Flat and unlit: this edge is saying "wrong", and
301 // lighting one side would have it say "raised" at the same time.
302 let _ = writeln!(
303 css,
304 ".{field}[aria-invalid=\"true\"] {{\n box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
305 bevel_var(Bevel::Inset),
306 opts.border_width
307 );
308 css
309}
310
311/// Badges and chips.
312///
313/// The one place phase A changes how goingson looks rather than only where its
314/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
315/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
316/// carrying the raised bevel. Splitting that means reading every call site to
317/// decide which of the two it always was.
318///
319/// What a badge does carry is a [`Tone`], the intent family it shares with
320/// notices and nothing else. Neutral is the bare class rather than a variant,
321/// because it is the absence of a status and not a status called "none".
322fn token_rules(opts: &Emit) -> String {
323 let mut css = String::new();
324
325 // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
326 // and a label with an edge says it can be pressed.
327 let badge = class("badge", opts);
328 let _ = writeln!(
329 css,
330 ".{badge} {{\n color: var(--{});\n}}",
331 Tone::Neutral.token()
332 );
333 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
334 let _ = writeln!(
335 css,
336 ".{badge}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
337 tone.token()
338 );
339 }
340
341 // A chip holds itself down, which is `Depth::pressed` arrived at
342 // independently by two apps. `removable` is a remove affordance, so it is
343 // markup and waits for phase B.
344 let chip = class("chip", opts);
345 let unlatched = Token::Chip { removable: false };
346 css.push_str(&depth_rule(&chip, unlatched.depth(false)));
347 css.push_str(&interactive_rules(&chip));
348 css.push_str(&depth_rule(
349 &format!("{chip}.latched"),
350 unlatched.depth(true),
351 ));
352 css
353}
354
355/// The three selectors, each named by what it picks.
356///
357/// A tab comes *forward* to join the pane it opens, which is why
358/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
359/// are held in. That is the folder semantic, and it is the whole reason the
360/// three are not one member with a flag.
361///
362/// [`Selector::abutting`] is not emitted: whether the options touch is
363/// spacing, and spacing is `makeover-geometry`'s question to answer.
364///
365/// Both states emit as of makeover-layout 0.3.0. Before it the description
366/// named only the chosen option, so an unchosen one fell through to
367/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
368/// strip hand-writing the recess that makes its chosen tab read as forward.
369fn selector_rules(opts: &Emit) -> String {
370 let mut css = String::new();
371 for (selector, name) in [
372 (Selector::Tabs, "tab"),
373 (Selector::Segmented, "segment"),
374 (Selector::Toggle, "toggle"),
375 ] {
376 let c = class(name, opts);
377 css.push_str(&depth_rule(&c, selector.unchosen()));
378 css.push_str(&interactive_rules(&c));
379 css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
380 }
381 css
382}
383
384/// The four parts of a list row.
385fn row_rules(opts: &Emit) -> String {
386 let mut css = String::new();
387 let row = class("row", opts);
388 for part in [
389 RowPart::Primary,
390 RowPart::Secondary,
391 RowPart::Meta,
392 RowPart::Actions,
393 ] {
394 let name = match part {
395 RowPart::Primary => "row-primary",
396 RowPart::Secondary => "row-secondary",
397 RowPart::Meta => "row-meta",
398 RowPart::Actions => "row-actions",
399 };
400 let c = class(name, opts);
401
402 // Actions carry controls rather than text, and `RowPart::intent` says
403 // so by returning the same intent inheriting already gives. Pinning it
404 // would be louder than saying nothing.
405 if !matches!(part, RowPart::Actions) {
406 let _ = writeln!(css, ".{c} {{\n color: var(--{});\n}}", part.intent());
407 }
408
409 if part.revealed_on_hover() {
410 // Hidden rather than absent: the row must not change height when
411 // the pointer arrives. `focus-within` carries the keyboard, which
412 // hover on its own would lock out.
413 //
414 // Transparent rather than `visibility: hidden`, which was the first
415 // form and defeated the very escape above: a `visibility: hidden`
416 // element is out of the focus order and out of the accessibility
417 // tree, so tabbing could never reach an action and could never
418 // trigger the row's `focus-within`. goingson had reached the same
419 // opacity form independently, on its own comment "always in the DOM
420 // for keyboard and screen readers".
421 //
422 // `pointer-events` rides along because opacity leaves the hit area
423 // behind: without it a renderer with no hover carries an invisible
424 // tappable control. Keyboard focus is unaffected by it.
425 let _ = writeln!(
426 css,
427 ".{c} {{\n opacity: 0;\n pointer-events: none;\n}}"
428 );
429 let _ = writeln!(
430 css,
431 ".{row}:hover .{c},\n.{row}:focus-within .{c} {{\n opacity: 1;\n pointer-events: auto;\n}}"
432 );
433 }
434 }
435 css
436}
437
438/// The progress trough, which has nothing behind it in the description.
439///
440/// Renderer-local chrome, on the same licence the skeletons hold as the
441/// webview's expression of `Readiness::Pending`: a determinate bar is a shape
442/// CSS draws readily and a terminal would rather not be told about. It earns
443/// the place empirically, goingson having grown four independent progress bars
444/// before anything named one.
445///
446/// The trough is a [`Depth::Well`], the same reading a text field gets:
447/// something with its content down inside it.
448fn progress_rules(opts: &Emit) -> String {
449 let progress = class("progress", opts);
450 // `progress-fill` rather than a bare `fill`: an unprefixed build claims
451 // these names in the app's own stylesheet, and `.fill` is grabby enough to
452 // catch things that have nothing to do with progress. goingson already
453 // calls it `.progress-fill`, so this is also the name that deletes.
454 let fill = class("progress-fill", opts);
455 let mut css = depth_rule(&progress, Depth::Well);
456
457 // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
458 // place this differs from the badge rules, and deliberately: a badge with
459 // no status is a muted label, while a bar with no status is still
460 // reporting progress, and `content-muted` would read as disabled.
461 let _ = writeln!(
462 css,
463 ".{progress} > .{fill} {{\n background: var(--action);\n}}"
464 );
465
466 // A bar can be saying something, same as a badge: goingson colours subtask
467 // progress as success and an over-estimate as danger, which is real
468 // information rather than decoration. Emitting the tones is what lets that
469 // survive adoption instead of staying hand-written.
470 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
471 let _ = writeln!(
472 css,
473 ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n background: var(--{0});\n}}",
474 tone.token()
475 );
476 }
477 css
478}
479
480/// The component layer: every named thing phase A emits.
481///
482/// No scrollbar track. It was on the phase A list and came off: eight lines of
483/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
484/// would want handed to it, so it stays with the apps.
485#[must_use]
486pub fn component_rules(opts: &Emit) -> String {
487 let mut css = String::new();
488 css.push_str(&surface_rules(opts));
489 css.push_str(&token_rules(opts));
490 css.push_str(&selector_rules(opts));
491 css.push_str(&row_rules(opts));
492 css.push_str(&progress_rules(opts));
493 css
494}
495
496/// The whole phase-A stylesheet: properties, depth rules and components, with
497/// a generated-file banner.
498#[must_use]
499pub fn stylesheet(opts: &Emit) -> String {
500 format!(
501 "/* Generated by makeover-webview from makeover-layout. Do not edit.\n \
502 Depth is a fill and an edge together; naming them apart is what let\n \
503 them disagree. See the crate's README and wiki note makeover-layout. */\n\
504 :root {{\n{}}}\n\n{}\n{}",
505 bevel_properties(opts),
506 depth_rules(opts),
507 component_rules(opts)
508 )
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use makeover_layout::Edge;
515
516 #[test]
517 fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
518 // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
519 // deletion, not a redesign, or nobody will take it.
520 let opts = Emit::default();
521 assert_eq!(
522 bevel_shadow(Bevel::Raised, &opts),
523 "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
524 );
525 assert_eq!(
526 bevel_shadow(Bevel::Inset, &opts),
527 "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
528 );
529 }
530
531 #[test]
532 fn no_colour_ever_reaches_the_output() {
533 let css = stylesheet(&Emit::default());
534 assert!(!css.contains('#'), "a hex literal escaped into the CSS");
535 assert!(
536 !css.contains("rgb"),
537 "a colour function escaped into the CSS"
538 );
539 // Every colour is named, never resolved.
540 assert!(css.contains("var(--surface-raised)"));
541 assert!(css.contains("var(--bevel-light)"));
542 }
543
544 #[test]
545 fn a_well_falls_back_through_css_rather_than_through_rust() {
546 assert_eq!(
547 fill_var(Fill::Well),
548 "var(--surface-well, var(--surface-page))"
549 );
550 // Nothing else needs one.
551 assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
552 assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
553 }
554
555 #[test]
556 fn raised_and_well_do_not_collapse_onto_each_other() {
557 let css = depth_rules(&Emit::default());
558 assert!(css.contains(".raised {"));
559 assert!(css.contains(".well {"));
560 assert!(css.contains("var(--bevel-raised)"));
561 assert!(css.contains("var(--bevel-inset)"));
562 }
563
564 #[test]
565 fn the_cascade_carries_the_pressed_state() {
566 let css = depth_rules(&Emit::default());
567 // The one thing this renderer gets free that the other two resolve by
568 // hand, eighteen call sites deep in audiofiles' case.
569 assert!(css.contains(".raised:active {"));
570 }
571
572 #[test]
573 fn pressing_moves_the_fill_and_not_only_the_edge() {
574 // The decision-1 guard, and the regression that mattered: emitting the
575 // bevel flip alone is what left goingson hand-writing `background:
576 // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
577 // of the three could be deleted.
578 let pressed = interactive_rules("button");
579 assert!(pressed.contains(".button:active {"));
580 assert!(
581 pressed.contains("background: var(--surface-well, var(--surface-page))"),
582 "pressed dropped its fill: {pressed}"
583 );
584 assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
585 }
586
587 #[test]
588 fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
589 // goingson presses to --surface-sunken. The description says a pressed
590 // raised region reads as a well, and makeover says outright that
591 // surface-sunken cannot serve as one, so the app is the thing that
592 // moves.
593 //
594 // Scoped to the pressed rules rather than to the whole sheet: since
595 // makeover-layout 0.3.0 an unchosen tab is legitimately
596 // --surface-sunken, so the token appearing somewhere in the output no
597 // longer means the app's choice leaked in.
598 let css = stylesheet(&Emit::default());
599 let mut checked = 0;
600 for rule in css.split("}\n") {
601 if !rule.contains(":active") {
602 continue;
603 }
604 checked += 1;
605 assert!(
606 !rule.contains("surface-sunken"),
607 "a pressed rule took the app's fill: {rule}"
608 );
609 }
610 assert!(checked > 0, "no pressed rules found to check");
611 assert_eq!(
612 Depth::Raised.pressed().fill(),
613 Some(Fill::Well),
614 "the description changed under us"
615 );
616 }
617
618 #[test]
619 fn hover_resolves_against_the_token_makeover_already_derives() {
620 let css = interactive_rules("card");
621 assert!(css.contains(".card:hover {"));
622 assert!(css.contains("background: var(--hover-surface)"));
623 // Not the app's choice, which was --surface-overlay.
624 assert!(!css.contains("surface-overlay"));
625 }
626
627 #[test]
628 fn a_badge_gets_no_edge_and_no_fill() {
629 // Decision 2, and the one visible redesign in phase A. Token::Badge is
630 // Flat: an edge on a label says it can be pressed.
631 let css = token_rules(&Emit::default());
632 let badge = css
633 .lines()
634 .skip_while(|l| !l.starts_with(".badge {"))
635 .take_while(|l| !l.starts_with('}'))
636 .collect::<Vec<_>>()
637 .join("\n");
638 assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
639 assert!(!badge.contains("background"), "badge kept a fill: {badge}");
640 assert_eq!(Token::Badge.depth(false), Depth::Flat);
641 assert_eq!(Token::Badge.depth(true), Depth::Flat);
642 }
643
644 #[test]
645 fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
646 let css = token_rules(&Emit::default());
647 // Neutral is the absence of a status, not a status named "none".
648 assert!(css.contains(".badge {\n color: var(--content-muted);"));
649 assert!(!css.contains("data-tone=\"content-muted\""));
650 for tone in ["info", "success", "warning", "danger"] {
651 assert!(
652 css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
653 "missing tone {tone}"
654 );
655 assert!(css.contains(&format!("color: var(--{tone})")));
656 }
657 }
658
659 #[test]
660 fn a_chip_is_raised_and_latches_into_a_well() {
661 let css = token_rules(&Emit::default());
662 assert!(css.contains(".chip {"));
663 assert!(css.contains(".chip.latched {"));
664 assert!(css.contains(".chip:active {"));
665 // The whole difference from a badge: it answers a click.
666 assert!(Token::Chip { removable: false }.interactive());
667 assert!(!Token::Badge.interactive());
668 }
669
670 #[test]
671 fn only_a_tab_comes_forward_when_chosen() {
672 // The folder semantic. Collapsing the three selectors would lose it.
673 let css = selector_rules(&Emit::default());
674 assert!(css.contains(".tab.chosen {"));
675 assert!(css.contains(".segment.chosen {"));
676 assert!(css.contains(".toggle.chosen {"));
677 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
678 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
679 assert_eq!(Selector::Toggle.chosen(), Depth::Well);
680
681 let tab = css
682 .lines()
683 .skip_while(|l| !l.starts_with(".tab.chosen {"))
684 .take_while(|l| !l.starts_with('}'))
685 .collect::<Vec<_>>()
686 .join("\n");
687 assert!(
688 tab.contains("var(--bevel-raised)"),
689 "tab was held in: {tab}"
690 );
691 }
692
693 #[test]
694 fn an_unchosen_tab_recedes_without_looking_picked() {
695 let css = selector_rules(&Emit::default());
696 // Recessed by colour and given no edge. An edge would make every option
697 // look picked; flat would leave the chosen one nothing to come forward
698 // from, which is the gap makeover-layout 0.3.0 closed.
699 assert!(
700 css.contains(".tab {\n background: var(--surface-sunken);\n}"),
701 "unchosen tab is not recessed: {css}"
702 );
703 assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
704 assert!(css.contains(".tab:hover {"));
705 }
706
707 #[test]
708 fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
709 // The inverse of the tab, and why the three selectors are not one
710 // member with a flag.
711 let css = selector_rules(&Emit::default());
712 assert!(css.contains(".segment {\n background: var(--surface-raised);"));
713 assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
714 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
715 }
716
717 #[test]
718 fn row_actions_are_revealed_without_moving_the_row() {
719 let css = row_rules(&Emit::default());
720 assert!(css.contains(".row-actions {\n opacity: 0;"));
721 // Not display:none, which would reflow the row under the pointer.
722 assert!(!css.contains("display: none"));
723 // Hover alone would lock the keyboard out.
724 assert!(css.contains(".row:focus-within .row-actions"));
725 assert!(RowPart::Actions.revealed_on_hover());
726 }
727
728 #[test]
729 fn a_hidden_row_action_is_still_focusable_and_not_tappable() {
730 let css = row_rules(&Emit::default());
731 // `visibility: hidden` takes the actions out of the focus order, so the
732 // `focus-within` reveal above could never fire from an action itself.
733 assert!(!css.contains("visibility:"));
734 // Opacity leaves the hit area behind; the row must not carry an
735 // invisible tappable control where there is no hover to reveal it.
736 assert!(css.contains(".row-actions {\n opacity: 0;\n pointer-events: none;\n}"));
737 assert!(css.contains("opacity: 1;\n pointer-events: auto;"));
738 }
739
740 #[test]
741 fn the_three_text_parts_take_their_intents_and_actions_inherits() {
742 let css = row_rules(&Emit::default());
743 assert!(css.contains(".row-primary {\n color: var(--content);"));
744 assert!(css.contains(".row-secondary {\n color: var(--content-secondary);"));
745 assert!(css.contains(".row-meta {\n color: var(--content-muted);"));
746 // Actions carry controls, not text. Pinning the colour it would inherit
747 // anyway is louder than saying nothing.
748 assert!(!css.contains(".row-actions {\n color:"));
749 }
750
751 #[test]
752 fn the_progress_trough_is_a_well() {
753 let css = progress_rules(&Emit::default());
754 assert!(css.contains(".progress {"));
755 assert!(css.contains("box-shadow: var(--bevel-inset)"));
756 assert!(css.contains(".progress > .progress-fill {"));
757 assert!(css.contains("background: var(--action)"));
758 // A bare `.fill` would catch things that have nothing to do with
759 // progress once the sheet lands unprefixed.
760 assert!(!css.contains("> .fill "));
761 }
762
763 #[test]
764 fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
765 let css = progress_rules(&Emit::default());
766 // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
767 // status is still reporting progress, and muted would read as disabled.
768 assert!(css.contains(".progress > .progress-fill {\n background: var(--action);"));
769 assert!(!css.contains("progress-fill {\n color: var(--content-muted)"));
770 for tone in ["info", "success", "warning", "danger"] {
771 assert!(
772 css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
773 "missing progress tone {tone}"
774 );
775 }
776 // goingson's two live cases, which is why the tones are emitted at all.
777 assert!(css.contains("[data-tone=\"success\"] {\n background: var(--success);"));
778 assert!(css.contains("[data-tone=\"danger\"] {\n background: var(--danger);"));
779 }
780
781 #[test]
782 fn no_scrollbar_track_is_emitted() {
783 // Decision 3's negative half. It was on the phase A list and came off;
784 // this is what stops it drifting back in.
785 let css = stylesheet(&Emit::default());
786 assert!(!css.contains("scrollbar"));
787 assert!(!css.contains("::-webkit"));
788 }
789
790 #[test]
791 fn an_invalid_field_is_ringed_without_being_lit() {
792 let css = surface_rules(&Emit::default());
793 assert!(css.contains(".field {"));
794 // The ARIA attribute, not a class: one fact, read by both the visual
795 // and the accessible state, so they cannot drift.
796 assert!(css.contains(".field[aria-invalid=\"true\"] {"));
797 assert!(!css.contains(".field.invalid"));
798 // A flat ring: this edge says "wrong", and a two-tone bevel would have
799 // it say "raised" at the same time.
800 assert!(css.contains("0 0 0 1px var(--danger)"));
801 }
802
803 #[test]
804 fn an_invalid_field_keeps_the_well_underneath_it() {
805 // box-shadow is not additive. A lone ring replaces the bevel and drops
806 // the well out from under the field, which is what this emitted before
807 // 0.5.0 and is the whole reason the rule composes.
808 let css = surface_rules(&Emit::default());
809 let invalid = css
810 .lines()
811 .skip_while(|l| !l.starts_with(".field[aria-invalid"))
812 .take_while(|l| !l.starts_with('}'))
813 .collect::<Vec<_>>()
814 .join("\n");
815 assert!(
816 invalid.contains("var(--bevel-inset)"),
817 "the well was dropped: {invalid}"
818 );
819 assert!(invalid.contains("var(--danger)"));
820 }
821
822 #[test]
823 fn button_and_card_come_out_identical_by_construction() {
824 // The duplication phase A deletes. They are the same composition, so
825 // the only honest way to emit both is from one call.
826 let opts = Emit::default();
827 let css = surface_rules(&opts);
828 assert_eq!(
829 depth_declarations(Depth::Raised),
830 depth_declarations(Depth::Raised)
831 );
832 assert!(css.contains(".button {"));
833 assert!(css.contains(".card {"));
834 assert_eq!(
835 interactive_rules("button").replace("button", "card"),
836 interactive_rules("card")
837 );
838 }
839
840 #[test]
841 fn a_prefix_reaches_the_component_classes_too() {
842 let opts = Emit {
843 class_prefix: "mo-",
844 ..Emit::default()
845 };
846 let css = stylesheet(&opts);
847 for name in [
848 "mo-button",
849 "mo-card",
850 "mo-field",
851 "mo-badge",
852 "mo-chip",
853 "mo-tab",
854 "mo-row-primary",
855 "mo-progress",
856 "mo-progress-fill",
857 ] {
858 assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
859 }
860 // The bare names must be gone entirely, or a prefixed build still
861 // collides with the app's own stylesheet.
862 assert!(!css.contains(".button {"));
863 assert!(!css.contains(".card {"));
864 assert!(!css.contains(".badge {"));
865 }
866
867 #[test]
868 fn the_whole_sheet_still_names_every_colour() {
869 // The crate's founding property, asserted over the component layer and
870 // not only the primitives.
871 let css = stylesheet(&Emit::default());
872 assert!(!css.contains('#'));
873 assert!(!css.contains("rgb"));
874 for line in css.lines() {
875 // Declarations only: a selector or an at-rule can carry a colon of
876 // its own (`:root`, `:hover`) and declares nothing.
877 let declaration = line.strip_prefix(" ").map(str::trim);
878 let Some(Some((_, value))) = declaration.map(|d| d.split_once(": ")) else {
879 continue;
880 };
881 if value.contains("var(--") {
882 continue;
883 }
884 // Everything left has to be a keyword, a number or a
885 // caller-supplied length, never a colour.
886 assert!(
887 value.contains("inset")
888 || matches!(value.trim_end_matches(';'), "0" | "1" | "none" | "auto"),
889 "unrecognised literal value: {line}"
890 );
891 }
892 }
893
894 #[test]
895 fn flat_emits_nothing_at_all() {
896 assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
897 assert!(!depth_rules(&Emit::default()).contains("flat"));
898 }
899
900 #[test]
901 fn a_prefix_namespaces_every_class() {
902 let opts = Emit {
903 class_prefix: "mo-",
904 ..Emit::default()
905 };
906 let css = depth_rules(&opts);
907 assert!(css.contains(".mo-raised {"));
908 assert!(css.contains(".mo-well {"));
909 assert!(!css.contains(".raised {"));
910 }
911
912 #[test]
913 fn the_border_width_is_the_callers() {
914 let opts = Emit {
915 border_width: "2px",
916 ..Emit::default()
917 };
918 assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
919 }
920
921 #[test]
922 fn edges_agree_with_the_description() {
923 // Not a tautology: it is the guard that a CSS-shaped convenience never
924 // quietly reverses which side is lit.
925 let (tl, br) = Bevel::Raised.edges();
926 assert_eq!(tl.token(), Edge::Light.token());
927 assert_eq!(br.token(), Edge::Dark.token());
928 }
929}