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//! Some of what phase A emits is not a look but the withdrawal of one. A
36//! renderer that picks its element from the description inherits that element's
37//! user-agent chrome, and [`reset`] is where a primitive says which parts of it
38//! were never asked for.
39//!
40//! # Phase B: the markup, one description at a time
41//!
42//! [`form`] renders [`makeover_layout::Field`], which is the half of phase B
43//! whose description is settled. It emits strings, because both apps
44//! interpolate their fields into larger string-built forms and returning nodes
45//! would rewrite those too. It owns its own escaping, on the reasoning in that
46//! module: a Rust encoder can cover element text and attribute values with one
47//! function, where the apps need four and have to choose correctly at every
48//! call site.
49//!
50//! [`facet`] renders `makeover_layout::Facet`: a dimension a set is narrowed by,
51//! and the one phase-B emitter whose markup an app is not keeping, because the
52//! markup it replaces was two mechanisms rather than one. A tag's selection and
53//! a tag's browse position were separate state on MNW's discover page, which is
54//! why every filter row there carries a tick box *and* a chevron; one gesture
55//! doing both is what lets the second one go.
56//!
57//! [`list`] is the other half: column tracks, the narrowing rules, and the cell
58//! containers a row is made of. It stops at the cell boundary and does not
59//! render what goes inside one, on the reasoning in that module. So phase B is
60//! now the frame around content in both directions, and what an app still owns
61//! is the content itself.
62//!
63//! # What phase A settled, and what it costs
64//!
65//! Measured against goingson's `styles.css` rather than against a component
66//! list: `.btn`, `.card` and `.tag, .badge` each hand-write the same
67//! composition, so three quarters of phase A is one rule with several names.
68//!
69//! Two of the four decisions change how goingson looks, and adoption should
70//! not be described as a pure deletion:
71//!
72//! - **Pressed carries its fill.** [`interactive_rules`] emits
73//! [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
74//! will press to `--surface-well`, and hovers to `--surface-overlay` today
75//! and will hover to `--hover-surface`. Since `surface-well` inverts by theme
76//! where `surface-sunken` does not, a dark theme presses *lighter* than it
77//! hovers. That falls out of `makeover`'s own derivation, which says outright
78//! that `surface-sunken` cannot serve as a well, so if it reads wrong the
79//! answer is there and not here.
80//! - **Badges go flat.** See [`token_rules`].
81//!
82//! The other two: the progress trough is renderer-local and the scrollbar
83//! track was dropped ([`component_rules`]), and no class prefix ships by
84//! default, so adoption means deleting the app's hand-written rule in the same
85//! commit that adds the generated one. `.card`, `.badge` and the tab classes
86//! all already exist in goingson, and while both rules exist the cascade order
87//! decides which wins. That is the one real risk in adopting this, and it is
88//! why the migration lands per component rather than in one commit.
89//!
90//! # Interaction states
91//!
92//! [`interactive_rules`] emits four states, in emission order, and the order is
93//! load-bearing: they are all specificity (0,2,0), so disabled beats hover by
94//! coming last and by nothing else. Nothing here reaches for `:not(:disabled)`,
95//! which would raise a selector this crate wraps in its own layer.
96//!
97//! Emitting the states here is what keeps an app from completing the primitive
98//! from outside, by out-specifying a rule it does not own. Those overrides are
99//! also what breaks under cascade layers: an app that declares `@layer` puts
100//! its own rules in a named layer, and unlayered declarations outrank every
101//! named layer regardless of specificity.
102//!
103//! Hover sits inside a capability query. `makeover-touch` answers whether a
104//! fingertip has hover and `makeover-geometry` spells the condition; this crate
105//! asks and does not decide, so no app has to take the hover state back on
106//! touch.
107//!
108//! # The layer contract
109//!
110//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
111//! lives in `makeover-geometry` because that is the one crate every CSS emitter
112//! in the family already depends on). `makeover-geometry` does the same for
113//! `geometry.css`.
114//!
115//! The cascade resolves origin and importance, then layer, then specificity,
116//! then source order, and **unlayered normal declarations outrank every named
117//! layer**. An unlayered generated file therefore beats every rule an app owns,
118//! regardless of specificity and regardless of loading last. Nothing errors when
119//! that happens: the CSS is valid, the minifier is happy, and buttons and badges
120//! look subtly wrong. The layer belongs here rather than in each app, because an
121//! app cannot fix it from its own stylesheet: the fix is to layer the file it
122//! does not own.
123//!
124//! An app should declare the order once, or the layer's position is decided by
125//! whichever generated file the browser happens to see first:
126//!
127//! ```css
128//! @layer makeover, base, components, responsive;
129//! ```
130//!
131//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
132//! from this crate's pieces: rules an app generates from them are as generated
133//! as the ones here, so they belong in the same layer and this crate cannot put
134//! them there on the app's behalf.
135//!
136//! # Suggestions
137//!
138//! `Outcome::Suggestions` carries `Candidate` rather than `Choice`, and a
139//! candidate has no `unavailable`: a suggestion that cannot be picked is a row
140//! a route should not have offered. What it has instead is a `detail`, the line
141//! that tells it from a row reading the same, and it is drawn in
142//! `--content-muted` rather than in the disabled token. A detail orients rather
143//! than refuses, and every other secondary line in this crate reads the same
144//! way. The class is `.form-suggestion-detail`.
145//!
146//! # An interval is one question with two ends
147//!
148//! [`makeover_layout::FieldKind::Interval`] emits a `role="group"` named by the
149//! field's label, holding one `<input type="number">` per end.
150//!
151//! - **The group carries the error and the descriptions**, on the split
152//! [`makeover_layout::FieldKind::Radio`] already uses here: what is wrong is
153//! the answer, and a crossed interval is not the fault of either end.
154//! - **Both boxes take the whole extent.** `min`, `max` and `step` describe the
155//! axis, so they are written twice. The crossing rule is not emitted, because
156//! HTML has no attribute for it and the description does not carry it: it
157//! comes back as an error on the group, like every other refusal.
158//! - **Which end is which is `aria-label` and nothing more.** The description
159//! states direction structurally, by which member holds which name, and never
160//! in words. Visible Min and Max captions are a page's own and reach the
161//! group through [`form::Filling::trailing`].
162//!
163//! [`form::Value::Between`] is the second value. A separator inside one string
164//! would make this crate the owner of a delimiter that either end could contain.
165//!
166//! # A number's unit is adjacent text
167//!
168//! HTML has no unit attribute and inventing one would be markup nothing reads,
169//! so `Field::unit` is a `<span>` after the control. It is named in
170//! `aria-describedby` rather than left as decoration, because a number and what
171//! it is measured in are one fact and reading the first without the second is
172//! reading it wrong. What that buys is a unit a consumer can read back rather
173//! than a suffix on a label it would have to parse.
174//!
175//! # A curve this renderer can carry, and one it declines
176//!
177//! A range takes its granularity from the curve (`Field::curve.step()`), every
178//! other kind keeps `Field::step`, and `Curve::Linear` emits a plain range.
179//!
180//! **A constant-ratio curve emits a linear track, and that is the answer, not a
181//! debt.** HTML has no logarithmic range input, so a described screen asking
182//! for one is asking the browser for something it does not have, the same class
183//! of request as [`makeover_layout::FieldKind::Date`] on a host with no
184//! calendar. The renderer answers with the nearest control the host really
185//! offers and keeps every fact that survives the translation: the extent, the
186//! granularity, and the value's own units. What does not survive is resolution
187//! at the small end. The value submitted is still a value in the field's own
188//! units, which is what every handler on this path reads.
189//!
190//! The alternatives are worse in the specific way this stack exists to avoid.
191//! Shipping JS that maps thumb position to value puts app code back in the
192//! renderer. Changing what the control submits from a value to a fraction moves
193//! the mapping to whoever reads the form, and a server reading these forms with
194//! its own handlers would take a fraction where a value is expected, silently.
195//!
196//! When this reopens: the day a described screen on the webview path asks for a
197//! non-linear range. The answer then is mapping in `quasi-router`, where one
198//! implementation serves every host, not JS here.
199//!
200//! # A markdown field gets a preview
201//!
202//! A [`makeover_layout::FieldKind::Rich`] field is marked
203//! `data-format="markdown"`, and [`form::editor_rules`] is what spends that
204//! mark. The Write/Preview pair is a segmented control, so it takes the depth,
205//! the focus ring and the chosen state from rules that already exist; the
206//! preview pane is a well, because it stands where the control stood. Both are
207//! gated on the attribute rather than on a class, which is what the attribute is
208//! for. A permission taken and not spent turns every conversion into a
209//! regression.
210//!
211//! **This crate renders no markdown.** The pane arrives empty and is filled by
212//! whatever binds the editor, which is where the host's sanitiser already is. A
213//! converter here would move that guarantee into a crate with no view of the
214//! host's content-security posture.
215//!
216//! # Ranges, ghost text, and an option that cannot be picked
217//!
218//! - `FieldKind::Range` emits `<input type="range">`, and `Field::step` emits
219//! `step`. The step is emitted only when the description carries one: the
220//! browser's own default is `step="1"`, which is what a description means by
221//! saying nothing, and is also what turns a 0-to-1 threshold into a
222//! two-position control.
223//! - A select with nothing chosen emits a disabled, selected, valueless first
224//! option carrying `Field::placeholder`. HTML has no placeholder attribute on
225//! `<select>`; this is the idiom, and `required` keeps working through it
226//! because the option's value is empty.
227//! - `Choice::unavailable` emits `disabled` plus the reason. Where it goes
228//! differs by control and the difference is forced: a radio group gets a
229//! `.form-option-reason` span beside the label, and a `<select>` option has
230//! room for no element at all, so the reason runs into its text.
231//! - `Choice::detail` takes the same split for the same reason: a
232//! `.form-option-detail` span in a radio group, run into the text of a
233//! `<select>`'s option. An option carrying both reads what it is before why it
234//! cannot be picked.
235//!
236//! # A cell says what it holds
237//!
238//! [`CellPart`](makeover_layout::CellPart) names the four things a cell holds,
239//! and [`table_rules`] turns them into `.cell-value`, `.cell-tokens`,
240//! `.cell-actions` and `.cell-link`. The value and the link take a colour: a
241//! token carries its own tone and an action is a control rather than text.
242//!
243//! The colour goes on `.cell-value` rather than on `.cell`. On the container it
244//! cascades into the parts that are not text, and a control in a cell is painted
245//! as text, which is the drift
246//! [`RowPart::intent`](makeover_layout::RowPart) prevents for list rows.
247//!
248//! [`list::Cell::part`] is `Option<CellPart>` and never `Option<RowPart>`: the
249//! two answer different questions, and only one of them is about a cell.
250//!
251//! # A table narrows itself
252//!
253//! A table a description produced knows its columns at render time, so no rule
254//! can be written per table: it would have to travel with the markup, as a
255//! `<style>` element that needs `style-src 'unsafe-inline'` or in a head an htmx
256//! fragment swap does not carry. [`table_rules`] lays every table out as flex
257//! rows instead, each column starting at its declared floor and giving up room
258//! by its [`Priority`](makeover_layout::Priority), so the browser narrows a
259//! table at the width its floors add up to. [`list::column_classes`] is what
260//! puts the column's classes on a cell, and every cell's contents go in
261//! [`list::CELL_IN`]. **A header row emitted by a renderer's own code has to do
262//! both too**, or the header and the body disagree about which column just
263//! closed and how wide the rest are.
264//!
265//! `.button` takes the four tones as colour, off `data-tone`, the way the badge
266//! does, so a destructive button has somewhere for its tone to land. A list is
267//! reset rather than left as a bulleted list.
268//!
269//! `RowPart::revealed_on_hover` is not honoured. Hiding a row's actions until
270//! hover hides them from pointer users alone, who are the ones scanning a list
271//! to learn what can be done to a row, and every escape the rule grows
272//! (`focus-within` for the keyboard, a capability gate for a fingertip) is a
273//! report that hiding was wrong for somebody.
274//!
275//! # The depth classes are not controls
276//!
277//! `.raised` is a statement about shape and carries no interactive set, so the
278//! vocabulary has a raised surface that is merely an object. An app that wants
279//! one does not have to take a control class and cancel the control half.
280//!
281//! `.button` is the same depth *and* a control, and takes its states from
282//! [`surface_rules`], which is where a state belongs: on the thing that claims
283//! to answer a pointer. `.card` is a raised object, and it answers a pointer
284//! only when the element it is written on is a control -- `a`, `button`,
285//! `label`, or anything carrying `data-act` -- so one name serves the card
286//! that is read and the card that is pressed.
287//!
288//! # Substitution, three ways
289//!
290//! A theme with no `surface-well` is answered differently by each renderer,
291//! which is why substitution belongs to a renderer and not to the description:
292//!
293//! - `makeover-immediate` substitutes the page in Rust.
294//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
295//! terminal would quantise the two together.
296//! - here, CSS already has the mechanism: `var(--surface-well,
297//! var(--surface-page))` falls back in the browser, and nothing in Rust
298//! decides anything.
299
300#![forbid(unsafe_code)]
301
302pub mod chart;
303pub mod facet;
304pub mod figure;
305pub mod form;
306pub mod list;
307pub mod meter;
308pub mod placeholder;
309pub mod reset;
310pub mod vocabulary;
311
312/// A render of every emitter, scraped for the classes it wrote.
313///
314/// Test-only, and the guard behind [`vocabulary::names`]. See the module's own
315/// header for why the check renders rather than reads the source.
316#[cfg(test)]
317mod corpus;
318
319use crate::list::{cell_part_class, part_class};
320use crate::reset::{Chrome, Reset};
321use makeover_geometry::{Density, Gap, SizeClass};
322// Re-exported rather than redefined. An app assembling its own stylesheet out
323// of this crate's pieces needs the same layer name, and most such apps depend
324// on this crate and not on `makeover-geometry` directly.
325pub use makeover_geometry::{CSS_LAYER, in_css_layer};
326
327/// This crate's version, as the generated stylesheet reports it.
328///
329/// A consumer whose lockfile still pins an old `makeover-webview` gets a
330/// well-formed sheet with components missing and no error anywhere, so the
331/// emitter has to name itself in what it writes. Read by
332/// `makeover_build::layout_css` through [`stylesheet`].
333pub const VERSION: &str = env!("CARGO_PKG_VERSION");
334use makeover_layout::{
335 Bevel, CellPart, Depth, Fallback, Fill, Flow, Intent, RowPart, Selector, Sort, State, Token,
336 Tone,
337};
338use makeover_touch::Affordance;
339use std::fmt::Write as _;
340
341/// How the emitted CSS is shaped.
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub struct Emit {
344 /// Bevel thickness, as a CSS length.
345 ///
346 /// A value, so it arrives from the caller: border widths belong to
347 /// `makeover-geometry` and will come from there once it carries them.
348 pub border_width: &'static str,
349 /// Focus ring thickness, as a CSS length.
350 ///
351 /// Separate from [`border_width`](Self::border_width), and never derived
352 /// from it: a bevel and a focus indicator answer different questions, and
353 /// only one of them has to be noticed from across a desk.
354 ///
355 /// The default is the measured consensus rather than a new opinion. Every
356 /// consumer had already written its own ring and all three chose at least
357 /// 2px: the MNW server 2px across 10 rules, Balanced Breakfast 2px,
358 /// goingson 2px on three rules and 3px on the one covering twelve
359 /// selectors. The design system was the only thing in the tree saying 1px.
360 pub focus_width: &'static str,
361 /// Prefix for emitted class names, without the leading dot.
362 pub class_prefix: &'static str,
363}
364
365impl Default for Emit {
366 fn default() -> Self {
367 Self {
368 border_width: "1px",
369 focus_width: "2px",
370 class_prefix: "",
371 }
372 }
373}
374
375/// A string as CSS escapes, for a `content` value.
376///
377/// `\u{25B2}` becomes `\25B2`. Emitted escaped rather than literally so the
378/// stylesheet is ASCII whatever the description spells: a `content` string is
379/// read by whatever encoding the consumer serves the file as, and a caret that
380/// depends on that is a caret that works on one machine.
381///
382/// Terminated by the closing quote at every site here. A CSS hex escape takes
383/// up to six digits and ends at the first character that cannot be one, so an
384/// escape followed by more text would need a space that these do not.
385fn css_escape(text: &str) -> String {
386 text.chars().fold(String::new(), |mut out, c| {
387 let _ = write!(out, "\\{:X}", c as u32);
388 out
389 })
390}
391
392/// The CSS custom property holding a bevel's composition.
393#[must_use]
394pub fn bevel_var(bevel: Bevel) -> &'static str {
395 match bevel {
396 Bevel::Raised => "--bevel-raised",
397 Bevel::Inset => "--bevel-inset",
398 }
399}
400
401/// A `var()` reference to a fill intent, with the browser's own fallback where
402/// the intent may be absent.
403///
404/// The fallback is CSS syntax, not a decision made here. That is the whole
405/// difference between this renderer and the other two.
406#[must_use]
407pub fn fill_var(fill: Fill) -> String {
408 match fill {
409 Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
410 other => format!("var(--{})", other.token()),
411 }
412}
413
414/// The two-tone edge as a `box-shadow` value.
415///
416/// Two inset shadows, one per corner pair: the light one offset down and
417/// right so it lands on the top and left edges, the dark one the other way.
418/// The same assignment `makeover-immediate` draws with polylines and
419/// `makeover-tui` draws with box-drawing characters.
420#[must_use]
421pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
422 let (top_left, bottom_right) = bevel.edges();
423 let w = opts.border_width;
424 format!(
425 "inset {w} {w} 0 var(--{}), inset -{w} -{w} 0 var(--{})",
426 top_left.token(),
427 bottom_right.token()
428 )
429}
430
431/// The custom properties both bevels resolve through.
432///
433/// Emitted as properties rather than inlined into every rule because that is
434/// what the apps already do, and because a consumer that wants the edge
435/// without the fill reads the property directly.
436#[must_use]
437pub fn bevel_properties(opts: &Emit) -> String {
438 let mut css = String::new();
439 for bevel in [Bevel::Raised, Bevel::Inset] {
440 let _ = writeln!(
441 css,
442 " {}: {};",
443 bevel_var(bevel),
444 bevel_shadow(bevel, opts)
445 );
446 }
447 css.push_str(ELEVATION_PROPERTY);
448 css
449}
450
451/// The cast shadow of a surface that floats over the page.
452///
453/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
454/// this crate owns the geometry, and neither has to know the other's numbers.
455///
456/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
457/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
458/// that reaches for this on a card or a plate has renamed a literal rather than
459/// replaced it.
460///
461/// Two lengths rather than one, because a single blur reads as a smudge at
462/// plate size and as a halo at menu size. The offset is small and downward: a
463/// Platinum-era menu sits just off the page rather than hovering above it.
464const ELEVATION_PROPERTY: &str =
465 " --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
466
467/// The class name for a depth.
468#[must_use]
469pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
470 let name = match depth {
471 Depth::Flat => return None,
472 Depth::Raised => "raised",
473 Depth::Well => "well",
474 Depth::Sunken => "sunken",
475 // A depth added to the description since this renderer was last
476 // built. No class, on the same footing as Flat: emitting a name
477 // whose rule body we cannot write would put a class in the markup
478 // that the stylesheet never defines.
479 _ => return None,
480 };
481 Some(format!("{}{name}", opts.class_prefix))
482}
483
484/// A prefixed class name.
485///
486/// Public, for the renderers that emit markup this crate does not. A screen
487/// renderer writing `class="row"` has to prefix it the way the stylesheet half
488/// does, or a prefixed app gets rules matching everything except the elements
489/// that renderer wrote, and the failure is invisible: the CSS stays valid and
490/// one element is unstyled. Call this rather than copying it.
491#[must_use]
492pub fn class(name: &str, opts: &Emit) -> String {
493 let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
494 push_class(&mut out, name, opts);
495 out
496}
497
498/// A prefixed class name, written into a buffer the caller already has.
499///
500/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
501/// putting every class on every element through a `format!` allocates even in
502/// the default case, where the prefix is empty and the answer is the argument.
503/// A described table row carries roughly eighty transient allocations that way,
504/// and this and the escaper are most of them.
505///
506/// [`class`] stays for callers holding a name rather than a buffer.
507///
508/// [`escape_into`]: crate::form::escape_into
509pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
510 out.push_str(opts.class_prefix);
511 out.push_str(name);
512}
513
514/// The attribute an element's custom properties ride in, instead of `style`.
515///
516/// A number this crate hands the stylesheet -- a bar's value and its axis, a
517/// facet's depth, a meter's fill -- is a custom property the rules divide or
518/// multiply. It used to be written as `style="--value: 4210"`, and a
519/// `style-src` without `'unsafe-inline'` refuses every style attribute, so a
520/// page under that policy drew every chart flat. The same text in this
521/// attribute is data a policy does not police, and the host's script sets each
522/// property through the CSSOM, which the policy allows: quasi-webview's
523/// `VARS_JS`.
524///
525/// The value is `--name: value` pairs separated by `;`, the declaration syntax
526/// the `style` attribute already had, so the numbers still reach the markup as
527/// themselves. That is the property the residual seam needs: see the
528/// [`chart`](crate::chart) module header.
529///
530/// Only custom properties. A script that applied any declaration from markup
531/// would hand the policy's refusal straight back.
532pub const VARS_ATTR: &str = "data-vars";
533
534/// The class an option of a selector carries, which is what the rules key off.
535///
536/// Named for the option and not for the group: [`selector_rules`] styles the
537/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
538/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
539/// and `option`, put `toggle` on the wrapping element rather than on the
540/// buttons inside it, and every described selector in that renderer came out
541/// with no depth, no focus ring and no chosen state, while the toggle group got
542/// a bevel meant for its buttons.
543///
544/// The chosen option additionally carries `chosen`, the same way a latched chip
545/// carries `latched`. That name is this crate's too; there is no reason for a
546/// caller to spell it, and [`selector_rules`] is where it is written down.
547#[must_use]
548pub fn option_class(selector: Selector) -> &'static str {
549 match selector {
550 Selector::Tabs => "tab",
551 Selector::Segmented => "segment",
552 Selector::Toggle => "toggle",
553 }
554}
555
556/// The fill and edge declarations for a depth, as a rule body.
557///
558/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
559/// Callers lean on the emptiness to skip the rule rather than emit a class that
560/// sets nothing: a class that sets no properties is a class that means "I
561/// thought about this", which is what comments are for.
562///
563/// The two halves are emitted independently because [`Depth::Sunken`] has a
564/// fill and no bevel. Requiring both would silently drop the fill for exactly
565/// that case. Independent does not
566/// mean unpaired: both halves still come off one `Depth`, so they cannot
567/// disagree about what the region is.
568#[must_use]
569pub fn depth_declarations(depth: Depth) -> String {
570 let mut css = String::new();
571 if let Some(fill) = depth.fill() {
572 let _ = writeln!(css, " background: {};", fill_var(fill));
573 }
574 if let Some(bevel) = depth.bevel() {
575 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
576 }
577 css
578}
579
580/// One rule giving a selector a depth, or nothing when the depth declares
581/// nothing.
582#[must_use]
583pub fn depth_rule(selector: &str, depth: Depth) -> String {
584 let body = depth_declarations(depth);
585 if body.is_empty() {
586 return String::new();
587 }
588 format!(".{selector} {{\n{body}}}\n")
589}
590
591/// The media condition a hover rule has to sit inside, or `None` if hover is
592/// unconditional.
593///
594/// Two crates answer this and neither answer is made here. `makeover-touch`
595/// owns *whether* hover exists at a density, and `makeover-geometry` owns how
596/// that capability is spelled as a media condition. Asking both is what stops
597/// this renderer minting a third opinion, which is what all three apps did:
598/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
599/// alone, and the MNW server had no gate at all.
600///
601/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
602/// member, which reports as much through `reads_size`. Passing Compact is not
603/// a claim about width; the test below pins that every class agrees.
604fn hover_condition() -> Option<&'static str> {
605 if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
606 // A fingertip grew a hover state. Nothing to gate, and this renderer
607 // should not invent a reason to gate anyway.
608 None
609 } else {
610 Some(Density::Pointer.media_condition())
611 }
612}
613
614/// Put a rule inside a media query, or leave it alone.
615fn gated(condition: Option<&str>, rule: &str) -> String {
616 let Some(condition) = condition else {
617 return rule.to_string();
618 };
619 let mut css = format!("@media {condition} {{\n");
620 for line in rule.lines() {
621 // Blank lines stay blank. Indenting one leaves trailing whitespace,
622 // which is the sort of thing a formatter later reverts and calls a diff.
623 if line.is_empty() {
624 css.push('\n');
625 } else {
626 let _ = writeln!(css, " {line}");
627 }
628 }
629 css.push_str("}\n");
630 css
631}
632
633/// The keyboard focus ring, placed by the depth it lands on.
634///
635/// This is the webview's **focus ring** and nothing more. **Reach** and
636/// **focus** are both the browser's — the document decides what is reachable
637/// and `:focus-visible` decides which reached thing wears the ring — and no
638/// description states either. The three terms are defined once in
639/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
640///
641/// One ring for the whole system, because a focus ring's job is to be
642/// recognised and three apps having three of them is the failure. What varies
643/// is where it sits, and that comes off [`Depth`] rather than off a per-
644/// component choice: a well takes the ring inside its own edge, and anything
645/// standing proud of the page takes it outside.
646///
647/// `outline` rather than the composed `box-shadow` the invalid-field ring at
648/// [`field_rules`] uses, and deliberately the one place the two rings are built
649/// differently. A `box-shadow` ring has to restate the bevel beside it, because
650/// `box-shadow` is not additive and a lone ring silently drops the well out
651/// from under the element. That restatement is a second copy of the depth,
652/// living in a different function from the first, and it is exactly the
653/// duplication `Depth` exists to prevent. `outline` occupies its own property,
654/// so the bevel survives untouched and there is nothing to keep in agreement.
655/// They render the same: both are a flush ring one border-width wide.
656#[must_use]
657pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
658 let w = opts.focus_width;
659 // Same magnitude either way, and only the sign comes off the depth. Both
660 // values are what the consumers had already converged on independently:
661 // 2px out is what all three wrote, and 2px in is the MNW server's own
662 // answer for the one inset ring it had.
663 let offset = match depth.bevel() {
664 // Inside the well, clear of its edge rather than painted over it.
665 Some(Bevel::Inset) => format!("calc(-1 * {w})"),
666 // Raised, or no edge at all. Outside, standing off by its own width.
667 _ => w.to_string(),
668 };
669 // The token by name. It is `makeover`'s, derived from the action colour,
670 // and reaching it through a description member was a second path to the
671 // same variable for as long as one existed.
672 format!(
673 ".{selector}:focus-visible {{\n outline: {w} solid var(--focus-ring);\n outline-offset: {offset};\n}}\n"
674 )
675}
676
677/// A rest depth said out loud on both axes, for a rule that has to beat the
678/// states above it.
679///
680/// [`depth_declarations`] states an axis only when the depth has something to
681/// say about it, which is right for a rest rule: a [`Depth::Flat`] region
682/// inherits what it sits on, and asserting `background: none` there would be
683/// the difference between level-with and painted-transparent. It is wrong for
684/// a rule whose whole job is to take a state back. An axis left unstated is an
685/// axis the state above keeps, so `Flat` re-asserted nothing at all and a
686/// disabled control kept whatever hover had given it.
687///
688/// So the axes the depth is silent on are withdrawn rather than skipped, and
689/// the withdrawal is spelled by [`reset`] rather than here, so a disabled
690/// control and a flat one say the same words. Reaches further than the fill:
691/// [`Depth::Sunken`] and [`Depth::Overlay`] have no bevel either, and the
692/// pressed rule above hands out an inset one.
693fn rest_declarations(depth: Depth) -> String {
694 let mut css = String::new();
695 match depth.fill() {
696 Some(fill) => {
697 let _ = writeln!(css, " background: {};", fill_var(fill));
698 }
699 None => css.push_str(&Reset::NOTHING.and(Chrome::Fill).declarations()),
700 }
701 match depth.bevel() {
702 Some(bevel) => {
703 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
704 }
705 None => css.push_str(&Reset::NOTHING.and(Chrome::Shadow).declarations()),
706 }
707 css
708}
709
710/// Present, visible, and not answering.
711///
712/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
713/// only matches form elements and half the things this crate emits are not
714/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
715/// the accessible state is the pattern [`field_rules`] already establishes for
716/// `aria-invalid`, on the reasoning that one fact read by both the styling and
717/// the accessibility tree cannot drift from itself.
718///
719/// The rest depth is re-asserted rather than assumed, because this rule has to
720/// beat the hover and pressed rules above it. It does that on source order at
721/// equal specificity, not by out-specifying them: every rule this function's
722/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
723/// one of them and have to be unpicked when this output moves inside its own
724/// cascade layer.
725///
726/// Re-asserted on **both** axes, through [`rest_declarations`].
727/// `depth_declarations` alone is empty for [`Depth::Flat`], so a flat control
728/// would win the contest with nothing to say and keep the hover surface
729/// underneath a control that had stopped answering.
730#[must_use]
731pub fn disabled_rule(selector: &str, depth: Depth) -> String {
732 format!(
733 ".{selector}:disabled,\n.{selector}[aria-disabled=\"true\"] {{\n{} color: var(--{});\n cursor: not-allowed;\n}}\n",
734 rest_declarations(depth),
735 State::Disabled.token()
736 )
737}
738
739/// Every state a selector that answers a click implies: hover, pressed, focus
740/// and disabled, in that order.
741///
742/// Order is the whole cascade mechanism here. All four selectors are
743/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
744/// and by nothing else.
745///
746/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
747/// only the edge is what left goingson hand-writing `background:
748/// var(--surface-sunken)` on three separate rules, and a fill that does not
749/// travel with its edge is precisely the disagreement `Depth` exists to make
750/// unrepresentable. So the pressed fill comes from the description
751/// (`--surface-well`) rather than from whatever each app reached for.
752///
753/// Hover has no member in the description and is renderer policy: a terminal
754/// and an immediate-mode painter have no hover to express. It resolves against
755/// `--hover-surface`, which `makeover` already derives and which nothing
756/// consumed until now. What it *is* gated on is capability, via
757/// [`hover_condition`]. Before that gate existed the apps each wrote their own:
758/// goingson's section 60 exists solely to take back the hover state this
759/// function had just handed it, by out-specifying a rule it does not own.
760///
761/// `depth` is the selector's **rest** depth, used to place the focus ring and
762/// to restore the surface under a disabled control. The pressed rule keeps
763/// inverting from [`Depth::Raised`] regardless: a tab's unchosen depth is
764/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
765/// from the rest depth would leave a tab with no press at all.
766#[must_use]
767pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
768 let mut css = gated(
769 hover_condition(),
770 &format!(".{selector}:hover {{\n background: var(--hover-surface);\n}}\n"),
771 );
772 css.push_str(&depth_rule(
773 &format!("{selector}:active"),
774 Depth::Raised.pressed(),
775 ));
776 css.push_str(&focus_rule(selector, depth, opts));
777 css.push_str(&disabled_rule(selector, depth));
778 css
779}
780
781/// The compound a card's interactive states are written against: the class
782/// on an element that is itself a control.
783///
784/// `label` for a card wrapping a choice, `[data-act]` for an act a renderer
785/// drew on some other element. Without the class prefix, the way every
786/// selector handed to [`interactive_rules`] is.
787#[must_use]
788pub fn pressable_card(card: &str) -> String {
789 format!("{card}:is(a, button, label, [data-act])")
790}
791
792/// One rule per depth: its fill and its edge, together.
793///
794/// A depth and nothing else. `.raised` says a surface sits on what is behind
795/// it, which is a statement about the shape and not about what happens when a
796/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
797/// named surfaces are where interaction lives: `.button`, and `.card` written
798/// on a control, get their states from [`surface_rules`].
799///
800/// Giving this class the interactive set leaves the vocabulary with no raised
801/// surface that is merely an object, so a consumer that needs one has to take a
802/// control class and cancel half of it.
803#[must_use]
804pub fn depth_rules(opts: &Emit) -> String {
805 let mut css = String::new();
806 for depth in [Depth::Raised, Depth::Well] {
807 let Some(class) = depth_class(depth, opts) else {
808 continue;
809 };
810 css.push_str(&depth_rule(&class, depth));
811 }
812 css
813}
814
815/// The three surfaces that are a depth with a name.
816///
817/// `button` and `card` are both [`Depth::Raised`], and `field` is a
818/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
819/// gives a text field. Their bodies come out identical by construction rather
820/// than by hand: three hand-written copies in goingson's stylesheet is what
821/// phase A deletes, and generating them from one call is what stops them
822/// drifting apart again.
823///
824/// A card's states hang off [`pressable_card`] rather than the bare class. A
825/// card is a raised object that answers a pointer only when it is written on a
826/// control, which is what lets one name cover both: a store tile that is one
827/// link, a tier picker that is a label round a radio, and a use-case card that
828/// does nothing and so has no hover to cancel.
829fn surface_rules(opts: &Emit) -> String {
830 let mut css = String::new();
831 let button = class("button", opts);
832 css.push_str(&depth_rule(&button, Depth::Raised));
833 css.push_str(&interactive_rules(&button, Depth::Raised, opts));
834
835 let card = class("card", opts);
836 css.push_str(&depth_rule(&card, Depth::Raised));
837 css.push_str(&interactive_rules(
838 &pressable_card(&card),
839 Depth::Raised,
840 opts,
841 ));
842
843 let field = class("field", opts);
844 css.push_str(&depth_rule(&field, Depth::Well));
845
846 // A field takes focus and refuses input like everything else here, and got
847 // neither until now, which is why all three apps hand-write a focus ring
848 // for it and no two of them match. No hover or pressed: a text field does
849 // not light up under the pointer and does not invert when clicked, so the
850 // two states `interactive_rules` would add are the two it does not have.
851 css.push_str(&focus_rule(&field, Depth::Well, opts));
852 css.push_str(&disabled_rule(&field, Depth::Well));
853
854 // A file field's own button is a button. `::file-selector-button` is the
855 // one part of an `<input type="file">` a stylesheet reaches, and without a
856 // rule the platform's grey control sits inside a well drawn in the theme's.
857 // Raised, with the hover and the press a button has; no focus ring, because
858 // the focus belongs to the input the pseudo-element is part of, and the
859 // field's own ring already draws it.
860 let chooser = format!("{field}::file-selector-button");
861 css.push_str(&depth_rule(&chooser, Depth::Raised));
862 let _ = writeln!(
863 css,
864 ".{chooser} {{\n border: none;\n color: inherit;\n font: inherit;\n padding: var(--gap-bound) var(--gap-peer);\n margin-inline-end: var(--gap-peer);\n cursor: pointer;\n}}"
865 );
866 css.push_str(&gated(
867 hover_condition(),
868 &format!(".{chooser}:hover {{\n background: var(--hover-surface);\n}}\n"),
869 ));
870 css.push_str(&depth_rule(
871 &format!("{chooser}:active"),
872 Depth::Raised.pressed(),
873 ));
874
875 // Keyed on the ARIA attribute rather than on a class, so the visual state
876 // and the accessible state cannot drift apart: there is one fact and both
877 // read it. goingson already drove its invalid styling this way and was
878 // right to; the `.invalid` class this emitted before 0.5.0 was a second
879 // place to forget.
880 //
881 // The ring composes *after* the bevel rather than replacing it. box-shadow
882 // is not additive, so a lone ring silently dropped the well out from under
883 // an invalid field. Flat and unlit: this edge is saying "wrong", and
884 // lighting one side would have it say "raised" at the same time.
885 let _ = writeln!(
886 css,
887 ".{field}[aria-invalid=\"true\"] {{\n box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
888 bevel_var(Bevel::Inset),
889 opts.border_width
890 );
891
892 // The default-button ring, on the one control that commits
893 // (`makeover_layout::Act::commits`, wiki `explicit-commit-affordance`).
894 // A flush frame twice the border width, composed after the bevel for the
895 // invalid ring's reason, and outside the element, so the focus outline,
896 // which stands off by its own width, lands beside it rather than over it.
897 // Pressed keeps the ring and inverts only the bevel; disabled keeps it in
898 // the muted ink, the way a disabled control keeps its bevel.
899 //
900 // An attribute rather than a class, for `data-tone`'s reason: it is a fact
901 // about the act, and a renderer writes it beside the tone.
902 let ring = format!("0 0 0 calc(2 * {})", opts.border_width);
903 let _ = writeln!(
904 css,
905 ".{button}[data-commits] {{\n box-shadow: var({}), {ring} var(--border-strong);\n font-weight: bold;\n}}",
906 bevel_var(Bevel::Raised)
907 );
908 let _ = writeln!(
909 css,
910 ".{button}[data-commits]:active {{\n box-shadow: var({}), {ring} var(--border-strong);\n}}",
911 bevel_var(Bevel::Inset)
912 );
913 let _ = writeln!(
914 css,
915 ".{button}[data-commits]:is(:disabled, [aria-disabled=\"true\"]) {{\n box-shadow: var({}), {ring} var(--content-muted);\n}}",
916 bevel_var(Bevel::Raised)
917 );
918 css
919}
920
921/// Badges and chips.
922///
923/// The one place phase A changes how goingson looks rather than only where its
924/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
925/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
926/// carrying the raised bevel. Splitting that means reading every call site to
927/// decide which of the two it always was.
928///
929/// What a badge does carry is a [`Tone`], the intent family it shares with
930/// notices and nothing else. Neutral is the bare class rather than a variant,
931/// because it is the absence of a status and not a status called "none".
932/// Text that goes somewhere.
933///
934/// The one inline control. A table cell carries `cell-link` instead, which
935/// reads as its row's title rather than as a link; this is the same thing
936/// outside a table, which is what a described run holds when a sentence
937/// contains a link.
938///
939/// Colour and underline only. Whether a link is inline in a sentence or sitting
940/// on its own line is the app's layout, and how much room it takes is
941/// `makeover-geometry`'s. What is here is the pair of signals that say "this
942/// goes somewhere" and nothing that says where it sits.
943///
944/// The visited arm is deliberately absent. A link inside an app points at the
945/// app's own screens, which the user is expected to have been to, so painting
946/// them differently marks almost everything and distinguishes nothing.
947fn link_rules(opts: &Emit) -> String {
948 let mut css = String::new();
949 let link = class("link", opts);
950
951 let _ = writeln!(
952 css,
953 ".{link} {{\n color: var(--action);\n \
954 text-decoration: underline;\n}}"
955 );
956 // The hover step is the same one every other control takes, and it is a
957 // colour rather than a surface: a link has no box to raise.
958 let _ = writeln!(
959 css,
960 "@media (hover: hover) and (pointer: fine) {{\n .{link}:hover \
961 {{\n color: var(--action-hover);\n }}\n}}"
962 );
963 let _ = writeln!(
964 css,
965 ".{link}:focus-visible {{\n outline: {} solid var(--focus-ring);\n \
966 outline-offset: 2px;\n}}",
967 opts.focus_width
968 );
969 // A link is often a `<button>` rather than an `<a>`: a renderer picks the
970 // element from the method, so a link that writes is a button that has to
971 // stop looking like one. What that costs is named in [`reset`].
972 css.push_str(&Reset::TEXT_BUTTON.rule(&format!("button.{link}")));
973 css
974}
975
976fn token_rules(opts: &Emit) -> String {
977 let mut css = String::new();
978
979 // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
980 // and a label with an edge says it can be pressed.
981 let badge = class("badge", opts);
982 // `content-muted` literally, not `Tone::Neutral.token()`. What makes a
983 // badge quiet is `Token::Badge` answering no click, which this crate holds
984 // and `Tone` genuinely does not know. Routing it through Neutral put the
985 // claim where the evidence was not, and the bill arrived on the figure
986 // value: it took the same muting from the same call and read as its own
987 // caption. Neutral answers `content` from makeover-layout 0.36.0.
988 //
989 // A badge is a chip, wiki `table-model`: an opaque fill inside an edge, in
990 // the theme's own ink at normal weight. Coloured text was never ratified
991 // and measured 1.34:1 on goingson's warning; muted text 2.78:1 on
992 // solarized-dark. So the ink is `content` and what says which kind of
993 // token it is moves to the fill and the edge: the table's raised ground for
994 // a neutral chip, makeover's `*-surface` for a status, edged in its tone.
995 // Still no bevel: a label with a raised edge says it can be pressed.
996 let bw = opts.border_width;
997 let _ = writeln!(
998 css,
999 ".{badge} {{\n display: inline-flex;\n align-items: center;\n \
1000 padding: 0 var(--step-snug);\n border: {bw} solid var(--border);\n \
1001 border-radius: var(--radius-fine);\n background: var(--surface-raised);\n \
1002 color: var(--content);\n font-weight: normal;\n}}"
1003 );
1004 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1005 let _ = writeln!(
1006 css,
1007 ".{badge}[data-tone=\"{0}\"] {{\n background: var(--{0}-surface);\n \
1008 border-color: var(--{0});\n}}",
1009 tone.token()
1010 );
1011 }
1012
1013 // A button carries the four tones a badge does. It had none, on the reading
1014 // that a control's colour is its surface rather than its text, and that
1015 // reading has one hole big enough to matter: the button that destroys
1016 // something. Every consumer had written that rule itself, and a description
1017 // that says `Tone::Danger` on an act had nowhere for it to land.
1018 //
1019 // Colour and not a fill, matching the badge. A red surface is a decision
1020 // about emphasis that belongs to an app's own layer, and two of them
1021 // fighting is worse than neither.
1022 let button = class("button", opts);
1023 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1024 let _ = writeln!(
1025 css,
1026 ".{button}[data-tone=\"{0}\"] {{\n color: var(--{0});\n}}",
1027 tone.token()
1028 );
1029 }
1030
1031 // A chip holds itself down, which is `Depth::pressed` arrived at
1032 // independently by two apps. `removable` is a remove affordance, so it is
1033 // markup and waits for phase B.
1034 let chip = class("chip", opts);
1035 let unlatched = Token::Chip { removable: false };
1036 css.push_str(&depth_rule(&chip, unlatched.depth(false)));
1037 css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
1038 css.push_str(&depth_rule(
1039 &format!("{chip}.latched"),
1040 unlatched.depth(true),
1041 ));
1042 css
1043}
1044
1045/// The three selectors, each named by what it picks.
1046///
1047/// A tab comes *forward* to join the pane it opens, which is why
1048/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
1049/// are held in. That is the folder semantic, and it is the whole reason the
1050/// three are not one member with a flag.
1051///
1052/// [`Selector::abutting`] is not emitted: whether the options touch is
1053/// spacing, and spacing is `makeover-geometry`'s question to answer.
1054///
1055/// Both states emit. Naming only the chosen option leaves an unchosen one
1056/// falling through to [`Depth::Flat`] with nothing drawn for it, so an app has
1057/// to hand-write the recess that makes its chosen tab read as forward.
1058fn selector_rules(opts: &Emit) -> String {
1059 let mut css = String::new();
1060 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
1061 let c = class(option_class(selector), opts);
1062 css.push_str(&depth_rule(&c, selector.unchosen()));
1063 css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
1064 css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
1065 }
1066 css
1067}
1068
1069/// The parts of a list row.
1070///
1071/// The list is written out rather than derived because `RowPart` is
1072/// `#[non_exhaustive]`, so there is nothing to iterate. A member added upstream emits no rule until it is named here, which
1073/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
1074/// [`part_class`] carries the same list and the same obligation.
1075fn row_rules(opts: &Emit) -> String {
1076 let mut css = String::new();
1077
1078 // The container the rows sit in, giving back what a `<ul>` brought. Not a
1079 // size: there is no magnitude in it, which is the line this crate holds.
1080 css.push_str(&Reset::BULLETS.rule(&format!(".{}", class("list", opts))));
1081
1082 for part in [
1083 RowPart::Primary,
1084 RowPart::Secondary,
1085 RowPart::Meta,
1086 RowPart::Actions,
1087 RowPart::Tokens,
1088 RowPart::Proportion,
1089 ] {
1090 let c = class(part_class(part), opts);
1091
1092 // Actions carry controls rather than text, and `RowPart::intent` says
1093 // so by returning the same intent inheriting already gives. Pinning it
1094 // would be louder than saying nothing. Tokens answer alike, for their
1095 // own reason: each token carries its own tone, and a colour on the
1096 // strip would fight the things sitting in it. A proportion is the same
1097 // case again: the meter inside carries the tone.
1098 if !matches!(
1099 part,
1100 RowPart::Actions | RowPart::Tokens | RowPart::Proportion
1101 ) {
1102 let _ = writeln!(css, ".{c} {{\n color: var(--{});\n}}", part.intent());
1103 }
1104
1105 // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
1106 // otherwise and was not honoured here from 0.23.0; makeover-layout
1107 // 0.13.0 retired the method, so there is no longer a description saying
1108 // one thing and a renderer doing another.
1109 //
1110 // The rule was `opacity: 0` gated to pointer devices, revealed on
1111 // `:hover` and on `:focus-within`. Each escape it needed was a report
1112 // that hiding was wrong for somebody: `focus-within` because tabbing
1113 // could never reach an action; the gate because a fingertip had no way
1114 // to unhide, which both webview apps had already hand-written
1115 // `opacity: 1` to undo. What was left was a control hidden from
1116 // exactly one group: people using a pointer, who are also the group
1117 // scanning a list to find out what can be done to a row.
1118 //
1119 // A settings screen is where that reads worst: the whole reason to be
1120 // on it is to remove a key, and the button doing so was invisible
1121 // until pointed at. A table cell's actions were never hidden, so the
1122 // two arrangements now agree.
1123 }
1124
1125 // A part that may take two lines. `Flow::Tight` gets no rule: one line is
1126 // what a run already does, and restating it here would put a declaration on
1127 // every part in every row to say nothing.
1128 //
1129 // This is the shape both webview apps had already written by hand and
1130 // commented -- Balanced Breakfast on a feed row's title, goingson on a
1131 // problem's body -- which is the whole argument for the description
1132 // carrying it. `-webkit-` prefixed and unprefixed together: the prefixed
1133 // trio is what every engine actually implements, and `line-clamp` is the
1134 // standard property landing behind it.
1135 let _ = writeln!(
1136 css,
1137 ".{} {{\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: {lines};\n line-clamp: {lines};\n overflow: hidden;\n}}",
1138 class("row-relaxed", opts),
1139 lines = Flow::Relaxed.lines()
1140 );
1141
1142 // A row inside a hierarchy: a tree, an outline, a threaded list.
1143 // `edf33114`, decided 2026-08-30 (Max). makeover-layout names the concept
1144 // as `Nesting` -- deliberately not `Depth`, which is surface bevel in that
1145 // crate -- and this is the rule.
1146 //
1147 // Measured 2026-08-30: quasi-webview has been emitting `row-nested` with
1148 // `style="--row-depth:N"` on every described hierarchy, and **no stylesheet
1149 // anywhere in the tree read any of it**. So a described outline in a
1150 // browser was a flat list with chevrons in it -- the folding worked and the
1151 // indent did not exist.
1152 //
1153 // The magnitude is a custom property with a fallback, which is this crate's
1154 // own shape: `--awaiting-gap` above is the precedent, and an app overriding
1155 // `--row-indent` is how a level becomes worth more or less. What a level IS
1156 // stays the description's; what it is WORTH is a renderer's, and a terminal
1157 // spending columns for the same fact is not disagreeing.
1158 //
1159 // Here rather than in each app, and that was a live option rather than an
1160 // oversight. `row-select`, `row-current` and `row-chosen` are app-styled by
1161 // design; the indent is not decoration, it is what the description MEANS,
1162 // and three apps agreeing about it by accident is not agreement.
1163 //
1164 // `padding` and not `margin`: a row is a box that can be selected and
1165 // hovered, and indenting with margin would take the indent out of the
1166 // highlight, so the shading under a nested row would start where its text
1167 // does rather than where its row does.
1168 let _ = writeln!(
1169 css,
1170 ".{} {{\n padding-inline-start: calc(var(--row-depth, 0) * var(--row-indent, 1.5ch));\n}}",
1171 class("row-nested", opts)
1172 );
1173
1174 // The two halves of a branch, emitted by quasi-webview and unstyled until
1175 // now for the same reason.
1176 //
1177 // A branch row is the one a reader can fold, and the chevron is its hit
1178 // target. The chevron is drawn by the app or the description -- this says
1179 // where it sits and how big the target is, which is the accessibility fact
1180 // rather than the decorative one: a control smaller than this is one a
1181 // finger misses.
1182 let _ = writeln!(
1183 css,
1184 ".{} {{\n display: flex;\n align-items: baseline;\n gap: var(--row-disclose-gap, 0.5ch);\n}}",
1185 class("row-branch", opts)
1186 );
1187 let _ = writeln!(
1188 css,
1189 ".{} {{\n flex: none;\n min-inline-size: var(--tap-target, 2rem);\n min-block-size: var(--tap-target, 2rem);\n background: none;\n border: 0;\n color: inherit;\n cursor: pointer;\n}}",
1190 class("row-disclose", opts)
1191 );
1192
1193 // How a part holds what is in it, for a row and for a table cell. These
1194 // were quasi-webview's arrangement sheet's until 0.82.0, which ruled names
1195 // this crate emits, so a row an app wrote by hand got none of it. The row
1196 // itself stays quasi-webview's: where a part sits in the line is the screen
1197 // renderer's arrangement, and nothing here says it.
1198 //
1199 // A token or a control never breaks across two lines. What gives when the
1200 // line runs short is the row's text.
1201 let tokens = class(part_class(RowPart::Tokens), opts);
1202 let actions = class(part_class(RowPart::Actions), opts);
1203 let proportion = class(part_class(RowPart::Proportion), opts);
1204 let fallback = class("row-part", opts);
1205 let cell_tokens = class(cell_part_class(CellPart::Tokens), opts);
1206 let cell_actions = class(cell_part_class(CellPart::Actions), opts);
1207 let cell_fallback = class("cell-part", opts);
1208 let _ = writeln!(
1209 css,
1210 ".{fallback},\n.{cell_fallback} {{\n min-width: 0;\n}}"
1211 );
1212 let _ = writeln!(
1213 css,
1214 ".{tokens} {{\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1215 );
1216 let _ = writeln!(
1217 css,
1218 ".{actions} {{\n display: flex;\n flex: none;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1219 );
1220 // A cell's parts sit inside the cell's own box, so they are inline: the
1221 // cell's alignment, which the column kind sets, still places them.
1222 let _ = writeln!(
1223 css,
1224 ".{cell_tokens},\n.{cell_actions} {{\n display: inline-flex;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1225 );
1226 let _ = writeln!(css, ".{cell_tokens} {{\n flex-wrap: wrap;\n}}");
1227 let _ = writeln!(
1228 css,
1229 ".{tokens} > *,\n.{actions} > *,\n.{cell_tokens} > *,\n.{cell_actions} > * {{\n white-space: nowrap;\n}}"
1230 );
1231 // A proportion is a meter, and a meter is as wide as the row lets it be.
1232 let _ = writeln!(css, ".{proportion} {{\n flex: 1 1 auto;\n}}");
1233
1234 css
1235}
1236
1237/// A row of things that share their space, and what each fallback gets here.
1238///
1239/// Ruling: wiki `layout-room-and-fallback`, Max. Rule 1 is that every described
1240/// member is in flow, and these rules are how that is kept rather than asked
1241/// for. A member taken out of flow with `position: absolute` contributes zero
1242/// width to the row it shares, so nothing can collide with it and nothing
1243/// prevents the collision.
1244///
1245/// # The floor, which is most of the fix
1246///
1247/// `.run > *` gets `min-width: min-content`. That is the derived minimum the
1248/// ruling asks for, in this renderer's own unit and stated by the browser
1249/// rather than by anybody: a member cannot be squeezed narrower than what is
1250/// in it, so members in one flow push each other instead of overlapping. It
1251/// costs no query and no number, and it is what fixes all four measured widths
1252/// whichever fallback the group declared.
1253///
1254/// # A member that asks to fill
1255///
1256/// `.run > [data-width="fill"]` gets `flex: 1 1 0`, which is the second half of
1257/// what a column has always been able to say, reaching a row of regions.
1258/// `flex-basis: 0` and not `auto` is what makes several fills divide the room
1259/// equally rather than dividing the leftovers in proportion to their contents;
1260/// equal division is [`makeover_layout::Width::Fill`]'s own stated rule. The
1261/// floor above still applies, so a fill cannot shrink under what is in it.
1262///
1263/// A member that says nothing gets nothing, because a flex item with the floor
1264/// and no grow is already content-sized. That is why the omitted value here is
1265/// `Content` while a control omits `Fill`: each position leaves out what it
1266/// already did.
1267///
1268/// # What each fallback gets, exactly
1269///
1270/// [`Fallback::Wrap`] is `flex-wrap: wrap`, which is exact. The browser wraps
1271/// the run when the members no longer fit, deciding that from their own
1272/// intrinsic widths, which is the derived minimum doing the whole job.
1273///
1274/// [`Fallback::Stack`] is wrap plus `flex: 1 1 max-content` on the members, so
1275/// a member that cannot sit beside its sibling takes a line of its own and
1276/// fills it. For the two-member run this was ruled on -- a tab strip and a
1277/// band -- that is precisely "a row becomes a column".
1278///
1279/// [`Fallback::Shed`] and [`Fallback::Menu`] get wrap, and this renderer is
1280/// honouring less than the description says. **CSS cannot express either one
1281/// without breaking the ruling's own first constraint.** Both need to know that
1282/// the run is out of room in order to take a member out of it, a container
1283/// query is the only construct that can ask, and `@container` compares against
1284/// a `<length>` -- there is no `@container (inline-size < min-content)`. So
1285/// every honest spelling of Shed here needs an authored breakpoint, which is
1286/// the thing the ruling exists to forbid, and the dishonest ones are worse: a
1287/// clamped height clips by document order rather than by [`Priority`], and
1288/// `display: none` under a viewport `@media` is the `nth-child(n+5)` bug the
1289/// vocabulary replaced.
1290///
1291/// Wrapping is the right thing to do instead. It keeps every member reachable,
1292/// which is the property that was actually broken -- goingson's new-contact
1293/// button left the viewport entirely at 560 -- and it keeps rule 1. A renderer
1294/// answering with less than was described is precedented and deliberate here:
1295/// [`makeover_layout::Region::Columns`] says a terminal stacking a board's
1296/// columns is honouring the description rather than degrading it.
1297///
1298/// The real mechanism needs the shed members to have somewhere to go, which is
1299/// markup and belongs to quasi-webview: an overflow control is a member of the
1300/// run, and the description does not yet say that a member *is* one.
1301///
1302/// # Menu, once a script is measuring
1303///
1304/// That is now built, in `quasi-webview`'s `menu.js`, and this crate's half of
1305/// it is two classes and one override. A script that has taken a menu run over
1306/// marks it `data-menu`, and a marked run goes back to `nowrap`: wrapping is
1307/// what hides the overflow condition the script is trying to measure. The
1308/// unmarked rule above is untouched, so a page that ships no script still
1309/// wraps, which is rule 1 — every member reachable — rather than a strip with
1310/// tabs squeezed off the end.
1311///
1312/// `.run-overflow` is the control the shed members move into and
1313/// `.run-overflow-items` is where they land. The geometry is this crate's the
1314/// way every other surface's is; what is *in* it is the script's, because which
1315/// members no longer fit is a measurement and not a description.
1316fn run_rules(opts: &Emit) -> String {
1317 let run = class("run", opts);
1318 let mut css = String::new();
1319
1320 // `flex-wrap: nowrap` is stated rather than left to the default, because
1321 // the fallbacks below are read as overrides of this line and a reader
1322 // should not have to know which way flexbox leans to see that.
1323 //
1324 // No gap. Spacing between members is the app's, the same way this crate
1325 // states no margins anywhere else; a gap here would be a size, and the one
1326 // hardcoded size in the mechanism is makeover-geometry's contact patch.
1327 let _ = writeln!(
1328 css,
1329 ".{run} {{\n display: flex;\n flex-wrap: nowrap;\n align-items: center;\n}}"
1330 );
1331
1332 // The derived minimum, and the whole reason a member can no longer be
1333 // overlapped. `min-width: auto` is flexbox's default for a flex item and is
1334 // *not* the same thing: auto lets an item be compressed below its content
1335 // in a nowrap run, which is how a toolbar ends up drawn over a tab strip
1336 // even without anything leaving the flow.
1337 let _ = writeln!(css, ".{run} > * {{\n min-width: min-content;\n}}");
1338
1339 // A member that absorbs what is left. `flex-basis: 0` rather than `auto` is
1340 // what makes several fills divide the room equally instead of dividing the
1341 // leftovers in proportion to what is already in them, which is
1342 // `Width::Fill`'s own rule and the one thing that type states about more
1343 // than one of them.
1344 //
1345 // The `min-width: min-content` floor above is deliberately not overridden.
1346 // A fill that could shrink below its contents would overlap its neighbour,
1347 // which is rule 1, and equal division under a floor is still equal division
1348 // everywhere the floor is not reached.
1349 //
1350 // Attribute rather than class, because the width is a fact the description
1351 // carried rather than a hook this crate invented: the same division
1352 // `data-tone` and `data-selector` are on the right side of. It beats the
1353 // `Stack` rule below on specificity whichever order they are written in,
1354 // which is what a member asking to fill should do to a blanket.
1355 let _ = writeln!(
1356 css,
1357 ".{run} > [data-width=\"fill\"] {{\n flex: 1 1 0;\n}}"
1358 );
1359
1360 for fallback in [
1361 Fallback::Wrap,
1362 Fallback::Stack,
1363 Fallback::Shed,
1364 Fallback::Menu,
1365 ] {
1366 let name = fallback_class(fallback);
1367 let c = class(name, opts);
1368 let _ = writeln!(css, ".{c} {{\n flex-wrap: wrap;\n}}");
1369 if matches!(fallback, Fallback::Stack) {
1370 let _ = writeln!(css, ".{c} > * {{\n flex: 1 1 max-content;\n}}");
1371 }
1372 }
1373
1374 // A menu run a script has taken over. The mark is the script's and this is
1375 // the only rule that reads it: wrapping is what a run does when nothing is
1376 // measuring, and it is also what makes the overflow unmeasurable, since a
1377 // wrapped run always fits. The two cannot both be on.
1378 let menu = class(fallback_class(Fallback::Menu), opts);
1379 let _ = writeln!(css, ".{menu}[data-menu] {{\n flex-wrap: nowrap;\n}}");
1380
1381 // The overflow control, and it is a member of the run like any other: in
1382 // flow, at the end, taking the width of what is in it. `relative` is what
1383 // the items hang off.
1384 let overflow = class("run-overflow", opts);
1385 let items = class("run-overflow-items", opts);
1386 let _ = writeln!(css, ".{overflow} {{\n position: relative;\n}}");
1387
1388 // Overlaid rather than in flow, for the reason every menu is: a control
1389 // that pushed the page down when it opened would change the layout it was
1390 // opened to escape. `inset-inline-end: 0` rather than a left, so the panel
1391 // stays on the page in both writing directions.
1392 //
1393 // No width, no padding and no border. All three are sizes and sizes are
1394 // makeover-geometry's; what is stated here is placement, the surface and
1395 // the shadow that separates it from the page, which is the same division
1396 // `figure_rules` and the timeline entry make. The elevation shadow is what
1397 // an overlaid surface takes instead of an edge -- see `ELEVATION_PROPERTY`.
1398 let _ = writeln!(
1399 css,
1400 ".{items} {{\n \
1401 position: absolute;\n \
1402 inset-block-start: 100%;\n \
1403 inset-inline-end: 0;\n \
1404 z-index: 1;\n \
1405 display: flex;\n \
1406 flex-direction: column;\n \
1407 align-items: stretch;\n \
1408 background: var(--surface-raised);\n \
1409 box-shadow: var(--elevation-overlay);\n\
1410 }}"
1411 );
1412
1413 // `hidden` is how the script closes it, and a flex display would otherwise
1414 // beat the attribute's own `display: none`.
1415 let _ = writeln!(css, ".{items}[hidden] {{\n display: none;\n}}");
1416
1417 css
1418}
1419
1420/// Every class [`fallback_class`] can return, plus the run itself.
1421///
1422/// [`ROW_PART_CLASSES`](crate::list::ROW_PART_CLASSES)'s reasoning and the same
1423/// obligation: a `match` over a `#[non_exhaustive]` enum cannot be enumerated
1424/// from outside, so the list sits beside it and a test holds the two together.
1425/// `run` is in it because it is emitted in its own right rather than only as a
1426/// fallback's fallback.
1427pub const RUN_CLASSES: &[&str] = &[
1428 "run",
1429 "run-wrap",
1430 "run-stack",
1431 "run-shed",
1432 "run-menu",
1433 // Not returned by `fallback_class`: these two are the overflow control a
1434 // measuring renderer builds, and they are in the list because the list is
1435 // what a host seals its vocabulary against. A class emitted by a script and
1436 // missing from here is a control with no surface and no edge.
1437 "run-overflow",
1438 "run-overflow-items",
1439];
1440
1441/// The class a run carries for what it does when it is tight.
1442///
1443/// A run always carries `.run` as well, so an unrecognised fallback -- the enum
1444/// is `#[non_exhaustive]` -- lands as a plain nowrap row with the min-content
1445/// floor still under it. That is the safe failure: every member in flow and
1446/// none overlapped, which is the property, with only the rearrangement missing.
1447#[must_use]
1448pub fn fallback_class(fallback: Fallback) -> &'static str {
1449 match fallback {
1450 Fallback::Wrap => "run-wrap",
1451 Fallback::Stack => "run-stack",
1452 Fallback::Shed => "run-shed",
1453 Fallback::Menu => "run-menu",
1454 _ => "run",
1455 }
1456}
1457
1458/// The progress trough these rules fill.
1459///
1460/// [`meter::meter_html`](crate::meter::meter_html) is what fills these.
1461///
1462/// The rules stay a superset of what a description can ask for. An app drawing
1463/// its own bar keeps these classes, which is what the four goingson grew
1464/// independently were adopted onto.
1465///
1466/// The trough is a [`Depth::Well`], the same reading a text field gets:
1467/// something with its content down inside it.
1468fn progress_rules(opts: &Emit) -> String {
1469 let progress = class("progress", opts);
1470 // `progress-fill` rather than a bare `fill`: an unprefixed build claims
1471 // these names in the app's own stylesheet, and `.fill` is grabby enough to
1472 // catch things that have nothing to do with progress. goingson already
1473 // calls it `.progress-fill`, so this is also the name that deletes.
1474 let fill = class("progress-fill", opts);
1475 let mut css = depth_rule(&progress, Depth::Well);
1476
1477 // The untoned bar is `--action`, not [`Tone::Neutral`]. That is the one
1478 // place this differs from the badge rules, and deliberately: a badge with
1479 // no status is a muted label, while a bar with no status is still
1480 // reporting progress, and `content-muted` would read as disabled.
1481 // The width is the fill the meter emitter hands over in `data-vars`. The
1482 // fallback is an empty bar rather than a full one: an unset width on a block
1483 // is the whole trough, which would read as done.
1484 //
1485 // On the fill alone, not under `.progress >`: a rule names every class in
1486 // its selector to a consumer's drift check, and the trough's width is the
1487 // app's to set. goingson sizes `.progress` and failed its build on a width
1488 // this rule never gave the trough.
1489 let _ = writeln!(css, ".{fill} {{\n width: var(--meter-fill, 0%);\n}}");
1490 let _ = writeln!(
1491 css,
1492 ".{progress} > .{fill} {{\n background: var(--action);\n}}"
1493 );
1494
1495 // A bar can be saying something, same as a badge: goingson colours subtask
1496 // progress as success and an over-estimate as danger, which is real
1497 // information rather than decoration. Emitting the tones is what lets that
1498 // survive adoption instead of staying hand-written.
1499 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1500 let _ = writeln!(
1501 css,
1502 ".{progress} > .{fill}[data-tone=\"{0}\"] {{\n background: var(--{0});\n}}",
1503 tone.token()
1504 );
1505 }
1506 css
1507}
1508
1509/// What a wait looks like, for the attribute that has been describing one to
1510/// nobody.
1511///
1512/// Wiki `loading-and-progress-standard`, phase 2. `data-awaiting` is emitted
1513/// as `data-awaiting="determinate"` with a `data-awaiting-amount` beside it, or
1514/// `data-awaiting="indeterminate"` alone. This is the half that styles them,
1515/// without which the two render identically.
1516///
1517/// # Why it is keyed on `aria-busy` and not on the attribute alone
1518///
1519/// `data-awaiting` is a fact about the control: pressing this waits. It is true
1520/// when the page is painted and it stays true. Whether a wait is *running* is
1521/// true only between two events, so it is the binder's to set, and `aria-busy`
1522/// is the standard spelling of it — announced as well as drawn, which a class
1523/// of our own would not be.
1524///
1525/// That also keeps this crate out of any one client library's vocabulary.
1526/// `quasi-webview` sets `aria-busy` from htmx's request events; a host driving
1527/// the same markup another way sets it the same way and gets the same drawing.
1528///
1529/// # The two drawings
1530///
1531/// One pseudo-element either way, so no renderer has to emit an extra node.
1532///
1533/// Indeterminate is the activity mark of rule 2: a small square that blinks.
1534/// Determinate is a trough with a fill, drawn as a single gradient whose stop is
1535/// `--awaiting-share`, a plain number from 0 to 1 that the binder sets from
1536/// bytes it has actually watched land. A determinate control with nothing
1537/// setting the share draws an empty trough rather than a full one, which is the
1538/// honest reading: the size is known and the delivery is not.
1539///
1540/// **What the bar may not do**, from rule 1 and from `Awaiting`'s own docs:
1541/// what is done over what there is, and never a remaining time, an arrival time
1542/// or a rate extrapolated forward. Nothing here can express one, which is
1543/// deliberate — the only input is a share of a measured payload.
1544///
1545/// # Sizes, and the deferral rule
1546///
1547/// `progress_rules` emits the tones and never the width, because the width is
1548/// not this crate's to know. A pseudo-element has no intrinsic size at all, so
1549/// the same treatment would render nothing anywhere. Both sizes are therefore
1550/// custom properties with defaults: an app that wants a different mark sets
1551/// `--awaiting-mark` and `--awaiting-bar` once, and one that says nothing gets a
1552/// mark that is visible.
1553///
1554/// # The cadence, and what happens without it
1555///
1556/// `--cadence-activity` comes from `makeover-timing` through `makeover-build`,
1557/// and is a half-period, so a full cycle is twice it. It is used bare rather
1558/// than with a fallback: a number written here would be a second heartbeat for
1559/// a mark three renderers draw.
1560///
1561/// A sheet assembled without the time axis leaves `animation-duration` invalid,
1562/// which resolves to `0s`, which runs no animation and leaves the base style —
1563/// a lit, still mark. That is also exactly what the reduced-motion block does,
1564/// since it sets the cadence to `0ms`. Both fall out of one rule because the
1565/// base style is lit and the keyframes do the dimming, which is the ordering
1566/// `makeover_timing::reduced_motion_css` asks its consumers for by name.
1567fn awaiting_rules(opts: &Emit) -> String {
1568 let mut css = String::new();
1569
1570 // Dimming rather than lighting, so a zero-length animation leaves a lit
1571 // mark rather than a blank one. See `makeover_timing::reduced_motion_css`.
1572 css.push_str(
1573 "@keyframes makeover-activity {\n \
1574 0%, 49.99% {\n background: var(--action);\n }\n \
1575 50%, 100% {\n background: var(--surface-sunken);\n }\n\
1576 }\n",
1577 );
1578
1579 // Nothing is drawn until something is waiting. `content` on the base rule
1580 // rather than on the busy one keeps the box the same box across the
1581 // transition, so a mark appearing does not reflow the line it is in.
1582 let _ = writeln!(
1583 css,
1584 "[data-awaiting]::after {{\n \
1585 content: \"\";\n \
1586 display: none;\n \
1587 margin-inline-start: var(--awaiting-gap, 0.5ch);\n \
1588 vertical-align: baseline;\n\
1589 }}"
1590 );
1591
1592 let _ = writeln!(
1593 css,
1594 "[data-awaiting][aria-busy=\"true\"]::after {{\n \
1595 display: inline-block;\n \
1596 inline-size: var(--awaiting-mark, 0.5em);\n \
1597 block-size: var(--awaiting-mark, 0.5em);\n \
1598 background: var(--action);\n \
1599 opacity: 1;\n \
1600 animation: makeover-activity calc(var(--cadence-activity) * 2) \
1601 step-end infinite;\n\
1602 }}"
1603 );
1604
1605 // The measured half. A wider box, no blink, and a gradient whose stop is
1606 // the share: the fill and the trough in one paint, so the markup stays one
1607 // pseudo-element on both branches.
1608 //
1609 // `--awaiting-share` unset is an empty trough, not a full one. A bar that
1610 // read full because nobody was counting would be the confidently-wrong
1611 // drawing rule 1 exists to forbid.
1612 //
1613 // The trough takes an edge for the reason a well does: a bar at zero share
1614 // is otherwise a rectangle of the surface it sits on, which is nothing at
1615 // all. `border_width` rather than a literal, the way `depth_rule` and
1616 // `track_rules` write theirs.
1617 let _ = writeln!(
1618 css,
1619 "[data-awaiting=\"determinate\"][aria-busy=\"true\"]::after {{\n \
1620 inline-size: var(--awaiting-bar, 6em);\n \
1621 animation: none;\n \
1622 outline: {} solid var(--border);\n \
1623 outline-offset: -{};\n \
1624 background: linear-gradient(\n \
1625 to inline-end,\n \
1626 var(--action) 0 calc(var(--awaiting-share, 0) * 100%),\n \
1627 var(--surface-sunken) 0\n \
1628 );\n\
1629 }}",
1630 opts.border_width, opts.border_width
1631 );
1632
1633 css
1634}
1635
1636/// A strip of figures, and the two spans inside each one.
1637///
1638/// Colour only, which is the deferral rule applied to a component that badly
1639/// wants to break it. A figure reads as a figure because the value is set large
1640/// over a small caption, and that is a size: `makeover-geometry` answers how
1641/// much space and this crate answers what the thing is. Emitting `font-size`
1642/// here would be this crate naming a value, which is the one thing it is defined
1643/// by not doing, and `progress_rules` is the precedent — it emits the tones and
1644/// never the width, because the width is not its to know.
1645///
1646/// So the type scale is the app's, and what is generated is the part an app
1647/// cannot get right by itself: which of the two spans carries the tone, and,
1648/// from 0.82.0, the strip the figures sit in.
1649fn figure_rules(opts: &Emit) -> String {
1650 let figures = class("figures", opts);
1651 let figure = class("figure", opts);
1652 let value = class("figure-value", opts);
1653 let caption = class("figure-caption", opts);
1654 let change = class("figure-change", opts);
1655 let mut css = String::new();
1656
1657 // A strip of tiles that wraps rather than overflows, a section apart. It
1658 // was quasi-webview's arrangement sheet's to say, for a name this crate
1659 // emits.
1660 let _ = writeln!(
1661 css,
1662 ".{figures} {{\n display: flex;\n flex-wrap: wrap;\n gap: var(--gap-section);\n}}"
1663 );
1664
1665 // `content` literally. A figure's value is the thing itself, at full
1666 // weight -- wiki `three-tone-convention` classes it "active, emphasised",
1667 // and both other renderers already draw it that way (makeover-tui
1668 // `piece.rs:391` bold, makeover-immediate `widget.rs:244`). It reached
1669 // here through `Tone::Neutral.token()` and came out `content-muted`, so
1670 // the headline number sat at the colour of its own caption.
1671 let _ = writeln!(
1672 css,
1673 ".{figure} > .{value} {{\n color: var(--content);\n}}"
1674 );
1675 let _ = writeln!(
1676 css,
1677 ".{figure} > .{caption} {{\n color: var(--content-muted);\n}}"
1678 );
1679 let _ = writeln!(
1680 css,
1681 ".{figure} > .{change} {{\n color: var(--content-muted);\n}}"
1682 );
1683
1684 // A toned figure tones one part and never the caption. The caption is the
1685 // noun and stays muted.
1686 //
1687 // Which part depends on whether there is a change, and that is the whole of
1688 // what 0.13.0 changed here. A figure with a delta is an ordinary number that
1689 // has moved in a direction worth reading, so the delta takes the colour and
1690 // the number stays plain; a figure without one has nowhere else to put it.
1691 // `:has` is what lets one attribute mean both, and the alternative was the
1692 // emitter deciding by writing the attribute onto a different element, which
1693 // leaves two elements able to disagree about a figure's one meaning.
1694 for tone in [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger] {
1695 let _ = writeln!(
1696 css,
1697 ".{figure}[data-tone=\"{0}\"] > .{change} {{\n color: var(--{0});\n}}",
1698 tone.token()
1699 );
1700 let _ = writeln!(
1701 css,
1702 ".{figure}[data-tone=\"{0}\"]:not(:has(> .{change})) > .{value} \
1703 {{\n color: var(--{0});\n}}",
1704 tone.token()
1705 );
1706 }
1707 css
1708}
1709
1710/// A picture, its frame and its caption.
1711///
1712/// # The frame is a border, and this is the one place a bevel is wrong
1713///
1714/// Emitting [`Depth::Raised`] here through [`depth_rule`], the same call
1715/// `button` and `card` make, is wrong, and MNW's landing page is where it
1716/// showed: **the frames had no visible edge at all.**
1717///
1718/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow — a
1719/// 1px light run at the top-left and a dark one at the bottom-right, drawn
1720/// **inside** the element's box. On a button or a card that box is a surface
1721/// this crate owns, so an inset edge reads as the surface catching the light.
1722/// On a picture it is drawn on top of the picture, over whatever pixels the
1723/// image happens to have at its border. MNW's screenshots are light-on-light
1724/// parchment, so the light half landed on a light image and the frame
1725/// disappeared.
1726///
1727/// **You cannot bevel a surface you do not own.** A picture's content is the
1728/// app's, arrives at request time, and can be any colour, so its edge has to
1729/// sit *outside* the content rather than on it. That is a border.
1730///
1731/// The fill stays, and it is not decoration: it is what shows through a
1732/// transparent PNG and what stands in the frame's place while the image is
1733/// still loading.
1734///
1735/// This is a real limit on [`Depth`] rather than a special case. Every other
1736/// consumer of a depth draws its own surface; a picture is the first member
1737/// whose surface belongs to someone else.
1738///
1739/// # No size
1740///
1741/// `width: 100%` and nothing else. How large a picture is depends on the box it
1742/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
1743/// and a renderer that picked one would be answering for every consumer at
1744/// once. This is where `figure_rules` landed for the same reason.
1745fn picture_rules(opts: &Emit) -> String {
1746 let picture = class("picture", opts);
1747 let img = class("picture-img", opts);
1748 let caption = class("picture-caption", opts);
1749 let mut css = String::new();
1750
1751 // Block, or an inline image sits on the text baseline and carries a
1752 // descender's worth of space under it that no app ever wants and every app
1753 // deletes by hand. The border is the frame; see the type docs for why it is
1754 // not the bevel every other surface here gets.
1755 let _ = writeln!(
1756 css,
1757 ".{img} {{\n display: block;\n width: 100%;\n height: auto;\n \
1758 background: var(--{});\n border: {} solid var(--border);\n}}",
1759 Fill::Raised.token(),
1760 opts.border_width
1761 );
1762
1763 // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
1764 // so it is the bare rule above and needs nothing here.
1765 let _ = writeln!(
1766 css,
1767 ".{img}[data-fit=\"cover\"] {{\n height: 100%;\n object-fit: cover;\n}}"
1768 );
1769 let _ = writeln!(
1770 css,
1771 ".{img}[data-fit=\"contain\"] {{\n height: 100%;\n object-fit: contain;\n}}"
1772 );
1773
1774 // A caption reads back one step, which is `figure-caption`'s answer and the
1775 // same claim: it says what the thing above it is, and it is not the thing.
1776 let _ = writeln!(
1777 css,
1778 ".{picture} > .{caption} {{\n color: var(--content-muted);\n}}"
1779 );
1780
1781 css
1782}
1783
1784/// A region showing one child at a time, and the chrome that moves between them.
1785///
1786/// [`makeover_layout::Showing`] lets a description say that a region holds
1787/// several children and shows some of them. A renderer derives its own chrome
1788/// from that, which is what stops every renderer growing a `match` on a widget
1789/// name; these are the rules the derived chrome needs.
1790///
1791/// # Why the default is every child, and the enhancement takes them away
1792///
1793/// The controls are a lie until something binds them. A prev button rendered
1794/// into a document with no script is a control that looks live and answers
1795/// nothing, and the reader it lies to is exactly the one who cannot see the
1796/// other children either — the collapsing and the moving are the same half.
1797///
1798/// So the rules run in the direction the enhancement does. Nothing here hides a
1799/// child and nothing here shows a control. Whatever binds the region sets
1800/// `data-ready` on it, and that is what collapses the stack to one and reveals
1801/// the row that moves it. A reader with no script gets every child in order and
1802/// no controls, which is more content rather than less, and a reader with
1803/// script gets a settled page rather than a stack that jumps to one frame after
1804/// load.
1805///
1806/// MNW proved this shape by hand — a `<noscript>` stylesheet opening its
1807/// carousel back out — and it is here rather than there because the property is
1808/// the description's, not one app's.
1809///
1810/// # Not spacing
1811///
1812/// The row's gaps are `makeover-geometry`'s question and are absent for
1813/// [`row_rules`]'s reason. What is here is `display`, which carries no
1814/// magnitude, and the muted readout, which is the same claim `picture-caption`
1815/// makes: it says where you are among the children and it is not one of them.
1816fn showing_rules(opts: &Emit) -> String {
1817 let controls = class("showing", opts);
1818 let position = class("showing-position", opts);
1819 let frame = class("showing-frame", opts);
1820 let mut css = String::new();
1821
1822 // Hidden until something binds it, which is the whole argument above.
1823 let _ = writeln!(css, ".{controls} {{\n display: none;\n}}");
1824 // Block, and nothing about how the three sit in it. A button and a span are
1825 // inline already, so they make a row without this crate saying so, and
1826 // saying so is where `align-items` and a gap would follow -- both spacing,
1827 // both `makeover-geometry`'s, and `row_rules` refuses them for the same
1828 // reason.
1829 let _ = writeln!(
1830 css,
1831 "[data-ready] > .{controls} {{\n display: block;\n}}"
1832 );
1833
1834 // A child is in flow until the region is bound, and then only the current
1835 // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
1836 // are: one name for the state, set by whoever knows it.
1837 let _ = writeln!(
1838 css,
1839 "[data-ready] > .{frame}:not(.current) {{\n display: none;\n}}"
1840 );
1841
1842 // Reads back one step. `picture-caption`'s rule and its reason.
1843 let _ = writeln!(css, ".{position} {{\n color: var(--content-muted);\n}}");
1844
1845 css
1846}
1847
1848/// A time axis: the container, its gridlines and ruler, and the placed things.
1849///
1850/// [`Track`](makeover_layout::Track), the one member here whose whole point is
1851/// *position*. That makes the magnitude line this crate keeps worth restating
1852/// rather than assuming.
1853///
1854/// # Where the numbers come from
1855///
1856/// Every value that varies per item is a custom property the caller sets
1857/// inline, and every rule here reads one. `--track-at` and `--track-for` are
1858/// percentages of the span, which
1859/// [`Track::fraction`](makeover_layout::Track::fraction) computes once so three
1860/// renderers cannot disagree about it. Nothing here knows a pixel.
1861///
1862/// That is what lets the stylesheet stay static while the items move: an entry
1863/// carries `style="--track-at: 37.5%; --track-for: 4.166%"` and the rule below
1864/// turns it into a box. The alternative was emitting a rule per item, which is
1865/// a stylesheet that grows with the data.
1866///
1867/// **The height of the track is the app's**, not this crate's. 96 quarter-hour
1868/// slots at some slot height is a size, and a size is `makeover-geometry`'s
1869/// question -- the same refusal `figure_rules` and `placeholder_rules` make.
1870/// Percentages need a resolved height above them, so `.track` gets
1871/// `position: relative` and nothing else; the app says how tall a day is.
1872///
1873/// # Overlap
1874///
1875/// Two things at the same time is intrinsic to an axis and has no analogue in a
1876/// list. The description does not declare it -- `Placement::overlaps` derives it
1877/// from the times -- so what arrives here is a lane index and a lane count, and
1878/// the rule divides the width. A renderer that would rather stack them ignores
1879/// both properties and the defaults give it one full-width lane.
1880fn track_rules(opts: &Emit) -> String {
1881 let track = class("track", opts);
1882 let slot = class("track-slot", opts);
1883 let tick = class("track-tick", opts);
1884 let entry = class("track-entry", opts);
1885 let mut css = String::new();
1886
1887 // The positioning context every entry resolves against, and the whole of
1888 // what this crate says about the container. No height: see the doc above.
1889 let _ = writeln!(css, ".{track} {{\n position: relative;\n}}");
1890
1891 // Gridlines and the ruler are the axis reading itself back, which is
1892 // `picture-caption` and `showing-position`'s claim: about the thing rather
1893 // than one of the things.
1894 //
1895 // `border_width` rather than a literal, the way `depth_rule` writes its
1896 // edge. A gridline is the one place a timeline would most naturally reach
1897 // for a hardcoded 1px, and a hardcoded 1px is this crate naming a size.
1898 let _ = writeln!(
1899 css,
1900 ".{slot} {{\n border-top: {} solid var(--border);\n}}",
1901 opts.border_width
1902 );
1903 let _ = writeln!(css, ".{tick} {{\n color: var(--content-muted);\n}}");
1904
1905 // The one rule that does real work. Top and height are the placement;
1906 // left and width are the lane. Both lane properties default so an entry
1907 // that names neither is full width, which is the common case and the one a
1908 // renderer gets for free.
1909 let _ = writeln!(
1910 css,
1911 ".{entry} {{\n \
1912 position: absolute;\n \
1913 top: var(--track-at, 0%);\n \
1914 height: var(--track-for, 100%);\n \
1915 left: calc(var(--track-lane, 0) / var(--track-lanes, 1) * 100%);\n \
1916 width: calc(100% / var(--track-lanes, 1));\n\
1917 }}"
1918 );
1919
1920 css
1921}
1922
1923/// A region's stand-in, and the header of a table that can be reordered.
1924///
1925/// Both are colour and affordance only, the same place `figure_rules` lands:
1926/// emitting a type scale is not this crate's. How much room
1927/// a stand-in gets is a size — goingson has the same one at three, as
1928/// `--compact`, `--dashboard` and `--padded` — and a size is
1929/// `makeover-geometry`'s question.
1930///
1931/// The caret is the one thing here that is neither colour nor affordance, and it
1932/// is a renderer's own expression rather than a value the description named:
1933/// `aria-sort` is what the table actually says, and this turns it into something
1934/// visible for everyone not using a screen reader. A terminal draws its own; an
1935/// immediate-mode painter draws its own.
1936fn state_rules(opts: &Emit) -> String {
1937 let placeholder = class("placeholder", opts);
1938 let text = class("placeholder-text", opts);
1939 let heading = class("table-heading", opts);
1940 let mut css = String::new();
1941
1942 let _ = writeln!(
1943 css,
1944 ".{placeholder} > .{text} {{\n color: var(--content-muted);\n}}"
1945 );
1946 // Only the failure is toned. An empty list is the normal state of a new
1947 // install, and `Readiness::tone` is what says so.
1948 let _ = writeln!(
1949 css,
1950 ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n color: var(--{0});\n}}",
1951 Tone::Danger.token()
1952 );
1953 // The way out stands a group apart from the sentence it answers. A gap
1954 // step rather than a size: how much room the stand-in gets is still the
1955 // app's.
1956 let _ = writeln!(
1957 css,
1958 ".{placeholder} > .{} {{\n margin-block-start: var(--gap-group);\n}}",
1959 class("placeholder-action", opts)
1960 );
1961
1962 // A header that reorders the table is a control, and the pointer is the
1963 // only part of saying so that is not the app's own type and spacing.
1964 let _ = writeln!(
1965 css,
1966 ".{heading}[data-sortable] {{\n cursor: pointer;\n}}"
1967 );
1968 // The caret carries its own leading space, the way `makeover-tui` and
1969 // `makeover-immediate` both write `" \u{25B2}"`. It used to be emitted bare,
1970 // and both apps that adopted the vocabulary had to put the gap back in their
1971 // own stylesheets on the same afternoon -- each having to work out first that
1972 // app CSS outranks this crate's cascade layer, so adding the space the
1973 // obvious way, as `content`, silently wins over the glyph and leaves the
1974 // heading with no caret at all. A consumer should not have to know that, and
1975 // with the space emitted here there is nothing left for one to add.
1976 //
1977 // Three states, three tones, on the convention in wiki
1978 // `three-tone-convention`. A column in force is `content`; a column offering
1979 // to reorder and not doing it now is `content-secondary`, because it still
1980 // answers a press; a column that is not sortable emits no caret at all and
1981 // takes nothing. The idle arm used to hide its glyph and reserve the box,
1982 // which cost a reflow-free press and said nothing. It draws now, and the
1983 // reservation stops being a thing to get right.
1984 //
1985 // The glyph is `Sort::glyph`, escaped rather than written: a CSS `content`
1986 // string cannot carry the character literally through this file's own
1987 // escaping, and spelling it here as well would put the third copy back that
1988 // `makeover-layout` 0.27.5 exists to remove.
1989 //
1990 // On the heading's `.cell-in`, so the caret sits beside the label inside
1991 // its padding rather than at the far edge of a column that grew.
1992 let cell_in = class("cell-in", opts);
1993 let _ = writeln!(
1994 css,
1995 ".{heading}[data-sortable] > .{cell_in}::after \
1996 {{\n content: \" {}\";\n color: var(--content-secondary);\n}}",
1997 css_escape(Sort::Ascending.glyph())
1998 );
1999 for direction in [Sort::Ascending, Sort::Descending] {
2000 let _ = writeln!(
2001 css,
2002 ".{heading}[aria-sort=\"{}\"] > .{cell_in}::after \
2003 {{\n content: \" {}\";\n color: var(--content);\n}}",
2004 direction.as_str(),
2005 css_escape(direction.glyph())
2006 );
2007 }
2008 css
2009}
2010
2011/// One declared `ch` of a column's floor, in `rem`.
2012///
2013/// A figure at a table's text size, 0.6em of seven eighths of the base, is
2014/// 0.525rem, and a floor that sized a date to exactly its ten figures ended it
2015/// in an ellipsis with the rest of the row to spare. Nine sixteenths keeps it
2016/// whole. `rem` rather than the CSS `ch` because a container condition resolves
2017/// a font-relative unit against a different font than the cell's.
2018const CH_REM: f32 = 0.5625;
2019
2020/// The frame a table sits in, and how it narrows.
2021///
2022/// # Nothing travels with the table
2023///
2024/// A table a description produced knows its columns at render time, so any rule
2025/// written per table would have to travel with the markup: a `<style>` element
2026/// beside it, which needs `style-src 'unsafe-inline'` and so blocks the MNW
2027/// server's standing plan to drop it, or the head, which a table swapped in by
2028/// htmx arrives without. So every rule here is written once, against classes a
2029/// cell carries.
2030///
2031/// # Flex rows, and priority as a shrink factor
2032///
2033/// Each row is a flex row and each column a flex item starting at its declared
2034/// floor, the `min-N` rung [`list::column_classes`] puts on it. The columns
2035/// line up across rows because every row's cells share one basis, grow and
2036/// shrink per column. When the table is short of room the browser takes the
2037/// shortfall in proportion to each column's shrink factor, and [`Priority`] is
2038/// that factor: optional columns give way first, secondary ones next, and an
2039/// essential column of a kind that cannot be cut short does not give way at all.
2040///
2041/// So a table narrows at the width its floors add up to, with no breakpoint and
2042/// no count of positions. That is the number `makeover-tui` counts in cells and
2043/// `makeover-immediate` budgets in points, which is what makes a description
2044/// drop a column at one declared width in every host.
2045///
2046/// A droppable column under its floor hides its contents, through a container
2047/// condition on the cell, so a column reads whole or blank and never as a
2048/// fragment. The condition cannot read a custom property, which is why the floor
2049/// is a class from a fixed ladder and the edges are written in per density.
2050fn table_rules(opts: &Emit) -> String {
2051 let table = class("table", opts);
2052 let head = class("table-head", opts);
2053 let row = class("table-row", opts);
2054 let heading = class("table-heading", opts);
2055 let cell = class("cell", opts);
2056 let mut css = String::new();
2057
2058 // The table model, wiki `table-model`: specimen C with D's header strip, as
2059 // Max picked it off rendered specimens. The table paints its own raised
2060 // ground inside a hairline frame, so the row tones hold whatever it sits
2061 // on. Text is the note size, 14px at the default base.
2062 let bw = opts.border_width;
2063 let cell_in = class("cell-in", opts);
2064 let _ = writeln!(
2065 css,
2066 ".{table} {{\n border: {bw} solid var(--row-rule);\n \
2067 background: var(--surface-raised);\n font-size: var(--text-note);\n}}"
2068 );
2069 // Flex rows, so priority can be a shrink factor and the browser narrows the
2070 // table itself: see "A table narrows itself" below. Every row's cells share
2071 // one basis, grow and shrink per column, which is what lines the columns up
2072 // across rows without a table layout doing it.
2073 let _ = writeln!(
2074 css,
2075 ".{table} .{head},\n.{table} .{row} {{\n display: flex;\n}}"
2076 );
2077 // A minimum rather than a height, since a row grows to fit its tallest
2078 // cell: a cell holding more than a line grows the row.
2079 let _ = writeln!(
2080 css,
2081 ".{table} .{row} {{\n min-height: var(--row-block);\n}}"
2082 );
2083
2084 // One column, heading or cell: a flex item that starts at its floor
2085 // (`.min-N` below), grows if it fills, and gives room up by what it is
2086 // worth. `min-width: 0` lets it reach nothing, and it clips, so the padding
2087 // on `.cell-in` never lingers as a gap once the column has closed.
2088 //
2089 // A size container, so a droppable column can ask whether it is under its
2090 // own floor and show nothing rather than a fragment. Type goes on
2091 // `.cell-in`, so a heading and the cells under it are one box apart from
2092 // what they hold.
2093 //
2094 // A declared `ch` is drawn as `CH_REM`, in `rem`, in the basis and in the
2095 // container condition both. The CSS `ch` would be read off the cell by the
2096 // basis and off another font by the condition, so a column would hide at
2097 // one width while being sized at another: measured, three columns went
2098 // blank at 520px with room for all of them.
2099 let _ = writeln!(
2100 css,
2101 ".{table} .{heading},\n.{table} .{cell} {{\n display: flex;\n \
2102 align-items: center;\n flex: 0 1 calc({}rem + 2 * var(--gap-group));\n \
2103 min-width: 0;\n overflow: hidden;\n container-type: inline-size;\n}}",
2104 8.0 * CH_REM
2105 );
2106 let _ = writeln!(
2107 css,
2108 ".{table} .{cell_in} {{\n flex: 1 1 auto;\n min-width: 0;\n \
2109 overflow: hidden;\n text-overflow: ellipsis;\n}}"
2110 );
2111
2112 // The header strip. Its ink goes on the heading row and is inherited,
2113 // because `state_rules` colours the sort caret on `.cell-in::after` and a
2114 // colour on the heading itself would override it. `content-secondary`
2115 // rather than muted: the strip separates the header now, so the label does
2116 // not have to stay quiet by being pale. The edge sits under the strip, as
2117 // in the specimen. The strip is on the row as well as on each heading, so a
2118 // table whose columns do not fill its width has no gap in it, and on each
2119 // heading so one that sticks while the rows scroll under it stays opaque.
2120 // Tracking is typography's to own and nothing in the family owns it yet, so
2121 // it is a property with the specimen's value behind it.
2122 let _ = writeln!(
2123 css,
2124 ".{table} .{head} {{\n color: var(--content-secondary);\n \
2125 background: var(--surface-sunken);\n}}"
2126 );
2127 let _ = writeln!(
2128 css,
2129 ".{table} .{heading} {{\n align-items: flex-end;\n \
2130 background: var(--surface-sunken);\n border-bottom: {bw} solid var(--bevel-dark);\n}}"
2131 );
2132 let _ = writeln!(
2133 css,
2134 ".{table} .{heading} > .{cell_in} {{\n padding: var(--gap-peer) var(--gap-group);\n \
2135 font-size: var(--text-fine);\n font-weight: bold;\n \
2136 letter-spacing: var(--table-heading-tracking, 0.06em);\n \
2137 text-transform: uppercase;\n text-align: start;\n white-space: nowrap;\n}}"
2138 );
2139
2140 // Rows: a hairline between rows, a stripe on alternate rows, and a hover,
2141 // at every row count. Between rows and not above the first, where the
2142 // header's edge already draws the line.
2143 let _ = writeln!(
2144 css,
2145 ".{table} .{row} > .{cell} > .{cell_in} {{\n padding: var(--gap-bound) var(--gap-group);\n}}"
2146 );
2147 let _ = writeln!(
2148 css,
2149 ".{table} .{row} + .{row} {{\n border-top: {bw} solid var(--row-rule);\n}}"
2150 );
2151 // Parity of rows, never position of columns: the stripe alternates by what
2152 // a row is, and `of .{row}` keeps a header row out of the count.
2153 let _ = writeln!(
2154 css,
2155 ".{table} .{row}:nth-child(even of .{row}) {{\n background: var(--row-stripe);\n}}"
2156 );
2157 let _ = writeln!(
2158 css,
2159 "@media (hover: hover) and (pointer: fine) {{\n \
2160 .{table} .{row}:hover {{\n background: var(--row-hover);\n }}\n}}"
2161 );
2162
2163 let [
2164 kind_identifier,
2165 kind_date,
2166 kind_number,
2167 kind_status,
2168 kind_actions,
2169 kind_code,
2170 ] = [
2171 "kind-identifier",
2172 "kind-date",
2173 "kind-number",
2174 "kind-status",
2175 "kind-actions",
2176 "kind-code",
2177 ]
2178 .map(|name| class(name, opts));
2179 // Column kinds, wiki `table-model`. The class is on the heading and on
2180 // every cell. A heading takes the column's alignment and nowrap, so it lines
2181 // up with what is under it, and keeps the header's own type: the face and
2182 // figures a kind sets go on its cells. Prose has no class and no rule.
2183 let _ = writeln!(
2184 css,
2185 ".{table} .{cell}.{kind_identifier} > .{cell_in} {{\n font-family: var(--font-mono);\n \
2186 font-size: var(--text-fine);\n overflow-wrap: anywhere;\n}}"
2187 );
2188 let _ = writeln!(
2189 css,
2190 ".{table} .{kind_date} > .{cell_in} {{\n white-space: nowrap;\n}}\n\
2191 .{table} .{cell}.{kind_date} > .{cell_in} {{\n font-variant-numeric: tabular-nums;\n}}"
2192 );
2193 let _ = writeln!(
2194 css,
2195 ".{table} .{kind_number} > .{cell_in} {{\n white-space: nowrap;\n text-align: end;\n}}\n\
2196 .{table} .{cell}.{kind_number} > .{cell_in} {{\n font-variant-numeric: tabular-nums;\n}}"
2197 );
2198 let _ = writeln!(
2199 css,
2200 ".{table} .{kind_status} > .{cell_in} {{\n white-space: nowrap;\n}}"
2201 );
2202 let _ = writeln!(
2203 css,
2204 ".{table} .{kind_actions} > .{cell_in} {{\n white-space: nowrap;\n text-align: end;\n}}"
2205 );
2206 let _ = writeln!(
2207 css,
2208 ".{table} .{cell}.{kind_code} > .{cell_in} {{\n font-family: var(--font-mono);\n \
2209 white-space: pre;\n}}"
2210 );
2211 // A table holding code is read as code: one row per source line, where a
2212 // stripe, a padded block and a 45px row each break the reading. So it
2213 // keeps the frame and the header and drops the record treatment. Keyed on
2214 // the kind being present, which the table's own markup already says.
2215 //
2216 // And it never clips a line. The code column is sized by what it holds,
2217 // takes no part in narrowing, and the table scrolls sideways instead: a
2218 // source line cut short is a different line.
2219 let code = format!(".{table}:has(.{kind_code})");
2220 let _ = writeln!(
2221 css,
2222 "{code} {{\n overflow-x: auto;\n}}\n\
2223 {code} .{head},\n{code} .{row} {{\n min-width: max-content;\n}}\n\
2224 {code} .{row} {{\n min-height: auto;\n align-items: baseline;\n}}\n\
2225 {code} .{row} + .{row} {{\n border-top: 0;\n}}\n\
2226 {code} .{row} > .{cell} > .{cell_in} {{\n padding-block: 0;\n}}\n\
2227 {code} .{cell}.{kind_code},\n{code} .{heading}.{kind_code} {{\n \
2228 flex: 1 0 auto;\n overflow: visible;\n container-type: normal;\n}}\n\
2229 {code} .{row}:nth-child(even of .{row}) {{\n background: none;\n}}"
2230 );
2231 let _ = writeln!(
2232 css,
2233 "@media (hover: hover) and (pointer: fine) {{\n \
2234 {code} .{row}:hover {{\n background: none;\n }}\n}}"
2235 );
2236 // A fill column takes the slack; a content or fixed one stays at its floor
2237 // and keeps its value on one line rather than being given less by wrapping.
2238 // Scoped under `.{table}` for the reason every rule here is: the model is
2239 // what a cell takes by being in a table, and `.table .cell` at (0,2,0)
2240 // would outrank a bare class.
2241 let _ = writeln!(
2242 css,
2243 ".{table} .{} {{\n flex-grow: 1;\n}}",
2244 class("cell-fill", opts)
2245 );
2246 let _ = writeln!(
2247 css,
2248 ".{table} .{} > .{cell_in},\n.{table} .{} > .{cell_in} {{\n white-space: nowrap;\n}}",
2249 class("cell-content", opts),
2250 class("cell-fixed", opts)
2251 );
2252
2253 // A table narrows itself. Priority is how much room a column gives up when
2254 // the table runs out of it: the browser takes the shortfall from optional
2255 // columns until they reach nothing, then from secondary ones, and an
2256 // essential column only gives up what a thousandth of the others would.
2257 // No breakpoint and nothing per table, so a described table narrows at the
2258 // width its own floors add up to, which is the number the terminal counts
2259 // in cells and the immediate-mode painter budgets in points.
2260 //
2261 // An essential column of a kind that cannot be cut short does not shrink at
2262 // all: a control, a figure, a date or a state truncated is wrong rather than
2263 // short. `ColumnKind::holds_minimum` names them, so the list is the
2264 // description's rather than this sheet's.
2265 let [drops_first, drops_next, keeps] =
2266 ["cell-drops-first", "cell-drops-next", "cell-keeps"].map(|name| class(name, opts));
2267 let _ = writeln!(
2268 css,
2269 ".{table} .{drops_first} {{\n flex-shrink: 1000000;\n}}\n\
2270 .{table} .{drops_next} {{\n flex-shrink: 1000;\n}}"
2271 );
2272 let holding: Vec<String> = [
2273 makeover_layout::ColumnKind::Text,
2274 makeover_layout::ColumnKind::Identifier,
2275 makeover_layout::ColumnKind::Date,
2276 makeover_layout::ColumnKind::Number,
2277 makeover_layout::ColumnKind::Code,
2278 makeover_layout::ColumnKind::Status,
2279 makeover_layout::ColumnKind::Actions,
2280 ]
2281 .into_iter()
2282 .filter(|kind| kind.holds_minimum())
2283 .filter_map(list::kind_class)
2284 .map(|name| format!(".{}", class(name, opts)))
2285 .collect();
2286 let _ = writeln!(
2287 css,
2288 ".{table} .{keeps}:is({}) {{\n flex-shrink: 0;\n}}",
2289 holding.join(", ")
2290 );
2291
2292 // The floors, as a ladder. `Column::floor` is even and at most
2293 // `MIN_CEILING`, so every floor a description can reach is one of these.
2294 let rungs = (2..=makeover_layout::MIN_CEILING).step_by(2);
2295 for n in rungs.clone() {
2296 let _ = writeln!(
2297 css,
2298 ".{table} .{} {{\n flex-basis: calc({}rem + 2 * var(--gap-group));\n}}",
2299 class(&format!("min-{n}"), opts),
2300 f32::from(n) * CH_REM
2301 );
2302 }
2303
2304 // Whole or blank, never a fragment. A droppable column that has lost more
2305 // than one gap of its floor shows nothing, and its blank then closes over
2306 // the width it held.
2307 //
2308 // Nothing means no height either. Hidden text still lays out, and in a
2309 // column narrowed toward nothing a fill cell's words wrap one to a line: a
2310 // two-sentence description stood a row nine lines tall at 420px (MNW's
2311 // membership tiers). So the blank also holds its block size at zero and
2312 // clips what it holds.
2313 //
2314 // Not `display: none`, which would say the same thing more shortly. Apps
2315 // set `display` on `.cell-in` for layouts of their own (MNW's feed stacks a
2316 // two-line name with it), app CSS outranks this layer, and such a rule would
2317 // quietly bring every dropped cell back; makeover-build's drift check
2318 // refuses the pairing for that reason. Nothing sets a block size here.
2319 //
2320 // One gap and not none. The shrink factors order the tiers only nearly: a
2321 // secondary column gives up a fraction of a pixel while the optional ones
2322 // close, and a condition at the floor itself blanked it the moment they
2323 // started (measured, at 520px). One gap is far more than that leak and no
2324 // more than the column's own end padding, so whatever it holds overflows
2325 // into padding it still has rather than being cut.
2326 //
2327 // A container condition cannot read a custom property, so the gap is
2328 // written in rather than taken from `--gap-group`: once for the pointer
2329 // gap, and again under the touch condition where the gap is wider.
2330 for density in [Density::Pointer, Density::Touch] {
2331 let step = Gap::Group.step_at(density).ratio();
2332 let edge = f32::from(step.numerator) / f32::from(step.denominator);
2333 let mut block = String::new();
2334 for n in rungs.clone() {
2335 let _ = writeln!(
2336 block,
2337 "@container (inline-size < {}rem) {{\n \
2338 .{table} :is(.{drops_first}, .{drops_next}).{} > .{cell_in} {{\n \
2339 visibility: hidden;\n max-block-size: 0;\n overflow: hidden;\n }}\n}}",
2340 f32::from(n) * CH_REM + edge,
2341 class(&format!("min-{n}"), opts)
2342 );
2343 }
2344 match density {
2345 Density::Pointer => css.push_str(&block),
2346 Density::Touch => css.push_str(&gated(Some(density.media_condition()), &block)),
2347 }
2348 }
2349
2350 // What is inside a cell, which the table side could not say until
2351 // makeover-layout 0.14.0. Every cell was one `.cell` and one content
2352 // colour, so a button in a cell was painted as text -- the drift
2353 // `RowPart::intent` has prevented for list rows since 0.2.0 and prevented
2354 // for nothing here.
2355 //
2356 // The colour goes on `.cell-value` rather than on `.cell`, and that
2357 // placement is the whole fix. On the container it would cascade into the
2358 // tokens and the controls sitting beside the text, which is the bug said
2359 // in one rule; on the part that is text, it reaches text and stops.
2360 for part in [
2361 CellPart::Value,
2362 CellPart::Tokens,
2363 CellPart::Actions,
2364 CellPart::Link,
2365 ] {
2366 // Two of the four inherit: a token carries its own tone and an action
2367 // is a control rather than text. A link is text, the title of its row,
2368 // so it takes its intent like a value does. Left to inherit, it took
2369 // nothing: the colour is on `.cell-value` rather than on `.cell`, and an
2370 // anchor with no colour of its own draws in the browser's link blue.
2371 //
2372 // Written as a skip-list rather than as a match on Value, so a member
2373 // added upstream gets its intent emitted rather than being silently
2374 // dropped. That is the same trade `part_class`'s fallback makes: land
2375 // plainly, never land as nothing.
2376 if !matches!(part, CellPart::Tokens | CellPart::Actions) {
2377 // The underline says "this goes somewhere" in running text. In a
2378 // table the row already says it, by being the thing that activates.
2379 let underline = if part == CellPart::Link {
2380 "\n text-decoration: none;"
2381 } else {
2382 ""
2383 };
2384 let _ = writeln!(
2385 css,
2386 ".{} {{\n color: var(--{});{underline}\n}}",
2387 class(cell_part_class(part), opts),
2388 part.intent()
2389 );
2390 }
2391 }
2392
2393 css
2394}
2395
2396/// The component layer: every named thing phase A emits.
2397///
2398/// No scrollbar track. It was on the phase A list and came off: eight lines of
2399/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
2400/// would want handed to it, so it stays with the apps.
2401#[must_use]
2402pub fn component_rules(opts: &Emit) -> String {
2403 let mut css = String::new();
2404 css.push_str(&surface_rules(opts));
2405 css.push_str(&link_rules(opts));
2406 css.push_str(&token_rules(opts));
2407 css.push_str(&selector_rules(opts));
2408 css.push_str(&row_rules(opts));
2409 css.push_str(&run_rules(opts));
2410 css.push_str(&progress_rules(opts));
2411 css.push_str(&chart::rules(opts));
2412 css.push_str(&awaiting_rules(opts));
2413 css.push_str(&figure_rules(opts));
2414 css.push_str(&picture_rules(opts));
2415 css.push_str(&showing_rules(opts));
2416 css.push_str(&track_rules(opts));
2417 css.push_str(&state_rules(opts));
2418 css.push_str(&table_rules(opts));
2419 css.push_str(&facet::facet_rules(opts));
2420 css.push_str(&form::group_rules(opts));
2421 css.push_str(&form::editor_rules(opts));
2422 css.push_str(&form::suggestion_rules(opts));
2423 css.push_str(&form::unit_rules(opts));
2424 css.push_str(&form::option_detail_rules(opts));
2425 css.push_str(&form::note_rules(opts));
2426 css.push_str(&leaving_rules());
2427 css
2428}
2429
2430/// How a transient notice goes away.
2431///
2432/// `makeover-timing` says that `Intent::Dismiss` is how long a notice lives
2433/// *before it starts to leave*, and that the leaving itself is `Motion::Fade`.
2434/// `makeover-build` writes `--motion-fade` into every consumer's `timing.css`,
2435/// and this is the rule that reads it. Removing the node the moment the dismiss
2436/// is up skips the leaving entirely.
2437///
2438/// # Why an attribute and not a class
2439///
2440/// [`Emit`]'s prefix moves every class this crate writes, so a class here would
2441/// have to be resolved through `class()` by whoever sets it -- and the party
2442/// setting it is a script, which has no prefix to hand. `data-leaving` is
2443/// outside that namespace, so a renderer can set it from JavaScript with no
2444/// coordination.
2445///
2446/// The transition sits on the notice and the opacity on the leaving state, so
2447/// the element is transitionable before the attribute arrives; a transition
2448/// declared in the same rule as the value it changes has nothing to animate
2449/// from.
2450///
2451/// # Reduced motion is handled by the token, not by a second rule here
2452///
2453/// `timing.css` already zeroes `--motion-fade` under `prefers-reduced-motion`.
2454/// The reader who asked for less motion gets an instant change rather than a
2455/// fade, and the renderer that sets the attribute must still remove the node on
2456/// a timer rather than on `transitionend` -- a zero-length transition may fire
2457/// no event at all, and a node waiting on one that never comes stays forever.
2458///
2459/// The fallback is `0ms` and not a guessed duration: a page with no timing
2460/// sheet has not opted into this vocabulary, and the honest answer there is the
2461/// behaviour it had before, which is the notice going away at once.
2462fn leaving_rules() -> String {
2463 let mut css = String::new();
2464 let _ = writeln!(
2465 css,
2466 "[data-notice] {{\n transition: opacity var(--motion-fade, 0ms) \
2467 ease-out;\n}}"
2468 );
2469 let _ = writeln!(css, "[data-notice][data-leaving] {{\n opacity: 0;\n}}");
2470 css
2471}
2472
2473/// The whole phase-A stylesheet: properties, depth rules and components, in
2474/// [`CSS_LAYER`], under a generated-file banner.
2475///
2476/// The banner sits outside the layer, because a comment participates in no
2477/// cascade and a reader opening the file should see what it is before seeing
2478/// an at-rule.
2479#[must_use]
2480pub fn stylesheet(opts: &Emit) -> String {
2481 let body = in_css_layer(&format!(
2482 ":root {{\n{}}}\n\n{}\n{}",
2483 bevel_properties(opts),
2484 depth_rules(opts),
2485 component_rules(opts)
2486 ));
2487 // Counted from the body rather than through `vocabulary::names`, which
2488 // calls back into here.
2489 let classes = vocabulary::classes_in_css(&body).len();
2490 let version = VERSION;
2491 format!(
2492 "/* Generated by makeover-webview {version} from makeover-layout, \
2493 {classes} classes.\n \
2494 Do not edit. The version and the count are here because a stale\n \
2495 lockfile fails silently: an older emitter writes a well-formed sheet\n \
2496 with components missing, and nothing else in the file says so. If\n \
2497 this version trails what the manifest asks for, re-resolve.\n\n \
2498 Depth is a fill and an edge together; naming them apart is what let\n \
2499 them disagree. See the crate's README and wiki note makeover-layout.\n\n \
2500 Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n \
2501 order once in your own stylesheet, or this layer's position is decided\n \
2502 by whichever generated file the browser happens to see first:\n\n \
2503 @layer {CSS_LAYER}, base, components, responsive; */\n{body}"
2504 )
2505}
2506
2507#[cfg(test)]
2508mod tests;