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