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.47.0: a range, a chooser's ghost text, and an option that cannot be
163//! picked yet
164//!
165//! `makeover-layout` 0.28.0's three form findings, all of them cheap here and
166//! none of them cheap in the app that found them.
167//!
168//! - `FieldKind::Range` emits `<input type="range">`, and `Field::step` emits
169//! `step`. The step is emitted only when the description carries one: the
170//! browser's own default is `step="1"`, which is what a description means by
171//! saying nothing, and is also what turns a 0-to-1 threshold into a
172//! two-position control.
173//! - A select with nothing chosen emits a disabled, selected, valueless first
174//! option carrying `Field::placeholder`. HTML has no placeholder attribute on
175//! `<select>`; this is the idiom, and `required` keeps working through it
176//! because the option's value is empty.
177//! - `Choice::unavailable` emits `disabled` plus the reason. Where it goes
178//! differs by control and the difference is forced: a radio group gets a
179//! `.form-option-reason` span beside the label, and a `<select>` option has
180//! room for no element at all, so the reason runs into its text.
181//!
182//! # 0.25.0: a cell says what it holds
183//!
184//! 0.23.0 gave a table its layout and left every cell the same. One `.cell`
185//! carried the whole thing, so a cell holding text and a cell holding a button
186//! were one class and one content colour, and a control in a cell was painted
187//! as text. That is the drift [`RowPart::intent`](makeover_layout::RowPart)
188//! has prevented for list rows since 0.2.0 and prevented for nothing here.
189//!
190//! makeover-layout 0.14.0's [`CellPart`](makeover_layout::CellPart) names the
191//! four things a cell holds, and [`table_rules`] turns them into
192//! `.cell-value`, `.cell-tokens`, `.cell-actions` and `.cell-link`. Only the
193//! first takes a colour: a token carries its own tone, an action is a control
194//! rather than text, and a link takes the action colour from the anchor it is.
195//!
196//! The colour going on `.cell-value` rather than on `.cell` is the fix rather
197//! than an implementation detail. On the container it cascades into the parts
198//! that are not text, which is the bug said in one rule.
199//!
200//! [`list::Cell::part`] is `Option<CellPart>` here, where it was
201//! `Option<RowPart>`. A table cell borrowing the list row's vocabulary was the
202//! drift with a type on it: the two answer different questions, and only one of
203//! them was ever about a cell.
204//!
205//! # 0.23.0: a table lays itself out, and a row shows its controls
206//!
207//! Three things a description could say and this renderer had no rule for,
208//! found together by rendering the MNW server's SSH-keys settings tab through
209//! `quasi` and preferring the hand-written Askama original.
210//!
211//! **A table had no layout at all.** [`list::narrowing_css`] emits the track
212//! list, and it has to be called with the columns, so it works where the
213//! columns are known at build time: goingson builds `tables.css` in its own
214//! `build.rs` and is untouched. A table a description produced knows its
215//! columns at render time, and the rules would have had to travel with the
216//! markup: a `<style>` element per table, which needs `style-src
217//! 'unsafe-inline'` that the MNW server is working to drop, or the head, which
218//! an htmx fragment swap does not carry. [`table_rules`] lays a table out with
219//! `display: table` instead, which aligns columns across rows knowing nothing
220//! about how many there are. [`Priority`](makeover_layout::Priority) hiding
221//! moves from a generated rule per dropped column to one rule per drop class,
222//! and [`list::column_classes`] is what puts those classes on a cell. A header
223//! row emitted by a renderer's own code should call it too, or the header and
224//! the body disagree about which column just dropped.
225//!
226//! **A destructive button had nowhere for its tone to land.** `.button` carried
227//! no tone, on the reading that a control's colour is its surface. Every
228//! consumer had written the danger rule itself. It joins the badge in taking
229//! the four tones as colour, off `data-tone`.
230//!
231//! **A list rendered as a bulleted list**, because nothing here reset the `ul`
232//! a renderer emits for one.
233//!
234//! `RowPart::revealed_on_hover` also stops being honoured, which its own doc
235//! sanctioned: a renderer decides. It was retired outright in makeover-layout
236//! 0.13.0, once this had been its only consumer for a release. The rule hid a
237//! row's actions until hover,
238//! and every escape it grew was a report that hiding was wrong for somebody:
239//! `focus-within` for the keyboard, the capability gate for a fingertip with no
240//! way to unhide. What survived hid the controls from pointer users alone, who
241//! are the ones scanning a list to learn what can be done to a row.
242//!
243//! # 0.17.0: the depth classes stop being controls
244//!
245//! [`depth_rules`] gave `.raised` the whole interactive set. A depth is a
246//! statement about shape, so that left the vocabulary with no raised surface
247//! that is merely an object, and an app wanting one had two moves: write its
248//! own class from tokens, or take a control class and cancel the control half.
249//! goingson took the second, in three variants over sixteen elements
250//! (`.card--static` at 14 call sites, `.card--muted` at 2, `.card--shell` at 1),
251//! each re-asserting the resting fill and bevel on `:hover` and `:active`.
252//!
253//! Measured before changing it: `.raised` is emitted into goingson, Balanced
254//! Breakfast and the MNW server, and none of the three has a single call site.
255//! The states were unasked-for everywhere at once, and dropping them costs no
256//! migration anywhere.
257//!
258//! `.card` and `.button` are unchanged. They are the same depth *and* controls,
259//! and they take their states from [`surface_rules`], which is where a state
260//! belongs: on the thing that claims to answer a pointer.
261//!
262//! # Substitution, three ways
263//!
264//! `Fill::Well` has no colour on makeover before 2.3.0, and each renderer
265//! answers that differently, which is the evidence that dropping
266//! `Fill::fallback` from the description was right:
267//!
268//! - `makeover-immediate` substitutes the page in Rust.
269//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
270//! terminal would quantise the two together.
271//! - here, CSS already has the mechanism: `var(--surface-well,
272//! var(--surface-page))` falls back in the browser, and nothing in Rust
273//! decides anything.
274
275#![forbid(unsafe_code)]
276
277pub mod figure;
278pub mod form;
279pub mod list;
280pub mod meter;
281pub mod placeholder;
282pub mod vocabulary;
283
284use crate::list::{cell_part_class, part_class};
285use makeover_geometry::{Density, SizeClass};
286// Re-exported rather than redefined. An app assembling its own stylesheet out
287// of this crate's pieces needs the same layer name, and most such apps depend
288// on this crate and not on `makeover-geometry` directly: goingson builds
289// `tables.css` in its own build.rs from [`list::narrowing_css`], and those
290// rules are as generated as the ones here.
291pub use makeover_geometry::{CSS_LAYER, in_css_layer};
292use makeover_layout::{
293 Bevel, CellPart, Depth, Fallback, Fill, Flow, Intent, RowPart, Selector, Sort, State, Token,
294 Tone,
295};
296use makeover_touch::Affordance;
297use std::fmt::Write as _;
298
299/// How the emitted CSS is shaped.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub struct Emit {
302 /// Bevel thickness, as a CSS length.
303 ///
304 /// A value, so it arrives from the caller: border widths belong to
305 /// `makeover-geometry` and will come from there once it carries them.
306 pub border_width: &'static str,
307 /// Focus ring thickness, as a CSS length.
308 ///
309 /// Separate from [`border_width`](Self::border_width), which it reused
310 /// until 0.12.0. That reuse was an implementation convenience dressed as
311 /// consistency, and it emitted a 1px ring: a bevel and a focus indicator
312 /// are answering different questions, and only one of them has to be
313 /// noticed from across a desk.
314 ///
315 /// The default is the measured consensus rather than a new opinion. Every
316 /// consumer had already written its own ring and all three chose at least
317 /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
318 /// goingson 2px on three rules and 3px on the one covering twelve
319 /// selectors. The design system was the only thing in the tree saying 1px.
320 pub focus_width: &'static str,
321 /// Prefix for emitted class names, without the leading dot.
322 pub class_prefix: &'static str,
323}
324
325impl Default for Emit {
326 fn default() -> Self {
327 Self {
328 border_width: "1px",
329 focus_width: "2px",
330 class_prefix: "",
331 }
332 }
333}
334
335/// A string as CSS escapes, for a `content` value.
336///
337/// `\u{25B2}` becomes `\25B2`. Emitted escaped rather than literally so the
338/// stylesheet is ASCII whatever the description spells: a `content` string is
339/// read by whatever encoding the consumer serves the file as, and a caret that
340/// depends on that is a caret that works on one machine.
341///
342/// Terminated by the closing quote at every site here. A CSS hex escape takes
343/// up to six digits and ends at the first character that cannot be one, so an
344/// escape followed by more text would need a space that these do not.
345fn css_escape(text: &str) -> String {
346 text.chars().fold(String::new(), |mut out, c| {
347 let _ = write!(out, "\\{:X}", c as u32);
348 out
349 })
350}
351
352/// The CSS custom property holding a bevel's composition.
353#[must_use]
354pub fn bevel_var(bevel: Bevel) -> &'static str {
355 match bevel {
356 Bevel::Raised => "--bevel-raised",
357 Bevel::Inset => "--bevel-inset",
358 }
359}
360
361/// A `var()` reference to a fill intent, with the browser's own fallback where
362/// the intent may be absent.
363///
364/// The fallback is CSS syntax, not a decision made here. That is the whole
365/// difference between this renderer and the other two.
366#[must_use]
367pub fn fill_var(fill: Fill) -> String {
368 match fill {
369 Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
370 other => format!("var(--{})", other.token()),
371 }
372}
373
374/// The two-tone edge as a `box-shadow` value.
375///
376/// Two inset shadows, one per corner pair: the light one offset down and
377/// right so it lands on the top and left edges, the dark one the other way.
378/// The same assignment `makeover-immediate` draws with polylines and
379/// `makeover-tui` draws with box-drawing characters.
380#[must_use]
381pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
382 let (top_left, bottom_right) = bevel.edges();
383 let w = opts.border_width;
384 format!(
385 "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
386 top_left.token(),
387 bottom_right.token()
388 )
389}
390
391/// The custom properties both bevels resolve through.
392///
393/// Emitted as properties rather than inlined into every rule because that is
394/// what the apps already do, and because a consumer that wants the edge
395/// without the fill reads the property directly.
396#[must_use]
397pub fn bevel_properties(opts: &Emit) -> String {
398 let mut css = String::new();
399 for bevel in [Bevel::Raised, Bevel::Inset] {
400 let _ = writeln!(
401 css,
402 " {}: {};",
403 bevel_var(bevel),
404 bevel_shadow(bevel, opts)
405 );
406 }
407 css.push_str(ELEVATION_PROPERTY);
408 css
409}
410
411/// The cast shadow of a surface that floats over the page.
412///
413/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
414/// this crate owns the geometry, and neither has to know the other's numbers.
415///
416/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
417/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
418/// that reaches for this on a card or a plate has renamed a literal rather than
419/// replaced it.
420///
421/// Two lengths rather than one, because a single blur reads as a smudge at
422/// plate size and as a halo at menu size. The offset is small and downward: a
423/// Platinum-era menu sits just off the page rather than hovering above it.
424const ELEVATION_PROPERTY: &str =
425 " --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
426
427/// The class name for a depth.
428#[must_use]
429pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
430 let name = match depth {
431 Depth::Flat => return None,
432 Depth::Raised => "raised",
433 Depth::Well => "well",
434 Depth::Sunken => "sunken",
435 // A depth added to the description since this renderer was last
436 // built. No class, on the same footing as Flat: emitting a name
437 // whose rule body we cannot write would put a class in the markup
438 // that the stylesheet never defines.
439 _ => return None,
440 };
441 Some(format!("{}{name}", opts.class_prefix))
442}
443
444/// A prefixed class name.
445///
446/// Public since 0.27.0, for the renderers that emit markup this crate does not.
447/// A screen renderer writing `class="row"` has to prefix it the way the
448/// stylesheet half does or a prefixed app gets rules matching everything except
449/// the elements that renderer wrote, and the failure is invisible: the CSS
450/// stays valid and one element is unstyled. quasi-webview carried a byte
451/// identical copy of this function until it could call this one.
452#[must_use]
453pub fn class(name: &str, opts: &Emit) -> String {
454 let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
455 push_class(&mut out, name, opts);
456 out
457}
458
459/// A prefixed class name, written into a buffer the caller already has.
460///
461/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
462/// every class on every element went through a `format!` before 0.40.0,
463/// including the default case where the prefix is empty and the answer is the
464/// argument. A described table row carried roughly eighty transient
465/// allocations, and this and the escaper were most of them.
466///
467/// [`class`] stays for callers holding a name rather than a buffer.
468///
469/// [`escape_into`]: crate::form::escape_into
470pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
471 out.push_str(opts.class_prefix);
472 out.push_str(name);
473}
474
475/// The class an option of a selector carries, which is what the rules key off.
476///
477/// Named for the option and not for the group: [`selector_rules`] styles the
478/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
479/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
480/// and `option`, put `toggle` on the wrapping element rather than on the
481/// buttons inside it, and every described selector in that renderer came out
482/// with no depth, no focus ring and no chosen state, while the toggle group got
483/// a bevel meant for its buttons.
484///
485/// The chosen option additionally carries `chosen`, the same way a latched chip
486/// carries `latched`. That name is this crate's too; there is no reason for a
487/// caller to spell it, and [`selector_rules`] is where it is written down.
488#[must_use]
489pub fn option_class(selector: Selector) -> &'static str {
490 match selector {
491 Selector::Tabs => "tab",
492 Selector::Segmented => "segment",
493 Selector::Toggle => "toggle",
494 }
495}
496
497/// The fill and edge declarations for a depth, as a rule body.
498///
499/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
500/// Callers lean on the emptiness to skip the rule rather than emit a class that
501/// sets nothing: a class that sets no properties is a class that means "I
502/// thought about this", which is what comments are for.
503///
504/// The two halves are emitted independently because [`Depth::Sunken`] has a
505/// fill and no bevel. Requiring both, which this did before makeover-layout
506/// 0.3.0, silently dropped the fill for exactly that case. Independent does not
507/// mean unpaired: both halves still come off one `Depth`, so they cannot
508/// disagree about what the region is.
509#[must_use]
510pub fn depth_declarations(depth: Depth) -> String {
511 let mut css = String::new();
512 if let Some(fill) = depth.fill() {
513 let _ = writeln!(css, " background: {};", fill_var(fill));
514 }
515 if let Some(bevel) = depth.bevel() {
516 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
517 }
518 css
519}
520
521/// One rule giving a selector a depth, or nothing when the depth declares
522/// nothing.
523#[must_use]
524pub fn depth_rule(selector: &str, depth: Depth) -> String {
525 let body = depth_declarations(depth);
526 if body.is_empty() {
527 return String::new();
528 }
529 format!(".{selector} {{\n{body}}}\n")
530}
531
532/// The media condition a hover rule has to sit inside, or `None` if hover is
533/// unconditional.
534///
535/// Two crates answer this and neither answer is made here. `makeover-touch`
536/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
537/// that capability is spelled as a media condition. Asking both is what stops
538/// this renderer minting a third opinion, which is what all three apps did:
539/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
540/// alone, and the MNW server had no gate at all.
541///
542/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
543/// member, which reports as much through `reads_size`. Passing Compact is not
544/// a claim about width; the test below pins that every class agrees.
545fn hover_condition() -> Option<&'static str> {
546 if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
547 // A fingertip grew a hover state. Nothing to gate, and this renderer
548 // should not invent a reason to gate anyway.
549 None
550 } else {
551 Some(Density::Pointer.media_condition())
552 }
553}
554
555/// Put a rule inside a media query, or leave it alone.
556fn gated(condition: Option<&str>, rule: &str) -> String {
557 let Some(condition) = condition else {
558 return rule.to_string();
559 };
560 let mut css = format!("@media {condition} {{\n");
561 for line in rule.lines() {
562 // Blank lines stay blank. Indenting one leaves trailing whitespace,
563 // which is the sort of thing a formatter later reverts and calls a diff.
564 if line.is_empty() {
565 css.push('\n');
566 } else {
567 let _ = writeln!(css, " {line}");
568 }
569 }
570 css.push_str("}\n");
571 css
572}
573
574/// The keyboard focus ring, placed by the depth it lands on.
575///
576/// This is the webview's **focus ring** and nothing more. **Reach** and
577/// **focus** are both the browser's — the document decides what is reachable
578/// and `:focus-visible` decides which reached thing wears the ring — and no
579/// description states either. The three terms are defined once in
580/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
581///
582/// One ring for the whole system, because a focus ring's job is to be
583/// recognised and three apps having three of them is the failure. What varies
584/// is where it sits, and that comes off [`Depth`] rather than off a per-
585/// component choice: a well takes the ring inside its own edge, and anything
586/// standing proud of the page takes it outside.
587///
588/// `outline` rather than the composed `box-shadow` the invalid-field ring at
589/// [`field_rules`] uses, and deliberately the one place the two rings are built
590/// differently. A `box-shadow` ring has to restate the bevel beside it, because
591/// `box-shadow` is not additive and a lone ring silently drops the well out
592/// from under the element. That restatement is a second copy of the depth,
593/// living in a different function from the first, and it is exactly the
594/// duplication `Depth` exists to prevent. `outline` occupies its own property,
595/// so the bevel survives untouched and there is nothing to keep in agreement.
596/// They render the same: both are a flush ring one border-width wide.
597#[must_use]
598pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
599 let w = opts.focus_width;
600 // Same magnitude either way, and only the sign comes off the depth. Both
601 // values are what the consumers had already converged on independently:
602 // 2px out is what all three wrote, and 2px in is the MNW server's own
603 // answer for the one inset ring it had.
604 let offset = match depth.bevel() {
605 // Inside the well, clear of its edge rather than painted over it.
606 Some(Bevel::Inset) => format!("calc(-1 * {w})"),
607 // Raised, or no edge at all. Outside, standing off by its own width.
608 _ => w.to_string(),
609 };
610 // The token by name. It is `makeover`'s, derived from the action colour,
611 // and reaching it through a description member was a second path to the
612 // same variable for as long as one existed.
613 format!(
614 ".{selector}:focus-visible {{\n outline: {w} solid var(--focus-ring);\n outline-offset: {offset};\n}}\n"
615 )
616}
617
618/// Present, visible, and not answering.
619///
620/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
621/// only matches form elements and half the things this crate emits are not
622/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
623/// the accessible state is the pattern [`field_rules`] already establishes for
624/// `aria-invalid`, on the reasoning that one fact read by both the styling and
625/// the accessibility tree cannot drift from itself.
626///
627/// The rest depth is re-asserted rather than assumed, because this rule has to
628/// beat the hover and pressed rules above it. It does that on source order at
629/// equal specificity, not by out-specifying them: every rule this function's
630/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
631/// one of them and have to be unpicked when this output moves inside its own
632/// cascade layer.
633#[must_use]
634pub fn disabled_rule(selector: &str, depth: Depth) -> String {
635 format!(
636 ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{} color: var(--{});\n cursor: not-allowed;\n}}\n",
637 depth_declarations(depth),
638 State::Disabled.token()
639 )
640}
641
642/// Every state a selector that answers a click implies: hover, pressed, focus
643/// and disabled, in that order.
644///
645/// Order is the whole cascade mechanism here. All four selectors are
646/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
647/// and by nothing else.
648///
649/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
650/// only the edge is what left goingson hand-writing `background:
651/// var(--surface-sunken)` on three separate rules, and a fill that does not
652/// travel with its edge is precisely the disagreement `Depth` exists to make
653/// unrepresentable. So the pressed fill comes from the description
654/// (`--surface-well`) rather than from whatever each app reached for.
655///
656/// Hover has no member in the description and is renderer policy: a terminal
657/// and an immediate-mode painter have no hover to express. It resolves against
658/// `--hover-surface`, which `makeover` already derives and which nothing
659/// consumed until now. What it *is* gated on is capability, via
660/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
661/// goingson's section 60 exists solely to take back the hover state this
662/// function had just handed it, by out-specifying a rule it does not own.
663///
664/// `depth` is the selector's **rest** depth, used to place the focus ring and
665/// to restore the surface under a disabled control. The pressed rule keeps
666/// inverting from [`Depth::Raised`] regardless, which is what every caller got
667/// before this parameter existed: a tab's unchosen depth is
668/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
669/// from the rest depth would leave a tab with no press at all.
670#[must_use]
671pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
672 let mut css = gated(
673 hover_condition(),
674 &format!(".{selector}:hover {{\n background: var(--hover-surface);\n}}\n"),
675 );
676 css.push_str(&depth_rule(
677 &format!("{selector}:active"),
678 Depth::Raised.pressed(),
679 ));
680 css.push_str(&focus_rule(selector, depth, opts));
681 css.push_str(&disabled_rule(selector, depth));
682 css
683}
684
685/// One rule per depth: its fill and its edge, together.
686///
687/// A depth and nothing else. `.raised` says a surface sits on what is behind
688/// it, which is a statement about the shape and not about what happens when a
689/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
690/// named surfaces are where interaction lives: `.card` and `.button` are the
691/// same depth *and* controls, and they get their states from
692/// [`surface_rules`].
693///
694/// This class carried the interactive set until 0.17.0, which left the
695/// vocabulary with no raised surface that is merely an object. Consumers that
696/// needed one took a control class and cancelled half of it instead: sixteen
697/// elements in goingson across three `.card--*` variants, each re-asserting the
698/// resting fill and bevel on `:hover` and `:active`. Nothing anywhere used
699/// `.raised` itself, so the states were unasked-for in every consumer at once.
700#[must_use]
701pub fn depth_rules(opts: &Emit) -> String {
702 let mut css = String::new();
703 for depth in [Depth::Raised, Depth::Well] {
704 let Some(class) = depth_class(depth, opts) else {
705 continue;
706 };
707 css.push_str(&depth_rule(&class, depth));
708 }
709 css
710}
711
712/// The three surfaces that are a depth with a name.
713///
714/// `button` and `card` are both [`Depth::Raised`], and `field` is a
715/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
716/// gives a text field. Their bodies come out identical by construction rather
717/// than by hand: three hand-written copies in goingson's stylesheet is what
718/// phase A deletes, and generating them from one call is what stops them
719/// drifting apart again.
720fn surface_rules(opts: &Emit) -> String {
721 let mut css = String::new();
722 for name in ["button", "card"] {
723 let c = class(name, opts);
724 css.push_str(&depth_rule(&c, Depth::Raised));
725 css.push_str(&interactive_rules(&c, Depth::Raised, opts));
726 }
727
728 let field = class("field", opts);
729 css.push_str(&depth_rule(&field, Depth::Well));
730
731 // A field takes focus and refuses input like everything else here, and got
732 // neither until now, which is why all three apps hand-write a focus ring
733 // for it and no two of them match. No hover or pressed: a text field does
734 // not light up under the pointer and does not invert when clicked, so the
735 // two states `interactive_rules` would add are the two it does not have.
736 css.push_str(&focus_rule(&field, Depth::Well, opts));
737 css.push_str(&disabled_rule(&field, Depth::Well));
738
739 // Keyed on the ARIA attribute rather than on a class, so the visual state
740 // and the accessible state cannot drift apart: there is one fact and both
741 // read it. goingson already drove its invalid styling this way and was
742 // right to; the `.invalid` class this emitted before 0.5.0 was a second
743 // place to forget.
744 //
745 // The ring composes *after* the bevel rather than replacing it. box-shadow
746 // is not additive, so a lone ring silently dropped the well out from under
747 // an invalid field. Flat and unlit: this edge is saying "wrong", and
748 // lighting one side would have it say "raised" at the same time.
749 let _ = writeln!(
750 css,
751 ".{field}[aria-invalid=\"true\"] {{\n box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
752 bevel_var(Bevel::Inset),
753 opts.border_width
754 );
755 css
756}
757
758/// Badges and chips.
759///
760/// The one place phase A changes how goingson looks rather than only where its
761/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
762/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
763/// carrying the raised bevel. Splitting that means reading every call site to
764/// decide which of the two it always was.
765///
766/// What a badge does carry is a [`Tone`], the intent family it shares with
767/// notices and nothing else. Neutral is the bare class rather than a variant,
768/// because it is the absence of a status and not a status called "none".
769/// Text that goes somewhere.
770///
771/// The one inline control, and the vocabulary had no word for it until a
772/// description layer needed one. A table cell has carried `cell-link` since
773/// 0.14.0's part list, deliberately unruled because the cell's own rule covers
774/// it; what was missing is the same thing outside a table, which is what a
775/// described run holds when a sentence contains a link.
776///
777/// Colour and underline only. Whether a link is inline in a sentence or sitting
778/// on its own line is the app's layout, and how much room it takes is
779/// `makeover-geometry`'s. What is here is the pair of signals that say "this
780/// goes somewhere" and nothing that says where it sits.
781///
782/// The visited arm is deliberately absent. A link inside an app points at the
783/// app's own screens, which the user is expected to have been to, so painting
784/// them differently marks almost everything and distinguishes nothing.
785fn link_rules(opts: &Emit) -> String {
786 let mut css = String::new();
787 let link = class("link", opts);
788
789 let _ = writeln!(
790 css,
791 ".{link} {{\n color: var(--action);\n \
792 text-decoration: underline;\n}}"
793 );
794 // The hover step is the same one every other control takes, and it is a
795 // colour rather than a surface: a link has no box to raise.
796 let _ = writeln!(
797 css,
798 "@media (hover: hover) and (pointer: fine) {{\n .{link}:hover \
799 {{\n color: var(--action-hover);\n }}\n}}"
800 );
801 let _ = writeln!(
802 css,
803 ".{link}:focus-visible {{\n outline: {} solid var(--focus-ring);\n \
804 outline-offset: 2px;\n}}",
805 opts.focus_width
806 );
807 // A link is often a `<button>` rather than an `<a>`: a renderer picks the
808 // element from the method, so a link that writes is a button that has to
809 // stop looking like one.
810 let _ = writeln!(
811 css,
812 "button.{link} {{\n background: none;\n border: none;\n \
813 padding: 0;\n font: inherit;\n cursor: pointer;\n}}"
814 );
815 css
816}
817
818fn token_rules(opts: &Emit) -> String {
819 let mut css = String::new();
820
821 // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
822 // and a label with an edge says it can be pressed.
823 let badge = class("badge", opts);
824 let _ = writeln!(
825 css,
826 ".{badge} {{\n color: var(--{});\n}}",
827 Tone::Neutral.token()
828 );
829 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
830 let _ = writeln!(
831 css,
832 ".{badge}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
833 tone.token()
834 );
835 }
836
837 // A button carries the four tones a badge does. It had none, on the reading
838 // that a control's colour is its surface rather than its text, and that
839 // reading has one hole big enough to matter: the button that destroys
840 // something. Every consumer had written that rule itself, and a description
841 // that says `Tone::Danger` on an act had nowhere for it to land.
842 //
843 // Colour and not a fill, matching the badge. A red surface is a decision
844 // about emphasis that belongs to an app's own layer, and two of them
845 // fighting is worse than neither.
846 let button = class("button", opts);
847 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
848 let _ = writeln!(
849 css,
850 ".{button}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
851 tone.token()
852 );
853 }
854
855 // A chip holds itself down, which is `Depth::pressed` arrived at
856 // independently by two apps. `removable` is a remove affordance, so it is
857 // markup and waits for phase B.
858 let chip = class("chip", opts);
859 let unlatched = Token::Chip { removable: false };
860 css.push_str(&depth_rule(&chip, unlatched.depth(false)));
861 css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
862 css.push_str(&depth_rule(
863 &format!("{chip}.latched"),
864 unlatched.depth(true),
865 ));
866 css
867}
868
869/// The three selectors, each named by what it picks.
870///
871/// A tab comes *forward* to join the pane it opens, which is why
872/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
873/// are held in. That is the folder semantic, and it is the whole reason the
874/// three are not one member with a flag.
875///
876/// [`Selector::abutting`] is not emitted: whether the options touch is
877/// spacing, and spacing is `makeover-geometry`'s question to answer.
878///
879/// Both states emit as of makeover-layout 0.3.0. Before it the description
880/// named only the chosen option, so an unchosen one fell through to
881/// [`Depth::Flat`] and nothing was drawn for it, which left goingson's tab
882/// strip hand-writing the recess that makes its chosen tab read as forward.
883fn selector_rules(opts: &Emit) -> String {
884 let mut css = String::new();
885 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
886 let c = class(option_class(selector), opts);
887 css.push_str(&depth_rule(&c, selector.unchosen()));
888 css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
889 css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
890 }
891 css
892}
893
894/// The parts of a list row.
895///
896/// The list is written out rather than derived because `RowPart` is
897/// `#[non_exhaustive]` as of makeover-layout 0.9.0, so there is nothing to
898/// iterate. A member added upstream emits no rule until it is named here, which
899/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
900/// [`part_class`] carries the same list and the same obligation.
901fn row_rules(opts: &Emit) -> String {
902 let mut css = String::new();
903
904 // The container the rows sit in. Three zeroes and a keyword, all of them
905 // undoing a browser default the description never asked for: a described
906 // list of SSH keys is not a bulleted list, and it rendered as one because
907 // nothing here said otherwise. Not a size: there is no magnitude in it,
908 // which is the line this crate holds.
909 let _ = writeln!(
910 css,
911 ".{} {{\n list-style: none;\n margin: 0;\n padding: 0;\n}}",
912 class("list", opts)
913 );
914
915 for part in [
916 RowPart::Primary,
917 RowPart::Secondary,
918 RowPart::Meta,
919 RowPart::Actions,
920 RowPart::Tokens,
921 RowPart::Proportion,
922 ] {
923 let c = class(part_class(part), opts);
924
925 // Actions carry controls rather than text, and `RowPart::intent` says
926 // so by returning the same intent inheriting already gives. Pinning it
927 // would be louder than saying nothing. Tokens answer alike, for their
928 // own reason: each token carries its own tone, and a colour on the
929 // strip would fight the things sitting in it. A proportion is the same
930 // case again: the meter inside carries the tone.
931 if !matches!(
932 part,
933 RowPart::Actions | RowPart::Tokens | RowPart::Proportion
934 ) {
935 let _ = writeln!(css, ".{c} {{\n color: var(--{});\n}}", part.intent());
936 }
937
938 // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
939 // otherwise and was not honoured here from 0.23.0; makeover-layout
940 // 0.13.0 retired the method, so there is no longer a description saying
941 // one thing and a renderer doing another.
942 //
943 // The rule was `opacity: 0` gated to pointer devices, revealed on
944 // `:hover` and on `:focus-within`. Each escape it needed was a report
945 // that hiding was wrong for somebody: `focus-within` because tabbing
946 // could never reach an action; the gate because a fingertip had no way
947 // to unhide, which both webview apps had already hand-written
948 // `opacity: 1` to undo. What was left was a control hidden from
949 // exactly one group: people using a pointer, who are also the group
950 // scanning a list to find out what can be done to a row.
951 //
952 // A settings screen is where that reads worst: the whole reason to be
953 // on it is to remove a key, and the button doing so was invisible
954 // until pointed at. A table cell's actions were never hidden, so the
955 // two arrangements now agree.
956 }
957
958 // A part that may take two lines. `Flow::Tight` gets no rule: one line is
959 // what a run already does, and restating it here would put a declaration on
960 // every part in every row to say nothing.
961 //
962 // This is the shape both webview apps had already written by hand and
963 // commented -- Balanced Breakfast on a feed row's title, goingson on a
964 // problem's body -- which is the whole argument for the description
965 // carrying it. `-webkit-` prefixed and unprefixed together: the prefixed
966 // trio is what every engine actually implements, and `line-clamp` is the
967 // standard property landing behind it.
968 let _ = writeln!(
969 css,
970 ".{} {{\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: {lines};\n line-clamp: {lines};\n overflow: hidden;\n}}",
971 class("row-relaxed", opts),
972 lines = Flow::Relaxed.lines()
973 );
974
975 css
976}
977
978/// A row of things that share their space, and what each fallback gets here.
979///
980/// Ruling: wiki `layout-room-and-fallback`, Max 2026-08-18. The bug it answers
981/// is goingson's `styles.css:702`, which pinned every `.page-header` over the
982/// pill strip with `position: absolute` and so took the toolbar out of flow:
983/// zero width contributed to the row it shared, nothing able to collide with
984/// it, and therefore nothing preventing the collision. Rule 1 of the ruling is
985/// that every described member is in flow, and these rules are how that is kept
986/// rather than asked for.
987///
988/// # The floor, which is most of the fix
989///
990/// `.run > *` gets `min-width: min-content`. That is the derived minimum the
991/// ruling asks for, in this renderer's own unit and stated by the browser
992/// rather than by anybody: a member cannot be squeezed narrower than what is
993/// in it, so members in one flow push each other instead of overlapping. It
994/// costs no query and no number, and it is what fixes all four measured widths
995/// whichever fallback the group declared.
996///
997/// # What each fallback gets, exactly
998///
999/// [`Fallback::Wrap`] is `flex-wrap: wrap`, which is exact. The browser wraps
1000/// the run when the members no longer fit, deciding that from their own
1001/// intrinsic widths, which is the derived minimum doing the whole job.
1002///
1003/// [`Fallback::Stack`] is wrap plus `flex: 1 1 max-content` on the members, so
1004/// a member that cannot sit beside its sibling takes a line of its own and
1005/// fills it. For the two-member run this was ruled on -- a tab strip and a
1006/// band -- that is precisely "a row becomes a column".
1007///
1008/// [`Fallback::Shed`] and [`Fallback::Menu`] get wrap, and this renderer is
1009/// honouring less than the description says. **CSS cannot express either one
1010/// without breaking the ruling's own first constraint.** Both need to know that
1011/// the run is out of room in order to take a member out of it, a container
1012/// query is the only construct that can ask, and `@container` compares against
1013/// a `<length>` -- there is no `@container (inline-size < min-content)`. So
1014/// every honest spelling of Shed here needs an authored breakpoint, which is
1015/// the thing the ruling exists to forbid, and the dishonest ones are worse: a
1016/// clamped height clips by document order rather than by [`Priority`], and
1017/// `display: none` under a viewport `@media` is the `nth-child(n+5)` bug the
1018/// vocabulary replaced.
1019///
1020/// Wrapping is the right thing to do instead. It keeps every member reachable,
1021/// which is the property that was actually broken -- goingson's new-contact
1022/// button left the viewport entirely at 560 -- and it keeps rule 1. A renderer
1023/// answering with less than was described is precedented and deliberate here:
1024/// [`makeover_layout::Region::Columns`] says a terminal stacking a board's
1025/// columns is honouring the description rather than degrading it.
1026///
1027/// The real mechanism needs the shed members to have somewhere to go, which is
1028/// markup and belongs to quasi-webview: an overflow control is a member of the
1029/// run, and the description does not yet say that a member *is* one. Filed
1030/// rather than guessed at.
1031fn run_rules(opts: &Emit) -> String {
1032 let run = class("run", opts);
1033 let mut css = String::new();
1034
1035 // `flex-wrap: nowrap` is stated rather than left to the default, because
1036 // the fallbacks below are read as overrides of this line and a reader
1037 // should not have to know which way flexbox leans to see that.
1038 //
1039 // No gap. Spacing between members is the app's, the same way this crate
1040 // states no margins anywhere else; a gap here would be a size, and the one
1041 // hardcoded size in the mechanism is makeover-geometry's contact patch.
1042 let _ = writeln!(
1043 css,
1044 ".{run} {{\n display: flex;\n flex-wrap: nowrap;\n align-items: center;\n}}"
1045 );
1046
1047 // The derived minimum, and the whole reason a member can no longer be
1048 // overlapped. `min-width: auto` is flexbox's default for a flex item and is
1049 // *not* the same thing: auto lets an item be compressed below its content
1050 // in a nowrap run, which is how a toolbar ends up drawn over a tab strip
1051 // even without anything leaving the flow.
1052 let _ = writeln!(css, ".{run} > * {{\n min-width: min-content;\n}}");
1053
1054 for fallback in [
1055 Fallback::Wrap,
1056 Fallback::Stack,
1057 Fallback::Shed,
1058 Fallback::Menu,
1059 ] {
1060 let name = fallback_class(fallback);
1061 let c = class(name, opts);
1062 let _ = writeln!(css, ".{c} {{\n flex-wrap: wrap;\n}}");
1063 if matches!(fallback, Fallback::Stack) {
1064 let _ = writeln!(css, ".{c} > * {{\n flex: 1 1 max-content;\n}}");
1065 }
1066 }
1067
1068 css
1069}
1070
1071/// Every class [`fallback_class`] can return, plus the run itself.
1072///
1073/// [`ROW_PART_CLASSES`](crate::list::ROW_PART_CLASSES)'s reasoning and the same
1074/// obligation: a `match` over a `#[non_exhaustive]` enum cannot be enumerated
1075/// from outside, so the list sits beside it and a test holds the two together.
1076/// `run` is in it because it is emitted in its own right rather than only as a
1077/// fallback's fallback.
1078pub const RUN_CLASSES: &[&str] = &["run", "run-wrap", "run-stack", "run-shed", "run-menu"];
1079
1080/// The class a run carries for what it does when it is tight.
1081///
1082/// A run always carries `.run` as well, so an unrecognised fallback -- the enum
1083/// is `#[non_exhaustive]` -- lands as a plain nowrap row with the min-content
1084/// floor still under it. That is the safe failure: every member in flow and
1085/// none overlapped, which is the property, with only the rearrangement missing.
1086#[must_use]
1087pub fn fallback_class(fallback: Fallback) -> &'static str {
1088 match fallback {
1089 Fallback::Wrap => "run-wrap",
1090 Fallback::Stack => "run-stack",
1091 Fallback::Shed => "run-shed",
1092 Fallback::Menu => "run-menu",
1093 _ => "run",
1094 }
1095}
1096
1097/// The progress trough these rules fill.
1098///
1099/// This was renderer-local chrome with nothing behind it until makeover-layout
1100/// 0.10.0, which is the unusual order: the tones below were emitted for every
1101/// bar in the tree while the only way to describe one was to concatenate the
1102/// numbers into a heading. `Meter` is the word that arrived late, and
1103/// [`meter::meter_html`](crate::meter::meter_html) is what now fills these.
1104///
1105/// The rules stay a superset of what a description can ask for. An app drawing
1106/// its own bar keeps these classes, which is what the four goingson grew
1107/// independently were adopted onto.
1108///
1109/// The trough is a [`Depth::Well`], the same reading a text field gets:
1110/// something with its content down inside it.
1111fn progress_rules(opts: &Emit) -> String {
1112 let progress = class("progress", opts);
1113 // `progress-fill` rather than a bare `fill`: an unprefixed build claims
1114 // these names in the app's own stylesheet, and `.fill` is grabby enough to
1115 // catch things that have nothing to do with progress. goingson already
1116 // calls it `.progress-fill`, so this is also the name that deletes.
1117 let fill = class("progress-fill", opts);
1118 let mut css = depth_rule(&progress, Depth::Well);
1119
1120 // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
1121 // place this differs from the badge rules, and deliberately: a badge with
1122 // no status is a muted label, while a bar with no status is still
1123 // reporting progress, and `content-muted` would read as disabled.
1124 let _ = writeln!(
1125 css,
1126 ".{progress} > .{fill} {{\n background: var(--action);\n}}"
1127 );
1128
1129 // A bar can be saying something, same as a badge: goingson colours subtask
1130 // progress as success and an over-estimate as danger, which is real
1131 // information rather than decoration. Emitting the tones is what lets that
1132 // survive adoption instead of staying hand-written.
1133 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1134 let _ = writeln!(
1135 css,
1136 ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n background: var(--{0});\n}}",
1137 tone.token()
1138 );
1139 }
1140 css
1141}
1142
1143/// A strip of figures, and the two spans inside each one.
1144///
1145/// Colour only, which is the deferral rule applied to a component that badly
1146/// wants to break it. A figure reads as a figure because the value is set large
1147/// over a small caption, and that is a size: `makeover-geometry` answers how
1148/// much space and this crate answers what the thing is. Emitting `font-size`
1149/// here would be this crate naming a value, which is the one thing it is defined
1150/// by not doing, and `progress_rules` is the precedent — it emits the tones and
1151/// never the width, because the width is not its to know.
1152///
1153/// So the arrangement and the type scale are the app's, and what is generated is
1154/// the part an app cannot get right by itself: which of the two spans carries
1155/// the tone.
1156fn figure_rules(opts: &Emit) -> String {
1157 let figure = class("figure", opts);
1158 let value = class("figure-value", opts);
1159 let caption = class("figure-caption", opts);
1160 let change = class("figure-change", opts);
1161 let mut css = String::new();
1162
1163 let _ = writeln!(
1164 css,
1165 ".{figure} > .{value} {{\n color: var(--{});\n}}",
1166 Tone::Neutral.token()
1167 );
1168 let _ = writeln!(
1169 css,
1170 ".{figure} > .{caption} {{\n color: var(--content-muted);\n}}"
1171 );
1172 let _ = writeln!(
1173 css,
1174 ".{figure} > .{change} {{\n color: var(--content-muted);\n}}"
1175 );
1176
1177 // A toned figure tones one part and never the caption. The caption is the
1178 // noun and stays muted.
1179 //
1180 // Which part depends on whether there is a change, and that is the whole of
1181 // what 0.13.0 changed here. A figure with a delta is an ordinary number that
1182 // has moved in a direction worth reading, so the delta takes the colour and
1183 // the number stays plain; a figure without one has nowhere else to put it.
1184 // `:has` is what lets one attribute mean both, and the alternative was the
1185 // emitter deciding by writing the attribute onto a different element, which
1186 // leaves two elements able to disagree about a figure's one meaning.
1187 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1188 let _ = writeln!(
1189 css,
1190 ".{figure}[data-tone=\"{0}\"] > .{change} {{\n color: var(--{0});\n}}",
1191 tone.token()
1192 );
1193 let _ = writeln!(
1194 css,
1195 ".{figure}[data-tone=\"{0}\"]:not(:has(> .{change})) > .{value} \
1196 {{\n color: var(--{0});\n}}",
1197 tone.token()
1198 );
1199 }
1200 css
1201}
1202
1203/// A picture, its frame and its caption.
1204///
1205/// `makeover_layout::Image` arrived at 0.21.0, found by trying to describe MNW's
1206/// carousel and discovering nothing named a picture.
1207///
1208/// # The frame is a border, and this is the one place a bevel is wrong
1209///
1210/// 0.36.0 emitted [`Depth::Raised`] here through [`depth_rule`], the same call
1211/// `button` and `card` make. It was wrong, and MNW's landing page is where it
1212/// showed: **the frames had no visible edge at all.**
1213///
1214/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow — a
1215/// 1px light run at the top-left and a dark one at the bottom-right, drawn
1216/// **inside** the element's box. On a button or a card that box is a surface
1217/// this crate owns, so an inset edge reads as the surface catching the light.
1218/// On a picture it is drawn on top of the picture, over whatever pixels the
1219/// image happens to have at its border. MNW's screenshots are light-on-light
1220/// parchment, so the light half landed on a light image and the frame
1221/// disappeared.
1222///
1223/// **You cannot bevel a surface you do not own.** A picture's content is the
1224/// app's, arrives at request time, and can be any colour, so its edge has to
1225/// sit *outside* the content rather than on it. That is a border.
1226///
1227/// The fill stays, and it is not decoration: it is what shows through a
1228/// transparent PNG and what stands in the frame's place while the image is
1229/// still loading.
1230///
1231/// This is a real limit on [`Depth`] rather than a special case. Every other
1232/// consumer of a depth draws its own surface; a picture is the first member
1233/// whose surface belongs to someone else.
1234///
1235/// # No size
1236///
1237/// `width: 100%` and nothing else. How large a picture is depends on the box it
1238/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
1239/// and a renderer that picked one would be answering for every consumer at
1240/// once. This is where `figure_rules` landed for the same reason.
1241fn picture_rules(opts: &Emit) -> String {
1242 let picture = class("picture", opts);
1243 let img = class("picture-img", opts);
1244 let caption = class("picture-caption", opts);
1245 let mut css = String::new();
1246
1247 // Block, or an inline image sits on the text baseline and carries a
1248 // descender's worth of space under it that no app ever wants and every app
1249 // deletes by hand. The border is the frame; see the type docs for why it is
1250 // not the bevel every other surface here gets.
1251 let _ = writeln!(
1252 css,
1253 ".{img} {{\n display: block;\n width: 100%;\n height: auto;\n \
1254 background: var(--{});\n border: {} solid var(--border);\n}}",
1255 Fill::Raised.token(),
1256 opts.border_width
1257 );
1258
1259 // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
1260 // so it is the bare rule above and needs nothing here.
1261 let _ = writeln!(
1262 css,
1263 ".{img}[data-fit=\"cover\"] {{\n height: 100%;\n object-fit: cover;\n}}"
1264 );
1265 let _ = writeln!(
1266 css,
1267 ".{img}[data-fit=\"contain\"] {{\n height: 100%;\n object-fit: contain;\n}}"
1268 );
1269
1270 // A caption reads back one step, which is `figure-caption`'s answer and the
1271 // same claim: it says what the thing above it is, and it is not the thing.
1272 let _ = writeln!(
1273 css,
1274 ".{picture} > .{caption} {{\n color: var(--content-muted);\n}}"
1275 );
1276
1277 css
1278}
1279
1280/// A region showing one child at a time, and the chrome that moves between them.
1281///
1282/// [`makeover_layout::Showing`] lets a description say that a region holds
1283/// several children and shows some of them. A renderer derives its own chrome
1284/// from that, which is what stops every renderer growing a `match` on a widget
1285/// name; these are the rules the derived chrome needs.
1286///
1287/// # Why the default is every child, and the enhancement takes them away
1288///
1289/// The controls are a lie until something binds them. A prev button rendered
1290/// into a document with no script is a control that looks live and answers
1291/// nothing, and the reader it lies to is exactly the one who cannot see the
1292/// other children either — the collapsing and the moving are the same half.
1293///
1294/// So the rules run in the direction the enhancement does. Nothing here hides a
1295/// child and nothing here shows a control. Whatever binds the region sets
1296/// `data-ready` on it, and that is what collapses the stack to one and reveals
1297/// the row that moves it. A reader with no script gets every child in order and
1298/// no controls, which is more content rather than less, and a reader with
1299/// script gets a settled page rather than a stack that jumps to one frame after
1300/// load.
1301///
1302/// MNW proved this shape by hand — a `<noscript>` stylesheet opening its
1303/// carousel back out — and it is here rather than there because the property is
1304/// the description's, not one app's.
1305///
1306/// # Not spacing
1307///
1308/// The row's gaps are `makeover-geometry`'s question and are absent for
1309/// [`row_rules`]'s reason. What is here is `display`, which carries no
1310/// magnitude, and the muted readout, which is the same claim `picture-caption`
1311/// makes: it says where you are among the children and it is not one of them.
1312fn showing_rules(opts: &Emit) -> String {
1313 let controls = class("showing", opts);
1314 let position = class("showing-position", opts);
1315 let frame = class("showing-frame", opts);
1316 let mut css = String::new();
1317
1318 // Hidden until something binds it, which is the whole argument above.
1319 let _ = writeln!(css, ".{controls} {{\n display: none;\n}}");
1320 // Block, and nothing about how the three sit in it. A button and a span are
1321 // inline already, so they make a row without this crate saying so, and
1322 // saying so is where `align-items` and a gap would follow -- both spacing,
1323 // both `makeover-geometry`'s, and `row_rules` refuses them for the same
1324 // reason.
1325 let _ = writeln!(
1326 css,
1327 "[data-ready] > .{controls} {{\n display: block;\n}}"
1328 );
1329
1330 // A child is in flow until the region is bound, and then only the current
1331 // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
1332 // are: one name for the state, set by whoever knows it.
1333 let _ = writeln!(
1334 css,
1335 "[data-ready] > .{frame}:not(.current) {{\n display: none;\n}}"
1336 );
1337
1338 // Reads back one step. `picture-caption`'s rule and its reason.
1339 let _ = writeln!(css, ".{position} {{\n color: var(--content-muted);\n}}");
1340
1341 css
1342}
1343
1344/// A time axis: the container, its gridlines and ruler, and the placed things.
1345///
1346/// `makeover-layout` 0.24.0's [`Track`](makeover_layout::Track), and the first
1347/// member here whose whole point is *position*. That makes the magnitude line
1348/// this crate keeps worth restating rather than assuming.
1349///
1350/// # Where the numbers come from
1351///
1352/// Every value that varies per item is a custom property the caller sets
1353/// inline, and every rule here reads one. `--track-at` and `--track-for` are
1354/// percentages of the span, which
1355/// [`Track::fraction`](makeover_layout::Track::fraction) computes once so three
1356/// renderers cannot disagree about it. Nothing here knows a pixel.
1357///
1358/// That is what lets the stylesheet stay static while the items move: an entry
1359/// carries `style="--track-at: 37.5%; --track-for: 4.166%"` and the rule below
1360/// turns it into a box. The alternative was emitting a rule per item, which is
1361/// a stylesheet that grows with the data.
1362///
1363/// **The height of the track is the app's**, not this crate's. 96 quarter-hour
1364/// slots at some slot height is a size, and a size is `makeover-geometry`'s
1365/// question -- the same refusal `figure_rules` and `placeholder_rules` make.
1366/// Percentages need a resolved height above them, so `.track` gets
1367/// `position: relative` and nothing else; the app says how tall a day is.
1368///
1369/// # Overlap
1370///
1371/// Two things at the same time is intrinsic to an axis and has no analogue in a
1372/// list. The description does not declare it -- `Placement::overlaps` derives it
1373/// from the times -- so what arrives here is a lane index and a lane count, and
1374/// the rule divides the width. A renderer that would rather stack them ignores
1375/// both properties and the defaults give it one full-width lane.
1376fn track_rules(opts: &Emit) -> String {
1377 let track = class("track", opts);
1378 let slot = class("track-slot", opts);
1379 let tick = class("track-tick", opts);
1380 let entry = class("track-entry", opts);
1381 let mut css = String::new();
1382
1383 // The positioning context every entry resolves against, and the whole of
1384 // what this crate says about the container. No height: see the doc above.
1385 let _ = writeln!(css, ".{track} {{\n position: relative;\n}}");
1386
1387 // Gridlines and the ruler are the axis reading itself back, which is
1388 // `picture-caption` and `showing-position`'s claim: about the thing rather
1389 // than one of the things.
1390 //
1391 // `border_width` rather than a literal, the way `depth_rule` writes its
1392 // edge. A gridline is the one place a timeline would most naturally reach
1393 // for a hardcoded 1px, and a hardcoded 1px is this crate naming a size.
1394 let _ = writeln!(
1395 css,
1396 ".{slot} {{\n border-top: {} solid var(--border);\n}}",
1397 opts.border_width
1398 );
1399 let _ = writeln!(css, ".{tick} {{\n color: var(--content-muted);\n}}");
1400
1401 // The one rule that does real work. Top and height are the placement;
1402 // left and width are the lane. Both lane properties default so an entry
1403 // that names neither is full width, which is the common case and the one a
1404 // renderer gets for free.
1405 let _ = writeln!(
1406 css,
1407 ".{entry} {{\n \
1408 position: absolute;\n \
1409 top: var(--track-at, 0%);\n \
1410 height: var(--track-for, 100%);\n \
1411 left: calc(var(--track-lane, 0) / var(--track-lanes, 1) * 100%);\n \
1412 width: calc(100% / var(--track-lanes, 1));\n\
1413 }}"
1414 );
1415
1416 css
1417}
1418
1419/// A region's stand-in, and the header of a table that can be reordered.
1420///
1421/// Both are 0.12.0 members and both are colour and affordance only, which is
1422/// where `figure_rules` landed after trying to emit a type scale. How much room
1423/// a stand-in gets is a size — goingson has the same one at three, as
1424/// `--compact`, `--dashboard` and `--padded` — and a size is
1425/// `makeover-geometry`'s question.
1426///
1427/// The caret is the one thing here that is neither colour nor affordance, and it
1428/// is a renderer's own expression rather than a value the description named:
1429/// `aria-sort` is what the table actually says, and this turns it into something
1430/// visible for everyone not using a screen reader. A terminal draws its own; an
1431/// immediate-mode painter draws its own.
1432fn state_rules(opts: &Emit) -> String {
1433 let placeholder = class("placeholder", opts);
1434 let text = class("placeholder-text", opts);
1435 let heading = class("table-heading", opts);
1436 let mut css = String::new();
1437
1438 let _ = writeln!(
1439 css,
1440 ".{placeholder} > .{text} {{\n color: var(--content-muted);\n}}"
1441 );
1442 // Only the failure is toned. An empty list is the normal state of a new
1443 // install, and `Readiness::tone` is what says so.
1444 let _ = writeln!(
1445 css,
1446 ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n color: var(--{0});\n}}",
1447 Tone::Danger.token()
1448 );
1449
1450 // A header that reorders the table is a control, and the pointer is the
1451 // only part of saying so that is not the app's own type and spacing.
1452 let _ = writeln!(
1453 css,
1454 ".{heading}[data-sortable] {{\n cursor: pointer;\n}}"
1455 );
1456 // The caret carries its own leading space, the way `makeover-tui` and
1457 // `makeover-immediate` both write `" \u{25B2}"`. It used to be emitted bare,
1458 // and both apps that adopted the vocabulary had to put the gap back in their
1459 // own stylesheets on the same afternoon -- each having to work out first that
1460 // app CSS outranks this crate's cascade layer, so adding the space the
1461 // obvious way, as `content`, silently wins over the glyph and leaves the
1462 // heading with no caret at all. A consumer should not have to know that, and
1463 // with the space emitted here there is nothing left for one to add.
1464 //
1465 // Three states, three tones, on the convention in wiki
1466 // `three-tone-convention`. A column in force is `content`; a column offering
1467 // to reorder and not doing it now is `content-secondary`, because it still
1468 // answers a press; a column that is not sortable emits no caret at all and
1469 // takes nothing. The idle arm used to hide its glyph and reserve the box,
1470 // which cost a reflow-free press and said nothing. It draws now, and the
1471 // reservation stops being a thing to get right.
1472 //
1473 // The glyph is `Sort::glyph`, escaped rather than written: a CSS `content`
1474 // string cannot carry the character literally through this file's own
1475 // escaping, and spelling it here as well would put the third copy back that
1476 // `makeover-layout` 0.27.5 exists to remove.
1477 let _ = writeln!(
1478 css,
1479 ".{heading}[data-sortable]::after \
1480 {{\n content: \" {}\";\n color: var(--content-secondary);\n}}",
1481 css_escape(Sort::Ascending.glyph())
1482 );
1483 for direction in [Sort::Ascending, Sort::Descending] {
1484 let _ = writeln!(
1485 css,
1486 ".{heading}[aria-sort=\"{}\"]::after \
1487 {{\n content: \" {}\";\n color: var(--content);\n}}",
1488 direction.as_str(),
1489 css_escape(direction.glyph())
1490 );
1491 }
1492 css
1493}
1494
1495/// The frame a table sits in.
1496///
1497/// # Why this is a CSS table and not the grid the rest of the module assumes
1498///
1499/// A grid row needs `grid-template-columns`, which has to name every column in
1500/// order, so it cannot be written without knowing the columns. That is what
1501/// [`list::narrowing_css`] is for, and it works: goingson builds `tables.css` in
1502/// its own `build.rs` out of it, and nothing here changes that.
1503///
1504/// It does not work for a table a *description* produced. Those columns are
1505/// known at render time rather than at build time, and the rules would have to
1506/// travel with the markup: a `<style>` element per table, which needs
1507/// `style-src 'unsafe-inline'` and so blocks the MNW server's standing plan to
1508/// drop it. The head is not an escape: a table swapped in by htmx after a
1509/// delete arrives as a fragment with no head at all.
1510///
1511/// A CSS table aligns its columns across rows knowing nothing about how many
1512/// there are, so there is no track list to emit and nothing per-table to carry.
1513/// The cost is that a described table cannot take a per-column fixed length,
1514/// which costs nothing today: [`Sizing`](list::Sizing) is looked up by column
1515/// name and a description carries no lengths to put in it, so every track a
1516/// described table could ask for is already content, fill or auto.
1517///
1518/// [`Priority`] hiding is unchanged in kind. It moves from a generated
1519/// `display: none` per dropped column to one rule per drop class, which is the
1520/// same fact addressed by class rather than by cutoff, and still never by
1521/// position.
1522fn table_rules(opts: &Emit) -> String {
1523 let table = class("table", opts);
1524 let head = class("table-head", opts);
1525 let row = class("table-row", opts);
1526 let heading = class("table-heading", opts);
1527 let cell = class("cell", opts);
1528 let mut css = String::new();
1529
1530 let _ = writeln!(
1531 css,
1532 ".{table} {{\n display: table;\n width: 100%;\n}}"
1533 );
1534 let _ = writeln!(css, ".{head},\n.{row} {{\n display: table-row;\n}}");
1535 let _ = writeln!(css, ".{heading},\n.{cell} {{\n display: table-cell;\n}}");
1536
1537 // A content column shrinks to what is in it. `width: 1%` is how a CSS table
1538 // is told that: auto layout hands the slack to the columns that asked for
1539 // room, and a column asking for almost none gets what it needs and no more.
1540 // The `nowrap` is what stops it being given less by wrapping.
1541 let _ = writeln!(
1542 css,
1543 ".{} {{\n white-space: nowrap;\n width: 1%;\n}}",
1544 class("cell-content", opts)
1545 );
1546
1547 // A fixed column has no length to be fixed to. The description carries none
1548 // and `Sizing` is not reachable from here, so it behaves as content: the
1549 // honest answer to a width nobody supplied, and the same one `Sizing::track`
1550 // gives it.
1551 let _ = writeln!(
1552 css,
1553 ".{} {{\n white-space: nowrap;\n}}",
1554 class("cell-fixed", opts)
1555 );
1556
1557 // Optional columns go at the narrowest class, secondary ones go with them,
1558 // which is the cutoff walk `kept_at` describes said as two media queries.
1559 // Essential columns have no rule at all, because never dropping is what not
1560 // being mentioned already means.
1561 for (size, drops) in [
1562 (
1563 SizeClass::Compact,
1564 &["cell-drops-first", "cell-drops-next"][..],
1565 ),
1566 (SizeClass::Medium, &["cell-drops-first"][..]),
1567 ] {
1568 let selectors: Vec<String> = drops
1569 .iter()
1570 .map(|drop| format!(".{}", class(drop, opts)))
1571 .collect();
1572 css.push_str(&gated(
1573 Some(&size.media_condition()),
1574 &format!("{} {{\n display: none;\n}}\n", selectors.join(",\n")),
1575 ));
1576 }
1577
1578 // What is inside a cell, which the table side could not say until
1579 // makeover-layout 0.14.0. Every cell was one `.cell` and one content
1580 // colour, so a button in a cell was painted as text -- the drift
1581 // `RowPart::intent` has prevented for list rows since 0.2.0 and prevented
1582 // for nothing here.
1583 //
1584 // The colour goes on `.cell-value` rather than on `.cell`, and that
1585 // placement is the whole fix. On the container it would cascade into the
1586 // tokens and the controls sitting beside the text, which is the bug said
1587 // in one rule; on the part that is text, it reaches text and stops.
1588 for part in [
1589 CellPart::Value,
1590 CellPart::Tokens,
1591 CellPart::Actions,
1592 CellPart::Link,
1593 ] {
1594 // Three of the four inherit, each for its own reason: a token carries
1595 // its own tone, an action is a control rather than text, and a link
1596 // takes the action colour from the anchor it is. `CellPart::intent`
1597 // says so by answering with the intent inheriting already gives, and
1598 // pinning that would be louder than saying nothing.
1599 //
1600 // Written as a skip-list rather than as a match on Value, so a member
1601 // added upstream gets its intent emitted rather than being silently
1602 // dropped. That is the same trade `part_class`'s fallback makes: land
1603 // plainly, never land as nothing.
1604 if !matches!(part, CellPart::Tokens | CellPart::Actions | CellPart::Link) {
1605 let _ = writeln!(
1606 css,
1607 ".{} {{\n color: var(--{});\n}}",
1608 class(cell_part_class(part), opts),
1609 part.intent()
1610 );
1611 }
1612 }
1613
1614 css
1615}
1616
1617/// The component layer: every named thing phase A emits.
1618///
1619/// No scrollbar track. It was on the phase A list and came off: eight lines of
1620/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
1621/// would want handed to it, so it stays with the apps.
1622#[must_use]
1623pub fn component_rules(opts: &Emit) -> String {
1624 let mut css = String::new();
1625 css.push_str(&surface_rules(opts));
1626 css.push_str(&link_rules(opts));
1627 css.push_str(&token_rules(opts));
1628 css.push_str(&selector_rules(opts));
1629 css.push_str(&row_rules(opts));
1630 css.push_str(&run_rules(opts));
1631 css.push_str(&progress_rules(opts));
1632 css.push_str(&figure_rules(opts));
1633 css.push_str(&picture_rules(opts));
1634 css.push_str(&showing_rules(opts));
1635 css.push_str(&track_rules(opts));
1636 css.push_str(&state_rules(opts));
1637 css.push_str(&table_rules(opts));
1638 css
1639}
1640
1641/// The whole phase-A stylesheet: properties, depth rules and components, in
1642/// [`CSS_LAYER`], under a generated-file banner.
1643///
1644/// The banner sits outside the layer, because a comment participates in no
1645/// cascade and a reader opening the file should see what it is before seeing
1646/// an at-rule.
1647#[must_use]
1648pub fn stylesheet(opts: &Emit) -> String {
1649 format!(
1650 "/* Generated by makeover-webview from makeover-layout. Do not edit.\n \
1651 Depth is a fill and an edge together; naming them apart is what let\n \
1652 them disagree. See the crate's README and wiki note makeover-layout.\n\n \
1653 Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n \
1654 order once in your own stylesheet, or this layer's position is decided\n \
1655 by whichever generated file the browser happens to see first:\n\n \
1656 @layer {CSS_LAYER}, base, components, responsive; */\n{}",
1657 in_css_layer(&format!(
1658 ":root {{\n{}}}\n\n{}\n{}",
1659 bevel_properties(opts),
1660 depth_rules(opts),
1661 component_rules(opts)
1662 ))
1663 )
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668 use super::*;
1669 use makeover_layout::Edge;
1670
1671 #[test]
1672 fn every_fallback_class_is_one_a_checker_knows_about() {
1673 // The obligation ROW_PART_CLASSES carries, for the same reason: a class
1674 // this crate can write and the vocabulary list does not carry is
1675 // invisible to the dead-vocabulary seal and to the overlap check both.
1676 for fallback in [
1677 Fallback::Wrap,
1678 Fallback::Stack,
1679 Fallback::Shed,
1680 Fallback::Menu,
1681 ] {
1682 assert!(
1683 RUN_CLASSES.contains(&fallback_class(fallback)),
1684 "{fallback:?} is missing from RUN_CLASSES"
1685 );
1686 }
1687 let names = crate::vocabulary::names(&Emit::default());
1688 for name in RUN_CLASSES {
1689 assert!(names.contains(*name), "{name} is not in the vocabulary");
1690 }
1691 }
1692
1693 #[test]
1694 fn a_run_gives_every_member_a_floor_it_cannot_be_squeezed_below() {
1695 // The whole of what stops the overlap, and it is not a fallback: it
1696 // applies to every run whatever the group declared. flexbox's default
1697 // min-width is auto, which lets an item be compressed below its own
1698 // content in a nowrap row, and that is how a toolbar is drawn over a
1699 // tab strip even with nothing out of flow.
1700 let css = run_rules(&Emit::default());
1701 assert!(css.contains(".run > * {\n min-width: min-content;\n}"));
1702 // No number anywhere in it. The minimum is derived by the browser from
1703 // what the members contain, which is the ruling's own requirement.
1704 assert!(!css.contains("px"));
1705 assert!(!css.contains("rem"));
1706 assert!(!css.contains("@media"));
1707 }
1708
1709 #[test]
1710 fn room_is_never_asked_of_the_viewport() {
1711 // The 913 case: a window in SizeClass::Expanded holding a group out of
1712 // room. A viewport query answers about the window and would be wrong
1713 // about the group, which is why the table's @media walk is not the
1714 // precedent this follows.
1715 let css = run_rules(&Emit::default());
1716 for size in [SizeClass::Compact, SizeClass::Medium] {
1717 assert!(!css.contains(&size.media_condition()));
1718 }
1719 }
1720
1721 #[test]
1722 fn every_fallback_lands_as_a_class_and_an_unknown_one_lands_plainly() {
1723 let css = run_rules(&Emit::default());
1724 for fallback in [
1725 Fallback::Wrap,
1726 Fallback::Stack,
1727 Fallback::Shed,
1728 Fallback::Menu,
1729 ] {
1730 let class = fallback_class(fallback);
1731 assert!(css.contains(&format!(".{class} {{")), "{class} unemitted");
1732 }
1733 // Stack is the one that also says what a member does with the line it
1734 // took, which is what separates it from wrapping.
1735 assert!(css.contains(".run-stack > * {\n flex: 1 1 max-content;\n}"));
1736 }
1737
1738 #[test]
1739 fn the_emitted_bevel_matches_what_the_apps_already_hand_write() {
1740 // Balanced Breakfast's styles.css, verbatim. Adoption has to be a
1741 // deletion, not a redesign, or nobody will take it.
1742 let opts = Emit::default();
1743 assert_eq!(
1744 bevel_shadow(Bevel::Raised, &opts),
1745 "inset 1px 1px 0 var(--bevel-light), inset -1px -1px 0 var(--bevel-dark)"
1746 );
1747 assert_eq!(
1748 bevel_shadow(Bevel::Inset, &opts),
1749 "inset 1px 1px 0 var(--bevel-dark), inset -1px -1px 0 var(--bevel-light)"
1750 );
1751 }
1752
1753 #[test]
1754 fn no_colour_ever_reaches_the_output() {
1755 let css = stylesheet(&Emit::default());
1756 assert!(!css.contains('#'), "a hex literal escaped into the CSS");
1757 assert!(
1758 !css.contains("rgb"),
1759 "a colour function escaped into the CSS"
1760 );
1761 // Every colour is named, never resolved.
1762 assert!(css.contains("var(--surface-raised)"));
1763 assert!(css.contains("var(--bevel-light)"));
1764 }
1765
1766 #[test]
1767 fn a_well_falls_back_through_css_rather_than_through_rust() {
1768 assert_eq!(
1769 fill_var(Fill::Well),
1770 "var(--surface-well, var(--surface-page))"
1771 );
1772 // Nothing else needs one.
1773 assert_eq!(fill_var(Fill::Raised), "var(--surface-raised)");
1774 assert_eq!(fill_var(Fill::Page), "var(--surface-page)");
1775 }
1776
1777 #[test]
1778 fn raised_and_well_do_not_collapse_onto_each_other() {
1779 let css = depth_rules(&Emit::default());
1780 assert!(css.contains(".raised {"));
1781 assert!(css.contains(".well {"));
1782 assert!(css.contains("var(--bevel-raised)"));
1783 assert!(css.contains("var(--bevel-inset)"));
1784 }
1785
1786 /// The cast shadow is composed here from the tone `makeover` derives, so
1787 /// neither crate has to hold the other's numbers.
1788 ///
1789 /// It is a `:root` property and deliberately not a depth class. There is no
1790 /// `Depth::Overlay` in the description layer, and adding one would be a
1791 /// claim about what a screen means rather than about how it is painted;
1792 /// until something asks for it, a consumer names the property on the rule
1793 /// for the menu or the toast it already has.
1794 #[test]
1795 fn the_cast_shadow_is_a_root_property_not_a_depth() {
1796 let css = bevel_properties(&Emit::default());
1797 assert!(css.contains("--elevation-overlay:"));
1798 assert!(css.contains("var(--elevation)"));
1799 assert!(
1800 !depth_rules(&Emit::default()).contains("elevation"),
1801 "elevation is not a depth class"
1802 );
1803 }
1804
1805 #[test]
1806 fn the_cascade_carries_the_pressed_state() {
1807 let css = surface_rules(&Emit::default());
1808 // The one thing this renderer gets free that the other two resolve by
1809 // hand, eighteen call sites deep in audiofiles' case. Asserted on a
1810 // named surface: pressing belongs to the control, not to the depth.
1811 assert!(css.contains(".card:active {"));
1812 assert!(css.contains(".button:active {"));
1813 }
1814
1815 #[test]
1816 fn the_depth_class_is_a_surface_and_not_a_control() {
1817 let css = depth_rules(&Emit::default());
1818 // The static surface the vocabulary was missing. Sixteen goingson
1819 // elements wore .card and cancelled its hover and press to get this,
1820 // because a raised object that is not pressable had no other spelling.
1821 for state in [":hover", ":active", ":focus-visible", ":disabled"] {
1822 assert!(
1823 !css.contains(&format!(".raised{state}")),
1824 "the depth class claimed {state}: {css}"
1825 );
1826 }
1827 assert!(css.contains("var(--bevel-raised)"), "still raised: {css}");
1828 }
1829
1830 #[test]
1831 fn pressing_moves_the_fill_and_not_only_the_edge() {
1832 // The decision-1 guard, and the regression that mattered: emitting the
1833 // bevel flip alone is what left goingson hand-writing `background:
1834 // var(--surface-sunken)` on .btn, .card and .tag/.badge alike, so none
1835 // of the three could be deleted.
1836 let pressed = interactive_rules("button", Depth::Raised, &Emit::default());
1837 assert!(pressed.contains(".button:active {"));
1838 assert!(
1839 pressed.contains("background: var(--surface-well, var(--surface-page))"),
1840 "pressed dropped its fill: {pressed}"
1841 );
1842 assert!(pressed.contains("box-shadow: var(--bevel-inset)"));
1843 }
1844
1845 #[test]
1846 fn pressed_takes_its_fill_from_the_description_not_from_the_app() {
1847 // goingson presses to --surface-sunken. The description says a pressed
1848 // raised region reads as a well, and makeover says outright that
1849 // surface-sunken cannot serve as one, so the app is the thing that
1850 // moves.
1851 //
1852 // Scoped to the pressed rules rather than to the whole sheet: since
1853 // makeover-layout 0.3.0 an unchosen tab is legitimately
1854 // --surface-sunken, so the token appearing somewhere in the output no
1855 // longer means the app's choice leaked in.
1856 let css = stylesheet(&Emit::default());
1857 let mut checked = 0;
1858 for rule in css.split("}\n") {
1859 if !rule.contains(":active") {
1860 continue;
1861 }
1862 checked += 1;
1863 assert!(
1864 !rule.contains("surface-sunken"),
1865 "a pressed rule took the app's fill: {rule}"
1866 );
1867 }
1868 assert!(checked > 0, "no pressed rules found to check");
1869 assert_eq!(
1870 Depth::Raised.pressed().fill(),
1871 Some(Fill::Well),
1872 "the description changed under us"
1873 );
1874 }
1875
1876 #[test]
1877 fn the_whole_stylesheet_is_emitted_in_the_family_layer() {
1878 // The point of 0.11.0. Unlayered normal declarations outrank every
1879 // named layer, so an app declaring `@layer base, components` loses
1880 // every rule it owns to this file until this file is layered too.
1881 let css = stylesheet(&Emit::default());
1882 assert!(css.contains(&format!("@layer {CSS_LAYER} {{")));
1883
1884 // Exactly one layer block, and nothing outside it but the banner.
1885 assert_eq!(css.matches("@layer").count(), 2, "banner names it once");
1886 let opened = css.find("@layer makeover {").expect("layer opens");
1887 for (i, line) in css.lines().enumerate() {
1888 let before_layer = css.lines().take(i).map(str::len).sum::<usize>() < opened;
1889 if before_layer || line.is_empty() {
1890 continue;
1891 }
1892 assert!(
1893 line.starts_with(" ") || line == "}" || line.starts_with(" "),
1894 "line outside the layer: {line:?}"
1895 );
1896 }
1897 }
1898
1899 #[test]
1900 fn the_generated_sheet_carries_no_trailing_whitespace() {
1901 // A checked-in generated file that a formatter wants to rewrite is a
1902 // diff every time somebody saves it.
1903 let css = stylesheet(&Emit::default());
1904 for (i, line) in css.lines().enumerate() {
1905 assert_eq!(line, line.trim_end(), "trailing whitespace on line {i}");
1906 }
1907 }
1908
1909 #[test]
1910 fn the_banner_tells_an_app_how_to_order_the_layer() {
1911 // Without a declared order the layer's position depends on which
1912 // generated file the browser sees first, which is not a contract.
1913 let css = stylesheet(&Emit::default());
1914 assert!(css.contains("@layer makeover, base, components, responsive;"));
1915 // And the banner is outside the layer, not a rule inside it.
1916 assert!(css.starts_with("/* Generated by makeover-webview"));
1917 }
1918
1919 #[test]
1920 fn a_primitive_owns_every_state_it_implies() {
1921 // The whole point of 0.10.0. Anything emitting a hover rule owes the
1922 // other three, or the consuming app supplies them by out-specifying a
1923 // rule it does not own: 19 such rules in goingson, 21 in the MNW
1924 // server, and three focus rings that do not match.
1925 let css = stylesheet(&Emit::default());
1926 for selector in ["button", "card", "chip", "tab", "segment", "toggle"] {
1927 assert!(css.contains(&format!(".{selector}:hover {{")), "{selector}");
1928 assert!(
1929 css.contains(&format!(".{selector}:active {{")),
1930 "{selector}"
1931 );
1932 assert!(
1933 css.contains(&format!(".{selector}:focus-visible {{")),
1934 "{selector} has no focus ring"
1935 );
1936 assert!(
1937 css.contains(&format!(".{selector}:disabled,")),
1938 "{selector} has no disabled state"
1939 );
1940 }
1941 }
1942
1943 #[test]
1944 fn a_field_takes_focus_and_refuses_input_without_taking_a_hover() {
1945 // A text field does not light up under the pointer, so it gets the two
1946 // states it has and not the two it does not.
1947 let css = stylesheet(&Emit::default());
1948 assert!(css.contains(".field:focus-visible {"));
1949 assert!(css.contains(".field:disabled,"));
1950 assert!(!css.contains(".field:hover {"));
1951 assert!(!css.contains(".field:active {"));
1952 }
1953
1954 #[test]
1955 fn disabled_is_emitted_after_hover_so_source_order_settles_it() {
1956 // Every one of these selectors is specificity (0,2,0), so nothing but
1957 // order decides which wins. A disabled button taking the hover fill is
1958 // the exact bug goingson's `.button:disabled:hover` was written to fix,
1959 // and the reason it had to reach (0,3,0) to do it.
1960 let css = interactive_rules("button", Depth::Raised, &Emit::default());
1961 let hover = css.find(":hover").expect("hover");
1962 let active = css.find(":active").expect("active");
1963 let focus = css.find(":focus-visible").expect("focus");
1964 let disabled = css.find(":disabled").expect("disabled");
1965 assert!(hover < active && active < focus && focus < disabled);
1966
1967 // And it restores the surface, or the hover fill survives underneath.
1968 let tail = &css[disabled..];
1969 assert!(tail.contains("background: var(--surface-raised)"));
1970 }
1971
1972 #[test]
1973 fn a_disabled_state_reaches_things_that_cannot_be_disabled() {
1974 // `:disabled` matches form elements only, and a chip is a div. Keying
1975 // on the ARIA attribute too is the pattern the invalid field already
1976 // set: one fact, read by the styling and the accessibility tree alike.
1977 let css = disabled_rule("chip", Depth::Raised);
1978 assert!(css.contains(".chip:disabled,"));
1979 assert!(css.contains(".chip[aria-disabled=\"true\"]"));
1980 assert!(css.contains("cursor: not-allowed"));
1981 }
1982
1983 #[test]
1984 fn the_focus_ring_does_not_disturb_the_bevel_it_lands_on() {
1985 // `outline` has its own property, so unlike the invalid ring there is
1986 // no bevel to restate beside it and nothing to keep in agreement.
1987 let opts = Emit::default();
1988 let css = focus_rule("button", Depth::Raised, &opts);
1989 assert!(css.contains("outline: 2px solid var(--focus-ring)"));
1990 assert!(!css.contains("box-shadow"), "the ring restated the bevel");
1991 }
1992
1993 #[test]
1994 fn a_well_takes_the_ring_inside_and_a_raised_surface_outside() {
1995 // One ring, placed by depth. The offset comes off `Depth::bevel` and
1996 // not off a per-component choice, which is what gave three apps three
1997 // different rings.
1998 let opts = Emit::default();
1999 assert!(focus_rule("field", Depth::Well, &opts).contains("outline-offset: calc(-1 * 2px)"));
2000 assert!(focus_rule("button", Depth::Raised, &opts).contains("outline-offset: 2px"));
2001 // Nothing to sit inside of, so it sits outside.
2002 assert!(focus_rule("badge", Depth::Sunken, &opts).contains("outline-offset: 2px"));
2003
2004 // And the ring is not the bevel. Reusing border_width emitted a 1px
2005 // ring that every consumer had already overridden.
2006 assert_ne!(opts.focus_width, opts.border_width);
2007 }
2008
2009 #[test]
2010 fn hover_is_gated_on_capability_and_the_keyboard_path_is_not() {
2011 // goingson's section 60 exists only to take back the hover state this
2012 // crate handed it. Gating at the source is what deletes that section
2013 // in all three apps rather than having each fight for it.
2014 let css = stylesheet(&Emit::default());
2015 let condition = format!("@media {}", Density::Pointer.media_condition());
2016 assert!(css.contains(&condition));
2017
2018 // What is gated is every hover state the surfaces carry. The row's
2019 // actions used to be the other half of this test and are not gated any
2020 // more, because they are not hidden any more: a rule that reveals
2021 // nothing needs no capability answer.
2022 let gated: Vec<&str> = css.lines().filter(|line| line.contains(":hover")).collect();
2023 assert!(!gated.is_empty(), "{css}");
2024 for line in gated {
2025 let indent = line.len() - line.trim_start().len();
2026 assert!(indent > 4, "an ungated hover rule: {line}");
2027 }
2028 assert!(!css.contains(".row:hover"), "{css}");
2029 }
2030
2031 #[test]
2032 fn the_capability_answer_is_asked_for_and_not_assumed() {
2033 // Both halves come from the crates that own them. If `makeover-touch`
2034 // ever says a fingertip has hover, this stops gating on its own.
2035 assert!(!Affordance::Hover.available(Density::Touch, SizeClass::Compact));
2036 assert!(Affordance::Hover.available(Density::Pointer, SizeClass::Compact));
2037 assert_eq!(hover_condition(), Some(Density::Pointer.media_condition()));
2038
2039 // And the size class passed to that call is not a claim about width.
2040 assert!(Affordance::Hover.reads_density());
2041 for size in [SizeClass::Compact, SizeClass::Medium, SizeClass::Expanded] {
2042 assert!(!Affordance::Hover.available(Density::Touch, size));
2043 }
2044 }
2045
2046 #[test]
2047 fn hover_resolves_against_the_token_makeover_already_derives() {
2048 let css = interactive_rules("card", Depth::Raised, &Emit::default());
2049 assert!(css.contains(".card:hover {"));
2050 assert!(css.contains("background: var(--hover-surface)"));
2051 // Not the app's choice, which was --surface-overlay.
2052 assert!(!css.contains("surface-overlay"));
2053 }
2054
2055 #[test]
2056 fn a_badge_gets_no_edge_and_no_fill() {
2057 // Decision 2, and the one visible redesign in phase A. Token::Badge is
2058 // Flat: an edge on a label says it can be pressed.
2059 let css = token_rules(&Emit::default());
2060 let badge = css
2061 .lines()
2062 .skip_while(|l| !l.starts_with(".badge {"))
2063 .take_while(|l| !l.starts_with('}'))
2064 .collect::<Vec<_>>()
2065 .join("\n");
2066 assert!(!badge.contains("box-shadow"), "badge kept an edge: {badge}");
2067 assert!(!badge.contains("background"), "badge kept a fill: {badge}");
2068 assert_eq!(Token::Badge.depth(false), Depth::Flat);
2069 assert_eq!(Token::Badge.depth(true), Depth::Flat);
2070 }
2071
2072 #[test]
2073 fn a_badge_carries_a_tone_and_neutral_is_the_bare_class() {
2074 let css = token_rules(&Emit::default());
2075 // Neutral is the absence of a status, not a status named "none".
2076 assert!(css.contains(".badge {\n color: var(--content-muted);"));
2077 assert!(!css.contains("data-tone=\"content-muted\""));
2078 for tone in ["info", "success", "warning", "danger"] {
2079 assert!(
2080 css.contains(&format!(".badge[data-tone=\"{tone}\"]")),
2081 "missing tone {tone}"
2082 );
2083 assert!(css.contains(&format!("color: var(--{tone})")));
2084 }
2085 }
2086
2087 #[test]
2088 fn a_chip_is_raised_and_latches_into_a_well() {
2089 let css = token_rules(&Emit::default());
2090 assert!(css.contains(".chip {"));
2091 assert!(css.contains(".chip.latched {"));
2092 assert!(css.contains(".chip:active {"));
2093 // The whole difference from a badge: it answers a click.
2094 assert!(Token::Chip { removable: false }.interactive());
2095 assert!(!Token::Badge.interactive());
2096 }
2097
2098 #[test]
2099 fn only_a_tab_comes_forward_when_chosen() {
2100 // The folder semantic. Collapsing the three selectors would lose it.
2101 let css = selector_rules(&Emit::default());
2102 assert!(css.contains(".tab.chosen {"));
2103 assert!(css.contains(".segment.chosen {"));
2104 assert!(css.contains(".toggle.chosen {"));
2105 assert_eq!(Selector::Tabs.chosen(), Depth::Raised);
2106 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2107 assert_eq!(Selector::Toggle.chosen(), Depth::Well);
2108
2109 let tab = css
2110 .lines()
2111 .skip_while(|l| !l.starts_with(".tab.chosen {"))
2112 .take_while(|l| !l.starts_with('}'))
2113 .collect::<Vec<_>>()
2114 .join("\n");
2115 assert!(
2116 tab.contains("var(--bevel-raised)"),
2117 "tab was held in: {tab}"
2118 );
2119 }
2120
2121 #[test]
2122 fn an_unchosen_tab_recedes_without_looking_picked() {
2123 let css = selector_rules(&Emit::default());
2124 // Recessed by colour and given no edge. An edge would make every option
2125 // look picked; flat would leave the chosen one nothing to come forward
2126 // from, which is the gap makeover-layout 0.3.0 closed.
2127 assert!(
2128 css.contains(".tab {\n background: var(--surface-sunken);\n}"),
2129 "unchosen tab is not recessed: {css}"
2130 );
2131 assert_eq!(Selector::Tabs.unchosen(), Depth::Sunken);
2132 assert!(css.contains(".tab:hover {"));
2133 }
2134
2135 #[test]
2136 fn a_segment_stands_up_so_the_chosen_one_can_be_held_in() {
2137 // The inverse of the tab, and why the three selectors are not one
2138 // member with a flag.
2139 let css = selector_rules(&Emit::default());
2140 assert!(css.contains(".segment {\n background: var(--surface-raised);"));
2141 assert_eq!(Selector::Segmented.unchosen(), Depth::Raised);
2142 assert_eq!(Selector::Segmented.chosen(), Depth::Well);
2143 }
2144
2145 #[test]
2146 fn a_rows_actions_are_shown_at_rest() {
2147 let css = row_rules(&Emit::default());
2148
2149 // The hover reveal is gone, and with it every escape it needed. What
2150 // it hid was hidden from pointer users alone, who are the ones
2151 // scanning a list to learn what can be done to a row.
2152 assert!(!css.contains("opacity"), "{css}");
2153 assert!(!css.contains("pointer-events"), "{css}");
2154 assert!(!css.contains(":hover"), "{css}");
2155 assert!(!css.contains(":focus-within"), "{css}");
2156
2157 // Nor is it hidden any other way. `display: none` would reflow the row
2158 // and `visibility: hidden` would take the actions out of the focus
2159 // order; the point is that neither is reached for.
2160 assert!(!css.contains("display: none"), "{css}");
2161 assert!(!css.contains("visibility:"), "{css}");
2162 }
2163
2164 #[test]
2165 fn a_figures_tone_lands_on_the_delta_when_there_is_one() {
2166 // 0.13.0. The delta is the part that reads as good or bad; the number
2167 // itself is an ordinary fact. A figure with no delta has nowhere else to
2168 // put the colour, so the value takes it, and `:has` is what lets one
2169 // attribute mean both without the emitter choosing an element.
2170 let css = stylesheet(&Emit::default());
2171
2172 assert!(
2173 css.contains(".figure[data-tone=\"success\"] > .figure-change"),
2174 "{css}"
2175 );
2176 assert!(
2177 css.contains(
2178 ".figure[data-tone=\"success\"]:not(:has(> .figure-change)) > .figure-value"
2179 ),
2180 "{css}"
2181 );
2182 // The caption is the noun and never takes the tone.
2183 assert!(
2184 !css.contains("[data-tone=\"success\"] > .figure-caption"),
2185 "{css}"
2186 );
2187 }
2188
2189 #[test]
2190 fn the_three_text_parts_take_their_intents_and_actions_inherits() {
2191 let css = row_rules(&Emit::default());
2192 assert!(css.contains(".row-primary {\n color: var(--content);"));
2193 assert!(css.contains(".row-secondary {\n color: var(--content-secondary);"));
2194 assert!(css.contains(".row-meta {\n color: var(--content-muted);"));
2195 // Actions carry controls, not text. Pinning the colour it would inherit
2196 // anyway is louder than saying nothing.
2197 assert!(!css.contains(".row-actions {\n color:"));
2198 }
2199
2200 #[test]
2201 fn the_token_strip_takes_no_colour_of_its_own() {
2202 // makeover-layout 0.9.0. A token carries its own tone, so a colour on
2203 // the strip would be a rule fighting the things sitting in it -- the
2204 // same reasoning as actions, reached for a different reason.
2205 let css = row_rules(&Emit::default());
2206 assert!(!css.contains(".row-tokens {\n color:"));
2207 }
2208
2209 #[test]
2210 fn an_unknown_row_part_renders_plainly_rather_than_failing_to_build() {
2211 // What `#[non_exhaustive]` bought and what it cost. `part_class` can no
2212 // longer be exhaustive, so a member added upstream lands as a bare
2213 // class with no rule instead of stopping the build. Asserting the
2214 // fallback exists is what keeps it from being written as `unreachable!`
2215 // by someone who reads the match as closed.
2216 assert_eq!(part_class(RowPart::Tokens), "row-tokens");
2217 assert_eq!(part_class(RowPart::Meta), "row-meta");
2218 }
2219
2220 #[test]
2221 fn a_link_takes_the_action_colour_the_theme_actually_defines() {
2222 // `--action-primary` shipped here for months and no theme has ever
2223 // defined it, so every `.link` dropped its colour declaration outright
2224 // and fell back to inherited text. Nothing caught it because the sheet
2225 // is valid CSS either way; MNW's no-undefined-token lint is what found
2226 // it, 2026-08-14. The hover arm two lines below was always `--action-hover`,
2227 // which is what makes the typo legible in hindsight.
2228 let css = link_rules(&Emit::default());
2229 assert!(css.contains("color: var(--action);"));
2230 assert!(!css.contains("--action-primary"));
2231 assert!(css.contains("color: var(--action-hover);"));
2232 }
2233
2234 #[test]
2235 fn the_progress_trough_is_a_well() {
2236 let css = progress_rules(&Emit::default());
2237 assert!(css.contains(".progress {"));
2238 assert!(css.contains("box-shadow: var(--bevel-inset)"));
2239 assert!(css.contains(".progress > .progress-fill {"));
2240 assert!(css.contains("background: var(--action)"));
2241 // A bare `.fill` would catch things that have nothing to do with
2242 // progress once the sheet lands unprefixed.
2243 assert!(!css.contains("> .fill "));
2244 }
2245
2246 #[test]
2247 fn a_progress_bar_can_carry_a_tone_and_defaults_to_action() {
2248 let css = progress_rules(&Emit::default());
2249 // Untoned is --action, not Tone::Neutral's content-muted: a bar with no
2250 // status is still reporting progress, and muted would read as disabled.
2251 assert!(css.contains(".progress > .progress-fill {\n background: var(--action);"));
2252 assert!(!css.contains("progress-fill {\n color: var(--content-muted)"));
2253 for tone in ["info", "success", "warning", "danger"] {
2254 assert!(
2255 css.contains(&format!(".progress > .progress-fill[data-tone=\"{tone}\"]")),
2256 "missing progress tone {tone}"
2257 );
2258 }
2259 // goingson's two live cases, which is why the tones are emitted at all.
2260 assert!(css.contains("[data-tone=\"success\"] {\n background: var(--success);"));
2261 assert!(css.contains("[data-tone=\"danger\"] {\n background: var(--danger);"));
2262 }
2263
2264 #[test]
2265 fn no_scrollbar_track_is_emitted() {
2266 // Decision 3's negative half. It was on the phase A list and came off;
2267 // this is what stops it drifting back in.
2268 let css = stylesheet(&Emit::default());
2269 assert!(!css.contains("scrollbar"));
2270 assert!(!css.contains("::-webkit"));
2271 }
2272
2273 #[test]
2274 fn an_invalid_field_is_ringed_without_being_lit() {
2275 let css = surface_rules(&Emit::default());
2276 assert!(css.contains(".field {"));
2277 // The ARIA attribute, not a class: one fact, read by both the visual
2278 // and the accessible state, so they cannot drift.
2279 assert!(css.contains(".field[aria-invalid=\"true\"] {"));
2280 assert!(!css.contains(".field.invalid"));
2281 // A flat ring: this edge says "wrong", and a two-tone bevel would have
2282 // it say "raised" at the same time.
2283 assert!(css.contains("0 0 0 1px var(--danger)"));
2284 }
2285
2286 #[test]
2287 fn an_invalid_field_keeps_the_well_underneath_it() {
2288 // box-shadow is not additive. A lone ring replaces the bevel and drops
2289 // the well out from under the field, which is what this emitted before
2290 // 0.5.0 and is the whole reason the rule composes.
2291 let css = surface_rules(&Emit::default());
2292 let invalid = css
2293 .lines()
2294 .skip_while(|l| !l.starts_with(".field[aria-invalid"))
2295 .take_while(|l| !l.starts_with('}'))
2296 .collect::<Vec<_>>()
2297 .join("\n");
2298 assert!(
2299 invalid.contains("var(--bevel-inset)"),
2300 "the well was dropped: {invalid}"
2301 );
2302 assert!(invalid.contains("var(--danger)"));
2303 }
2304
2305 #[test]
2306 fn button_and_card_come_out_identical_by_construction() {
2307 // The duplication phase A deletes. They are the same composition, so
2308 // the only honest way to emit both is from one call.
2309 let opts = Emit::default();
2310 let css = surface_rules(&opts);
2311 assert_eq!(
2312 depth_declarations(Depth::Raised),
2313 depth_declarations(Depth::Raised)
2314 );
2315 assert!(css.contains(".button {"));
2316 assert!(css.contains(".card {"));
2317 assert_eq!(
2318 interactive_rules("button", Depth::Raised, &Emit::default()).replace("button", "card"),
2319 interactive_rules("card", Depth::Raised, &Emit::default())
2320 );
2321 }
2322
2323 #[test]
2324 fn a_prefix_reaches_the_component_classes_too() {
2325 let opts = Emit {
2326 class_prefix: "mo-",
2327 ..Emit::default()
2328 };
2329 let css = stylesheet(&opts);
2330 for name in [
2331 "mo-button",
2332 "mo-card",
2333 "mo-field",
2334 "mo-badge",
2335 "mo-chip",
2336 "mo-tab",
2337 "mo-row-primary",
2338 "mo-progress",
2339 "mo-progress-fill",
2340 ] {
2341 assert!(css.contains(&format!(".{name}")), "unprefixed: {name}");
2342 }
2343 // The bare names must be gone entirely, or a prefixed build still
2344 // collides with the app's own stylesheet.
2345 assert!(!css.contains(".button {"));
2346 assert!(!css.contains(".card {"));
2347 assert!(!css.contains(".badge {"));
2348 }
2349
2350 #[test]
2351 fn the_class_a_renderer_puts_on_an_option_is_the_one_the_rules_key_off() {
2352 // `option_class` is the contract a screen renderer writes markup
2353 // against, and the rules below are the other half of it. They come off
2354 // one mapping now, so this asserts the mapping is the one that reaches
2355 // the stylesheet rather than that two lists still agree.
2356 let css = stylesheet(&Emit::default());
2357 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
2358 let name = option_class(selector);
2359 assert!(css.contains(&format!(".{name} {{")), "{name}: {css}");
2360 assert!(css.contains(&format!(".{name}.chosen {{")), "{name}: {css}");
2361 }
2362 assert_eq!(option_class(Selector::Tabs), "tab");
2363 }
2364
2365 #[test]
2366 fn the_caret_brings_its_own_gap_and_is_the_glyph_the_description_names() {
2367 let css = stylesheet(&Emit::default());
2368
2369 // The space is inside the glyph, which is what the other two renderers
2370 // write. Emitted bare, every consumer has to add it back, and the
2371 // obvious way to add it -- `content` in an app stylesheet, which is
2372 // unlayered and so outranks this sheet -- deletes the caret instead.
2373 assert!(css.contains("content: \" \\25B2\";"), "{css}");
2374 assert!(css.contains("content: \" \\25BC\";"), "{css}");
2375 assert!(!css.contains("content: \"\\2"), "{css}");
2376
2377 // The arrows this renderer used to draw alone are gone. Composition
2378 // rather than agreement: the glyph comes from `Sort::glyph`, so a
2379 // fourth spelling cannot appear here without appearing everywhere.
2380 assert!(!css.contains("2191") && !css.contains("2193"), "{css}");
2381 assert!(css.contains(&css_escape(Sort::Ascending.glyph())), "{css}");
2382
2383 // Three states, three tones. An idle sortable heading draws its caret
2384 // now rather than reserving a hidden box for it, so there is no
2385 // visibility to order and no reflow left to guard against; what
2386 // separates the states is the colour, and the sorted arms come after
2387 // the idle one because the specificity is the same.
2388 let idle = css
2389 .find(".table-heading[data-sortable]::after")
2390 .expect("the idle caret is emitted");
2391 let sorted = css
2392 .find(".table-heading[aria-sort=\"ascending\"]::after")
2393 .expect("the ascending caret is emitted");
2394 assert!(idle < sorted, "{css}");
2395 assert!(
2396 css[idle..sorted].contains("color: var(--content-secondary);"),
2397 "{css}"
2398 );
2399 assert!(css[sorted..].contains("color: var(--content);"), "{css}");
2400 assert!(!css.contains("visibility: hidden;"), "{css}");
2401 }
2402
2403 #[test]
2404 fn a_destructive_button_has_somewhere_for_its_tone_to_land() {
2405 let css = component_rules(&Emit::default());
2406
2407 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
2408 assert!(
2409 css.contains(&format!(".button[data-tone=\"{}\"]", tone.token())),
2410 "{css}"
2411 );
2412 }
2413 // Colour, not a fill. A red surface is an app's decision about emphasis.
2414 assert!(!css.contains(".button[data-tone=\"danger\"] {\n background"));
2415 }
2416
2417 #[test]
2418 fn a_described_list_is_not_a_bulleted_list() {
2419 let css = component_rules(&Emit::default());
2420 assert!(css.contains(".list {\n list-style: none;"), "{css}");
2421 }
2422
2423 #[test]
2424 fn a_table_lays_itself_out_without_being_told_its_columns() {
2425 // The whole point of the CSS table. A described table's columns are
2426 // known at render time, so anything the stylesheet has to be told about
2427 // them would have to travel with the markup.
2428 let css = component_rules(&Emit::default());
2429
2430 assert!(css.contains(".table {\n display: table;"), "{css}");
2431 assert!(css.contains("display: table-row;"), "{css}");
2432 assert!(css.contains("display: table-cell;"), "{css}");
2433 assert!(!css.contains("grid-template-columns"), "{css}");
2434 }
2435
2436 #[test]
2437 fn a_control_in_a_cell_is_not_painted_as_text() {
2438 // The point of makeover-layout 0.14.0's CellPart, and the table-side
2439 // twin of `the_three_text_parts_take_their_intents_and_actions_inherits`
2440 // above. One `.cell` and one content colour meant a button in a cell
2441 // inherited it.
2442 let css = table_rules(&Emit::default());
2443
2444 assert!(
2445 css.contains(".cell-value {\n color: var(--content);"),
2446 "{css}"
2447 );
2448 assert!(!css.contains(".cell-actions {\n color:"), "{css}");
2449 assert!(!css.contains(".cell-tokens {\n color:"), "{css}");
2450 assert!(!css.contains(".cell-link {\n color:"), "{css}");
2451
2452 // The colour is on the part that is text, never on the container. On
2453 // `.cell` it would cascade into the three parts that are not text,
2454 // which is the bug written as one rule.
2455 assert!(!css.contains(".cell {\n color:"), "{css}");
2456 }
2457
2458 #[test]
2459 fn an_unknown_cell_part_renders_plainly_rather_than_failing_to_build() {
2460 // `part_class`'s obligation, taken on for the table side too. CellPart
2461 // is `#[non_exhaustive]`, so a member added upstream must land as a
2462 // bare class rather than as a build that stops.
2463 assert_eq!(cell_part_class(CellPart::Value), "cell-value");
2464 assert_eq!(cell_part_class(CellPart::Actions), "cell-actions");
2465 }
2466
2467 #[test]
2468 fn a_column_drops_by_its_priority_and_never_by_its_position() {
2469 let css = component_rules(&Emit::default());
2470
2471 // Optional goes at the narrowest class and secondary goes with it,
2472 // which is `kept_at`'s cutoff walk said as two queries.
2473 let compact = css
2474 .find(&format!("@media {}", SizeClass::Compact.media_condition()))
2475 .expect("a compact query");
2476 let medium = css
2477 .find(&format!("@media {}", SizeClass::Medium.media_condition()))
2478 .expect("a medium query");
2479 assert!(css[compact..].contains(".cell-drops-next"), "{css}");
2480 assert!(!css[medium..].contains(".cell-drops-next"), "{css}");
2481
2482 // Essential columns are never mentioned, because not being mentioned is
2483 // already what never dropping means.
2484 assert!(!css.contains(".cell-keeps"), "{css}");
2485
2486 // And nothing counts. `nth-child` is the bug the priority vocabulary
2487 // exists to end.
2488 assert!(!css.contains("nth-child"), "{css}");
2489 }
2490
2491 #[test]
2492 fn a_track_places_by_custom_property_and_never_by_a_size() {
2493 let css = track_rules(&Emit::default());
2494
2495 // Placement arrives from the caller, computed once by Track::fraction.
2496 // If either of these becomes a literal, three renderers have started
2497 // disagreeing about where 09:30 is.
2498 assert!(css.contains("top: var(--track-at"), "{css}");
2499 assert!(css.contains("height: var(--track-for"), "{css}");
2500
2501 // Overlap lanes default so an entry naming neither is full width.
2502 assert!(css.contains("--track-lane, 0"), "{css}");
2503 assert!(css.contains("--track-lanes, 1"), "{css}");
2504
2505 // The refusal that matters. A slot height here would be this crate
2506 // deciding how tall a quarter of an hour is, which is the thing
2507 // makeover-geometry owns and the reason `.track` gets no height at all.
2508 assert!(!css.contains("height: var(--track-slot"), "{css}");
2509 for size in ["px", "rem", "em", "vh"] {
2510 let bare = css
2511 .lines()
2512 .filter(|l| !l.contains("var(--"))
2513 .any(|l| l.contains(size));
2514 assert!(!bare, "track_rules named a {size} outside a var(): {css}");
2515 }
2516 }
2517
2518 #[test]
2519 fn a_relaxed_part_clamps_and_a_tight_one_says_nothing() {
2520 let css = stylesheet(&Emit::default());
2521 assert!(css.contains(".row-relaxed {"));
2522 assert!(css.contains("-webkit-line-clamp: 2;"));
2523 // The count is `Flow`'s, not this crate's. If the tier ever means three
2524 // lines, this fails here rather than in an app.
2525 assert!(css.contains(&format!("line-clamp: {};", Flow::Relaxed.lines())));
2526 // Tight gets no rule at all: one line is what a run already does, and a
2527 // class per part saying so is a declaration that changes nothing.
2528 assert!(!css.contains("row-tight"));
2529 assert_eq!(crate::list::flow_class(Flow::Relaxed), Some("row-relaxed"));
2530 assert_eq!(crate::list::flow_class(Flow::Tight), None);
2531 // Emitted, therefore checkable: an app's dead-vocabulary seal and the
2532 // overlap check both read `vocabulary::names`, so a class the renderer
2533 // can write and that list does not carry is invisible to both.
2534 assert!(crate::vocabulary::names(&Emit::default()).contains("row-relaxed"));
2535 }
2536
2537 #[test]
2538 fn the_whole_sheet_still_names_every_colour() {
2539 // The crate's founding property, asserted over the component layer and
2540 // not only the primitives.
2541 let css = stylesheet(&Emit::default());
2542 assert!(!css.contains('#'));
2543 assert!(!css.contains("rgb"));
2544 for line in css.lines() {
2545 // Declarations only: a selector or an at-rule can carry a colon of
2546 // its own (`:root`, `:hover`, `@media (hover: hover)`) and declares
2547 // nothing. Keyed on the trailing semicolon rather than on leading
2548 // indentation, which only ever worked as a proxy for nesting depth
2549 // and stopped when the sheet gained a cascade layer around it.
2550 let trimmed = line.trim();
2551 if !trimmed.ends_with(';') {
2552 continue;
2553 }
2554 let Some((_, value)) = trimmed.split_once(": ") else {
2555 continue;
2556 };
2557 if value.contains("var(--") {
2558 continue;
2559 }
2560 // Everything left has to be a keyword, a number or a
2561 // caller-supplied length, never a colour.
2562 //
2563 // The length arm is what the comment above always claimed and the
2564 // list never covered: `border_width` arrives from `Emit` and lands
2565 // bare in the focus ring's offset, where the bevel had only ever
2566 // used it inside an `inset` shadow.
2567 let opts = Emit::default();
2568 assert!(
2569 value.contains("inset")
2570 || value.contains(opts.border_width)
2571 || value.contains(opts.focus_width)
2572 // 0.12.0's two: a sortable header is a control and says so
2573 // with the pointer, and the caret is this renderer's own
2574 // expression of `aria-sort`. Neither is a colour, which is
2575 // what this test is actually about, and neither is a size,
2576 // which is the other thing this crate must not name. The
2577 // leading space inside the glyph is the same thing the other
2578 // two renderers write into theirs, so it is part of the
2579 // caret rather than spacing this crate decided on.
2580 || value
2581 .trim_start_matches('"')
2582 .trim_start()
2583 .starts_with("\\2")
2584 || matches!(
2585 value.trim_end_matches(';'),
2586 "0" | "1"
2587 | "none"
2588 | "auto"
2589 | "not-allowed"
2590 | "pointer"
2591 // The caret's reserved box. Visibility is presence,
2592 // not magnitude and not colour.
2593 | "hidden"
2594 | "visible"
2595 // The link's two signals. `underline` is a line and
2596 // `inherit` defers to whatever the app set, so
2597 // neither names a colour or a magnitude.
2598 | "underline"
2599 | "inherit"
2600 // The table frame. `display` is structure and not a
2601 // size; `nowrap` is what makes a content column
2602 // content. The two widths are the awkward pair and
2603 // they are still not sizes: `100%` is "all of
2604 // whatever you were given" and `1%` is the CSS
2605 // table idiom for "shrink to fit", which is a
2606 // behaviour spelled as a number because CSS has no
2607 // keyword for it. Neither names a magnitude, which
2608 // is the thing this crate leaves to
2609 // makeover-geometry.
2610 | "table"
2611 | "table-row"
2612 | "table-cell"
2613 | "nowrap"
2614 | "100%"
2615 | "1%"
2616 // The time axis, 0.42.0. `position` is the one
2617 // property whose whole job is where a thing sits,
2618 // which is exactly what this crate spent its life
2619 // refusing to say -- so it is worth being exact
2620 // about why these two are not that refusal
2621 // breaking.
2622 //
2623 // Neither names a magnitude. `relative` says the
2624 // track is what its entries resolve against, and
2625 // `absolute` says an entry is placed rather than
2626 // flowed. *Where* each entry lands is
2627 // `--track-at` and `--track-for`, custom
2628 // properties the caller sets from
2629 // `Track::fraction`, and they are skipped by the
2630 // `var(--` arm above like every other value this
2631 // crate refuses to decide.
2632 //
2633 // The rule that would break the refusal is a slot
2634 // height, and there is none: the track's height is
2635 // the app's, so the percentages have something to
2636 // resolve against and this crate still never says
2637 // how tall a day is.
2638 | "relative"
2639 | "absolute"
2640 // A run's five, 0.49.0. `flex`, `wrap` and
2641 // `center` are structure and alignment, the same
2642 // reading `table` gets: which way members are laid
2643 // out and how they line up, never how much of
2644 // anything.
2645 //
2646 // The two intrinsic keywords are the interesting
2647 // pair and they are the opposite of a size. A
2648 // magnitude is a number somebody chose;
2649 // `min-content` and `max-content` are the browser
2650 // being asked what the members themselves come to,
2651 // which is the derived minimum the room ruling
2652 // requires and the reason no breakpoint appears
2653 // anywhere in these rules. `1 1 max-content` is
2654 // grow, shrink and that basis, so its two digits
2655 // are ratios rather than lengths.
2656 | "flex"
2657 | "wrap"
2658 | "center"
2659 | "min-content"
2660 | "1 1 max-content"
2661 // A picture's three, 0.36.0. `block` is structure
2662 // for the reason `table` is: an inline image sits
2663 // on the baseline and carries a descender's worth
2664 // of space under it, which is a fact about
2665 // replaced elements rather than a size this crate
2666 // chose. `cover` and `contain` are `Fit`'s two
2667 // named members reaching CSS unchanged, which is
2668 // an intent arriving rather than a value being
2669 // picked.
2670 | "block"
2671 | "cover"
2672 | "contain"
2673 // A relaxed part's three, and the third is the
2674 // awkward one. `-webkit-box` and `vertical` are
2675 // structure: they say the part is a box of lines
2676 // stacked downward, which is the only way CSS lets
2677 // anyone ask for a clamp at all.
2678 //
2679 // `2` is a count of lines, not a length. The
2680 // distinction this crate holds is between naming a
2681 // magnitude -- a padding, a height, a font size,
2682 // all of which belong to makeover-geometry -- and
2683 // naming how many of something there are. A line's
2684 // height is still the app's, so two lines is
2685 // whatever two of the app's lines come to, and
2686 // nothing here decides how tall that is. It is also
2687 // not a value picked here: it is `Flow::Relaxed`'s
2688 // own answer arriving unchanged, the same way
2689 // `cover` and `contain` are `Fit`'s.
2690 | "-webkit-box"
2691 | "vertical"
2692 | "2"
2693 ),
2694 "unrecognised literal value: {line}"
2695 );
2696 }
2697 }
2698
2699 #[test]
2700 fn flat_emits_nothing_at_all() {
2701 assert_eq!(depth_class(Depth::Flat, &Emit::default()), None);
2702 assert!(!depth_rules(&Emit::default()).contains("flat"));
2703 }
2704
2705 #[test]
2706 fn a_prefix_namespaces_every_class() {
2707 let opts = Emit {
2708 class_prefix: "mo-",
2709 ..Emit::default()
2710 };
2711 let css = depth_rules(&opts);
2712 assert!(css.contains(".mo-raised {"));
2713 assert!(css.contains(".mo-well {"));
2714 assert!(!css.contains(".raised {"));
2715 }
2716
2717 #[test]
2718 fn the_border_width_is_the_callers() {
2719 let opts = Emit {
2720 border_width: "2px",
2721 ..Emit::default()
2722 };
2723 assert!(bevel_shadow(Bevel::Raised, &opts).contains("inset 2px 2px 0"));
2724 }
2725
2726 #[test]
2727 fn edges_agree_with_the_description() {
2728 // Not a tautology: it is the guard that a CSS-shaped convenience never
2729 // quietly reverses which side is lit.
2730 let (tl, br) = Bevel::Raised.edges();
2731 assert_eq!(tl.token(), Edge::Light.token());
2732 assert_eq!(br.token(), Edge::Dark.token());
2733 }
2734}