Skip to main content

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