Skip to main content

makeover_webview/
lib.rs

1//! The webview renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-webview -->
4//!
5//! This crate takes no `Palette`. It emits CSS that names intents
6//! (`var(--surface-raised)`), and the browser resolves them against whatever
7//! `themes.js` last wrote onto `:root`.
8//!
9//! # The stylesheet
10//!
11//! [`stylesheet`] writes the component CSS. Part of what it emits is the
12//! withdrawal of user-agent chrome: [`reset`] is where a primitive says which
13//! parts of its element's default look it does not take.
14//!
15//! Pressed carries its fill: [`interactive_rules`] emits [`Depth::pressed`]
16//! whole, so a control presses to `--surface-well` and hovers to
17//! `--hover-surface`. A badge is flat (`token_rules`). No class prefix ships
18//! by default.
19//!
20//! # The markup's names
21//!
22//! The vocabulary's members (fields, choices, columns, figures, meters, charts,
23//! acts and the rest) are drawn by the quasi hosts: `quasi-webview` for this
24//! renderer. This crate keeps what those hosts and hand-written apps share
25//! with it:
26//!
27//! - [`form`]: the escaper, [`form::Markup`] and [`form::Filling`], the field
28//!   classes and the rules behind them. One function covers element text and
29//!   attribute values.
30//! - [`list`]: column names as classes, the kind, part and flow classes, the
31//!   cell wrapper and sizer, and the `short-N` and `stacks-N` ladders a table
32//!   narrows and stacks by.
33//! - [`chart`], [`figure`], [`meter`]: class lists and rules only.
34//! - [`facet`] renders `makeover_layout::Facet` itself: a dimension a set is
35//!   narrowed by, where one gesture both selects a value and moves the browse
36//!   position.
37//! - [`placeholder`] draws the stand-in a region shows while it has nothing.
38//!
39//! The table rules (`table_rules`) are private and reach a consumer only
40//! through [`stylesheet`]. Every class a host's markup can carry is in one of
41//! the modules' class lists, and [`vocabulary::names`] is their union with the
42//! generated sheet.
43//!
44//! # Interaction states
45//!
46//! [`interactive_rules`] emits four states, in emission order, and the order is
47//! load-bearing: they are all specificity (0,2,0), so disabled beats hover by
48//! coming last. No rule uses `:not(:disabled)`.
49//!
50//! Hover sits inside a capability query: `makeover-layout`'s `Affordance`
51//! answers whether the pointer has hover and `makeover-geometry` spells the
52//! condition.
53//!
54//! # The layer contract
55//!
56//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`],
57//! defined in `makeover-geometry`). `makeover-geometry` layers the density and
58//! size-class blocks of `geometry.css` the same way; the compactness block
59//! that closes that file is unlayered.
60//!
61//! The cascade resolves origin and importance, then layer, then specificity,
62//! then source order, and **unlayered normal declarations outrank every named
63//! layer**. An app declares the order once, or the layer's position is decided
64//! by whichever generated file the browser sees first:
65//!
66//! ```css
67//! @layer makeover, base, components, responsive;
68//! ```
69//!
70//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
71//! from this crate's pieces, so the rules it generates from them land in the
72//! same layer.
73//!
74//! # Form rules
75//!
76//! The field markup is the hosts' and the look is this crate's. A few rules
77//! key on a mark the markup carries rather than a class:
78//!
79//! - A markdown field is marked `data-format="markdown"`, and
80//!   `form::editor_rules` keys on that mark. The Write/Preview pair is a
81//!   segmented control, taking the depth, the focus ring and the chosen state
82//!   from the existing rules; the preview pane is a well. **This crate renders
83//!   no markdown**: the pane is filled by whatever binds the editor.
84//! - A suggestion's second line, `.form-suggestion-detail`, is drawn in
85//!   `--content-muted` rather than in the disabled token, as are
86//!   `.form-option-detail` and `.form-unit`.
87//! - An unavailable option's reason is `.form-option-reason`, and a group with
88//!   an error carries `has-error` while its message carries `visible`
89//!   ([`form::FIELD_STATE_CLASSES`]).
90//!
91//! # A cell says what it holds
92//!
93//! [`CellPart`](makeover_layout::CellPart) names the four things a cell holds,
94//! and `table_rules` turns them into `.cell-value`, `.cell-tokens`,
95//! `.cell-actions` and `.cell-link`. The value and the link take a colour; a
96//! token carries its own tone and an action is a control. The colour goes on
97//! `.cell-value`, not on `.cell`, so it does not cascade into a control in the
98//! cell.
99//!
100//! # A table narrows itself
101//!
102//! No rule is written per table. `table_rules` lays every table out as flex
103//! rows, each column starting at its declared floor and giving up room by its
104//! [`Priority`](makeover_layout::Priority), so the browser narrows a table at
105//! the width its floors add up to. A host puts the column's classes on every
106//! cell (its name through [`list::push_column_name`], its width and drop tiers
107//! from [`list::CELL_WIDTH_CLASSES`] and [`list::CELL_DROP_CLASSES`], its kind
108//! from [`list::kind_class`]), and every cell's contents go in
109//! [`list::CELL_IN`]. **A header row emitted by a renderer's own code has to do
110//! both too**, or the header and the body disagree about which column just
111//! closed and how wide the rest are.
112//!
113//! `.button` takes the four tones off `data-tone` as a background tint
114//! (`--{tone}-surface`) and, unlike the badge, no edge colour. A list is reset
115//! rather than left bulleted. A row's actions are never hidden until hover.
116//!
117//! # The depth classes are not controls
118//!
119//! `.raised` states a shape and carries no interactive set. `.button` is the
120//! same depth and a control, and takes its states from `surface_rules`.
121//! `.card` is a raised object that answers a pointer only when the element it
122//! is written on is a control: `a`, `button`, `label`, or anything carrying
123//! `data-act`.
124//!
125//! # A theme with no well
126//!
127//! Each renderer answers a theme with no `surface-well` its own way:
128//!
129//! - `makeover-immediate` substitutes nothing: its `Palette::from_theme` fails
130//!   with `MissingToken`.
131//! - `makeover-tui` draws an edge instead.
132//! - here, `var(--surface-well, var(--surface-page))` falls back in the
133//!   browser.
134
135#![forbid(unsafe_code)]
136
137#[macro_use]
138mod put;
139
140#[cfg(feature = "build")]
141pub mod build;
142pub mod chart;
143mod css_lex;
144pub mod facet;
145pub mod figure;
146pub mod form;
147pub mod list;
148pub mod meter;
149pub mod placeholder;
150pub mod reset;
151pub mod vocabulary;
152
153mod rows;
154mod states;
155mod surface;
156mod table;
157pub use rows::{RUN_CLASSES, STRIP_CONTAINER, STRIP_FOLD, fallback_class};
158use rows::{row_rules, run_rules};
159use states::{awaiting_rules, facts_rules, picture_rules, showing_rules, state_rules, track_rules};
160use surface::{link_rules, selector_rules, surface_rules, token_rules};
161use table::table_rules;
162
163use crate::reset::{Chrome, Reset};
164use makeover_geometry::{Density, SizeClass};
165// Re-exported rather than redefined. An app assembling its own stylesheet out
166// of this crate's pieces needs the same layer name, and most such apps depend
167// on this crate and not on `makeover-geometry` directly.
168pub use makeover_geometry::{CSS_LAYER, in_css_layer};
169
170/// This crate's version, as the generated stylesheet reports it.
171///
172/// [`stylesheet`] writes it into the sheet's banner.
173pub const VERSION: &str = env!("CARGO_PKG_VERSION");
174use makeover_layout::{Affordance, Bevel, Depth, Fill, Intent, Selector, State, Tone};
175
176/// How the emitted CSS and markup are shaped, and the copy they carry.
177///
178/// Built with [`Emit::new`] and its setters. `#[non_exhaustive]`, so a new
179/// knob is not a breaking change for anyone who configures one.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181#[non_exhaustive]
182pub struct Emit {
183    /// Bevel thickness, as a CSS length.
184    ///
185    /// The default is `makeover_geometry::Stroke::Hairline`, and
186    /// [`focus_width`](Self::focus_width)'s is `Stroke::Mark`; a test holds
187    /// both equal to the scale.
188    pub border_width: &'static str,
189    /// Focus ring thickness, as a CSS length.
190    ///
191    /// Independent of [`border_width`](Self::border_width). The default is
192    /// 2px.
193    pub focus_width: &'static str,
194    /// The smallest a target may be drawn, as a CSS length.
195    ///
196    /// The default reads `makeover_geometry`'s density-aware floor (24px under
197    /// a pointer, 44px under touch), falling back to WCAG 2.2's 24px where the
198    /// geometry layer is absent. An absolute length, not a step of the scale.
199    pub target_min: &'static str,
200    /// Prefix for emitted class names, without the leading dot.
201    pub class_prefix: &'static str,
202    /// What marks a compulsory field, appended to its label.
203    ///
204    /// The counterpart of `makeover-tui`'s `PieceStyle::required_marker` and
205    /// `makeover-immediate`'s `FieldStyle::required_marker`, with their
206    /// default. Like the other `*_label` fields, it is copy the caller may
207    /// replace.
208    ///
209    /// The marker is an `aria-hidden` span: the control carries `required`,
210    /// which a screen reader announces.
211    pub required_marker: &'static str,
212    /// The accessible name's lead on a facet value's exclude button, before
213    /// the value's own label: "Exclude Drums".
214    pub exclude_label: &'static str,
215    /// The markdown editor's two modes, as the segments say them.
216    pub write_label: &'static str,
217    /// See [`write_label`](Self::write_label).
218    pub preview_label: &'static str,
219    /// The accessible names of an interval's two boxes.
220    pub lower_label: &'static str,
221    /// See [`lower_label`](Self::lower_label).
222    pub upper_label: &'static str,
223    /// The words a facet group's join toggle offers: picks under it combine
224    /// when any of them holds, or only when all do.
225    pub any_label: &'static str,
226    /// See [`any_label`](Self::any_label).
227    pub all_label: &'static str,
228    /// The accessible name's lead on a join toggle, before the group's label:
229    /// "Combine picks under Genre".
230    pub join_label: &'static str,
231    /// What marks the group a newcomer should start with.
232    pub start_label: &'static str,
233    /// What a ranked group says when a pick inside it is already in force.
234    pub in_use_label: &'static str,
235    /// What a ranked group says when no pick inside it would leave anything.
236    pub dead_label: &'static str,
237}
238
239impl Emit {
240    /// The defaults: the measured widths above, no prefix, and English copy.
241    #[must_use]
242    pub const fn new() -> Self {
243        Self {
244            border_width: "1px",
245            focus_width: "2px",
246            target_min: "var(--target-least, 24px)",
247            class_prefix: "",
248            required_marker: "*",
249            exclude_label: "Exclude",
250            write_label: "Write",
251            preview_label: "Preview",
252            lower_label: "lower",
253            upper_label: "upper",
254            any_label: "any",
255            all_label: "all",
256            join_label: "Combine picks under",
257            start_label: "start here",
258            in_use_label: "in use",
259            dead_label: "no effect",
260        }
261    }
262}
263
264/// One setter per field, named after it, for building an [`Emit`] outside this
265/// crate: `Emit::new().class_prefix("mk-")`.
266macro_rules! setters {
267    ($($field:ident),* $(,)?) => {
268        impl Emit {
269            $(
270                #[doc = concat!("Set [`", stringify!($field), "`](Self::", stringify!($field), ").")]
271                #[must_use]
272                pub const fn $field(mut self, value: &'static str) -> Self {
273                    self.$field = value;
274                    self
275                }
276            )*
277        }
278    };
279}
280
281setters!(
282    border_width,
283    focus_width,
284    target_min,
285    class_prefix,
286    required_marker,
287    exclude_label,
288    write_label,
289    preview_label,
290    lower_label,
291    upper_label,
292    any_label,
293    all_label,
294    join_label,
295    start_label,
296    in_use_label,
297    dead_label,
298);
299
300impl Default for Emit {
301    fn default() -> Self {
302        Self::new()
303    }
304}
305
306/// A string as CSS escapes, for a `content` value.
307///
308/// `\u{25B2}` becomes `\25B2`, so the stylesheet is ASCII whatever the
309/// description spells.
310///
311/// The escape writes no trailing space, so every call site follows it with
312/// the closing quote: a CSS hex escape takes up to six digits and ends at the
313/// first character that cannot be one.
314fn css_escape(text: &str) -> String {
315    text.chars().fold(String::new(), |mut out, c| {
316        put!(out, "\\{:X}", c as u32);
317        out
318    })
319}
320
321/// The CSS custom property holding a bevel's composition.
322#[must_use]
323pub fn bevel_var(bevel: Bevel) -> &'static str {
324    match bevel {
325        Bevel::Raised => "--bevel-raised",
326        Bevel::Inset => "--bevel-inset",
327        Bevel::RaisedOpen => "--bevel-raised-open",
328        // An edge added to the description since this renderer was last
329        // built. The raised edge rather than no edge: a control with no
330        // box-shadow reads as flat, which is a different claim, where a
331        // closed edge is at worst the same shape drawn one run too many.
332        _ => "--bevel-raised",
333    }
334}
335
336/// A `var()` reference to a fill intent, with the browser's own fallback where
337/// the intent may be absent.
338///
339/// The fallback is CSS syntax, resolved by the browser.
340#[must_use]
341pub fn fill_var(fill: Fill) -> String {
342    match fill {
343        Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
344        other => format!("var(--{})", other.token()),
345    }
346}
347
348/// The two-tone edge as a `box-shadow` value.
349///
350/// Two inset shadows, one per corner pair: the light one offset down and
351/// right so it lands on the top and left edges, the dark one the other way.
352/// The same assignment `makeover-immediate` draws with polylines and
353/// `makeover-tui` draws with box-drawing characters.
354#[must_use]
355pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
356    let (top_left, bottom_right) = bevel.edges();
357    let w = opts.border_width;
358    // The shaded run's vertical offset is what puts it on the bottom edge. At
359    // zero it lands on the right edge alone, which is the open bevel: three
360    // sides drawn and the fourth left for the surface below to continue
361    // through. Same two shadows either way, so nothing downstream has to know
362    // which it got.
363    // The sign belongs to the value rather than to the template: writing
364    // `-{down}` against a zero emits `-0`, which is a length no stylesheet
365    // should carry even where a parser accepts it.
366    let down = if bevel.draws_bottom() {
367        format!("-{w}")
368    } else {
369        "0".to_string()
370    };
371    format!(
372        "inset {w} {w} 0 var(--{}), inset -{w} {down} 0 var(--{})",
373        top_left.token(),
374        bottom_right.token()
375    )
376}
377
378/// The custom properties the bevels and edges resolve through, as `:root`
379/// declarations: one per [`Bevel`] ([`bevel_var`]: raised, inset, raised
380/// open), the open bevel turned a quarter (`--bevel-raised-open-side`), the
381/// overlay cast (`--elevation-overlay`) and the control edge
382/// (`--edge-control`). A consumer that wants an edge without the fill reads the
383/// property directly.
384#[must_use]
385pub fn bevel_properties(opts: &Emit) -> String {
386    let mut css = String::new();
387    for bevel in [Bevel::Raised, Bevel::Inset, Bevel::RaisedOpen] {
388        putln!(
389            css,
390            "    {}: {};",
391            bevel_var(bevel),
392            bevel_shadow(bevel, opts)
393        );
394    }
395    putln!(css, "    {OPEN_SIDE_VAR}: {};", open_side_shadow(opts));
396    css.push_str(ELEVATION_PROPERTY);
397    // The edge a surface draws when its depth alone does not separate it: a
398    // field, a button, a card, a toast. One shorthand, so no rule spells out
399    // its own `1px solid`.
400    putln!(
401        css,
402        "    --edge-control: {} solid var(--border);",
403        opts.border_width
404    );
405    css
406}
407
408/// The property holding [`Bevel::RaisedOpen`] turned a quarter.
409///
410/// Which run of an open bevel is left off is the arrangement's, not the edge's:
411/// the run facing the surface the tab opens into. A strip across its pane
412/// opens downward, which is the composition under [`bevel_var`]; a strip
413/// running down beside its pane opens toward the inline end, and this is that.
414/// Not a member of [`Bevel`]: the renderer drawing the arrangement says which
415/// side.
416const OPEN_SIDE_VAR: &str = "--bevel-raised-open-side";
417
418/// [`bevel_shadow`] for a tab that joins its pane on the inline-end side.
419///
420/// The lit run stays on top and left, and the shaded run drops its horizontal
421/// offset instead of its vertical one, so it lands on the bottom alone and the
422/// right run is not drawn. Physical rather than logical sides, as every bevel
423/// here is: `box-shadow` has no logical form.
424fn open_side_shadow(opts: &Emit) -> String {
425    let (top_left, bottom_right) = Bevel::RaisedOpen.edges();
426    let w = opts.border_width;
427    format!(
428        "inset {w} {w} 0 var(--{}), inset 0 -{w} 0 var(--{})",
429        top_left.token(),
430        bottom_right.token()
431    )
432}
433
434/// The cast shadow of a surface that floats over the page.
435///
436/// `makeover` derives the tone (`--elevation`); this sets the geometry: a
437/// hard 3px offset down and to the right, with no blur.
438///
439/// **Only for a surface that overlays the page**: a menu, a toast, a popover,
440/// a dropdown. A surface *in* the page takes `.raised` and its bevel.
441const ELEVATION_PROPERTY: &str = "    --elevation-overlay: 3px 3px 0 var(--elevation);\n";
442
443/// The class name for a depth: `raised`, `well` or `sunken`, prefixed, and
444/// `None` for [`Depth::Flat`] and any depth this renderer does not know.
445///
446/// [`depth_rules`] writes no rule for `sunken`, and [`vocabulary::names`]
447/// does not list it: a host that emits the class for [`Depth::Sunken`] gets
448/// a class the stylesheet does not style.
449#[must_use]
450pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
451    let name = match depth {
452        Depth::Flat => return None,
453        Depth::Raised => "raised",
454        Depth::Well => "well",
455        Depth::Sunken => "sunken",
456        // A depth added to the description since this renderer was last
457        // built. No class, on the same footing as Flat: emitting a name
458        // whose rule body we cannot write would put a class in the markup
459        // that the stylesheet never defines.
460        _ => return None,
461    };
462    Some(format!("{}{name}", opts.class_prefix))
463}
464
465/// A prefixed class name.
466///
467/// For a renderer that emits markup this crate does not: a class it writes
468/// takes the same [`Emit::class_prefix`] the stylesheet does.
469#[must_use]
470pub fn class(name: &str, opts: &Emit) -> String {
471    let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
472    push_class(&mut out, name, opts);
473    out
474}
475
476/// A prefixed class name, written into a buffer the caller already has.
477///
478/// The form the emitters use. [`class`] returns a `String` instead.
479pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
480    out.push_str(opts.class_prefix);
481    out.push_str(name);
482}
483
484/// The attribute an element's custom properties ride in, instead of `style`.
485///
486/// A number this crate hands the stylesheet (a bar's value and its axis, a
487/// facet's depth, a meter's fill) is a custom property the rules divide or
488/// multiply. It rides in this attribute, and [`VARS_JS`] sets each property
489/// through the CSSOM, so a page under a `style-src` without
490/// `'unsafe-inline'` still draws it.
491///
492/// The value is `--name: value` pairs separated by `;`, the `style`
493/// attribute's declaration syntax. Only custom properties are applied.
494pub const VARS_ATTR: &str = "data-vars";
495
496/// The script that applies [`VARS_ATTR`], for a host to serve beside its other
497/// assets.
498///
499/// Without it every number the rules read from that attribute is missing: bars
500/// and charts flat, tree rows unindented, a split screen at even halves.
501///
502/// It also restores this device's density choice onto the root element
503/// ([`DENSITY_STORE_KEY`] into
504/// [`DENSITY_ATTRIBUTE`](makeover_geometry::DENSITY_ATTRIBUTE)) and answers a
505/// [`DENSITY_CHOICE_ATTR`] picker. Serve it as a classic script in the head,
506/// not deferred, so its observer is
507/// running before the parser reaches the body and the first paint already has
508/// every property.
509///
510/// ```no_run
511/// # fn main() -> std::io::Result<()> {
512/// std::fs::write("static/vars.js", makeover_webview::VARS_JS)?;
513/// # Ok(())
514/// # }
515/// ```
516pub const VARS_JS: &str = include_str!("vars.js");
517
518/// The attribute a [`FieldKind::Density`](makeover_layout::FieldKind::Density)
519/// picker carries, which is how [`VARS_JS`] finds it.
520///
521/// The picker is a `<select>` with this attribute and **no `name`**, so no
522/// form or htmx request ever submits it: the device holds the answer, and the
523/// script reads and writes it there.
524pub const DENSITY_CHOICE_ATTR: &str = "data-density-choice";
525
526/// The browser storage key a device's density choice is kept under.
527///
528/// The value is [`Density::attribute_value`](makeover_geometry::Density::attribute_value),
529/// and an absent key is "follow detection". Browser storage is per origin:
530/// per device for a hosted app, per app for a desktop one.
531pub const DENSITY_STORE_KEY: &str = "makeover-density";
532
533/// Write the options of a density picker, in
534/// [`DENSITY_CHOICES`](makeover_layout::DENSITY_CHOICES) order.
535///
536/// None is marked selected. The server cannot know what this device chose,
537/// so [`VARS_JS`] sets the picker's value from storage as it arrives, which
538/// is before first paint on a page load and on insertion after a swap.
539///
540/// ```
541/// let mut out = String::new();
542/// makeover_webview::density_options_into(&mut out);
543/// assert!(out.starts_with("<option value=\"\">Automatic</option>"));
544/// assert!(out.contains("<option value=\"touch\">Touch</option>"));
545/// ```
546pub fn density_options_into(out: &mut String) {
547    for (density, label) in makeover_layout::DENSITY_CHOICES {
548        out.push_str("<option value=\"");
549        out.push_str(density.map_or("", makeover_geometry::Density::attribute_value));
550        out.push_str("\">");
551        form::escape_into(label, out);
552        out.push_str("</option>");
553    }
554}
555
556/// The class an option of a selector carries, which is what the rules key off.
557///
558/// Named for the option and not for the group: `selector_rules` styles the
559/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`, and
560/// the class goes on each option, not on the wrapping element.
561///
562/// The chosen option additionally carries `chosen`, the same way a latched
563/// chip carries `latched`; `selector_rules` writes both.
564#[must_use]
565pub fn option_class(selector: Selector) -> &'static str {
566    match selector {
567        Selector::Tabs => "tab",
568        Selector::Segmented => "segment",
569        Selector::Toggle => "toggle",
570        // A selector this crate has not learned draws as tabs, the plainest
571        // of the three, rather than as nothing.
572        _ => "tab",
573    }
574}
575
576/// The fill and edge declarations for a depth, as a rule body.
577///
578/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
579/// Callers skip the rule when it is empty.
580///
581/// Each half is emitted when the depth has it, so [`Depth::Sunken`], which
582/// has a fill and no bevel, gets its fill. Both halves come off one `Depth`.
583#[must_use]
584pub fn depth_declarations(depth: Depth) -> String {
585    let mut css = String::new();
586    if let Some(fill) = depth.fill() {
587        putln!(css, "    background: {};", fill_var(fill));
588    }
589    if let Some(bevel) = depth.bevel() {
590        putln!(css, "    box-shadow: var({});", bevel_var(bevel));
591    }
592    css
593}
594
595/// One rule giving a selector a depth, or nothing when the depth declares
596/// nothing.
597#[must_use]
598pub fn depth_rule(selector: &str, depth: Depth) -> String {
599    let body = depth_declarations(depth);
600    if body.is_empty() {
601        return String::new();
602    }
603    format!(".{selector} {{\n{body}}}\n")
604}
605
606/// The media condition a hover rule has to sit inside, or `None` if hover is
607/// unconditional.
608///
609/// `makeover-layout`'s [`Affordance`] answers *whether* hover exists at a
610/// density, and `makeover-geometry` spells that capability as a media
611/// condition. This asks both.
612///
613/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
614/// member, which reports as much through `reads_size`. Passing Compact is not
615/// a claim about width; the test below pins that every class agrees.
616pub(crate) fn hover_condition() -> Option<&'static str> {
617    if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
618        // A fingertip grew a hover state. Nothing to gate, and this renderer
619        // should not invent a reason to gate anyway.
620        None
621    } else {
622        Some(Density::Pointer.media_condition())
623    }
624}
625
626/// The tones that carry a status, each of which a toned member draws.
627pub(crate) const STATUS_TONES: [Tone; 4] = [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger];
628
629/// The disabled state, native or announced, as one selector suffix.
630pub(crate) const DISABLED: &str = ":is(:disabled, [aria-disabled=\"true\"])";
631
632/// One `{selector}[data-tone="…"]` rule per status tone, `body` writing the
633/// declarations for a tone token.
634pub(crate) fn tone_rules(css: &mut String, selector: &str, body: impl Fn(&str) -> String) {
635    for tone in STATUS_TONES {
636        let tone = tone.token();
637        putln!(css, "{selector}[data-tone=\"{tone}\"] {{\n{}}}", body(tone));
638    }
639}
640
641/// A status drawn as an edge on the start side, the words keeping their ink.
642pub(crate) fn status_edge(width: &str, tone: &str) -> String {
643    format!(
644        "    border-inline-start: {width} solid var(--{tone});\n    \
645         padding-inline-start: var(--step-snug);\n"
646    )
647}
648
649/// A status drawn as a tinted ground edged in the tone.
650fn toned_surface(tone: &str) -> String {
651    format!("    background: var(--{tone}-surface);\n    border-color: var(--{tone});\n")
652}
653
654/// Put a rule inside a media query, or leave it alone.
655pub(crate) fn gated(condition: Option<&str>, rule: &str) -> String {
656    let Some(condition) = condition else {
657        return rule.to_string();
658    };
659    let mut css = format!("@media {condition} {{\n");
660    for line in rule.lines() {
661        // Blank lines stay blank. Indenting one leaves trailing whitespace,
662        // which is the sort of thing a formatter later reverts and calls a diff.
663        if line.is_empty() {
664            css.push('\n');
665        } else {
666            putln!(css, "    {line}");
667        }
668    }
669    css.push_str("}\n");
670    css
671}
672
673/// The keyboard focus ring, placed by the depth it lands on.
674///
675/// This is the webview's **focus ring** and nothing more. **Reach** and
676/// **focus** are both the browser's, the document decides what is reachable
677/// and `:focus-visible` decides which reached thing wears the ring, and no
678/// description states either. The three terms are defined once in
679/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
680///
681/// One ring for every component. Its placement comes off [`Depth`]: an
682/// `outline` of [`Emit::focus_width`] in `--focus-ring`, offset inward by
683/// that width on a well (an inset bevel) and outward by it on anything else.
684/// The outline leaves the element's `box-shadow` bevel untouched.
685///
686/// The invalid-field ring in `surface_rules` is built differently: a
687/// `box-shadow` of [`Emit::border_width`] composed after the bevel, flush with
688/// the element.
689#[must_use]
690pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
691    let w = opts.focus_width;
692    // Same magnitude either way, and only the sign comes off the depth. Both
693    // values are what the consumers had already converged on independently:
694    // 2px out is what all three wrote, and 2px in is the MNW server's own
695    // answer for the one inset ring it had.
696    let offset = match depth.bevel() {
697        // Inside the well, clear of its edge rather than painted over it.
698        Some(Bevel::Inset) => format!("calc(-1 * {w})"),
699        // Raised, or no edge at all. Outside, standing off by its own width.
700        _ => w.to_string(),
701    };
702    // The token by name. It is `makeover`'s, derived from the action colour,
703    // and reaching it through a description member was a second path to the
704    // same variable for as long as one existed.
705    format!(
706        ".{selector}:focus-visible {{\n    outline: {w} solid var(--focus-ring);\n    outline-offset: {offset};\n}}\n"
707    )
708}
709
710/// A rest depth said out loud on both axes, for a rule that has to beat the
711/// states above it.
712///
713/// [`depth_declarations`] states an axis only when the depth has something to
714/// say about it. This states both: an axis the depth is silent on is
715/// withdrawn, in the words [`reset`] spells, so a state above it does not
716/// keep that axis. [`Depth::Flat`] withdraws fill and edge;
717/// [`Depth::Sunken`] and [`Depth::Overlay`] withdraw the edge the pressed
718/// rule hands out.
719fn rest_declarations(depth: Depth) -> String {
720    let mut css = String::new();
721    match depth.fill() {
722        Some(fill) => {
723            putln!(css, "    background: {};", fill_var(fill));
724        }
725        None => css.push_str(&Reset::NOTHING.and(Chrome::Fill).declarations()),
726    }
727    match depth.bevel() {
728        Some(bevel) => {
729            putln!(css, "    box-shadow: var({});", bevel_var(bevel));
730        }
731        None => css.push_str(&Reset::NOTHING.and(Chrome::Shadow).declarations()),
732    }
733    css
734}
735
736/// Present, visible, and not answering.
737///
738/// Matches `[aria-disabled="true"]` as well as `:disabled`, since a `div`
739/// carrying `.chip` or `.tab` can never be `:disabled`.
740///
741/// The rest depth is re-asserted on both axes, through `rest_declarations`.
742/// The rule beats the hover and pressed rules on source order at equal
743/// specificity (0,2,0).
744#[must_use]
745pub fn disabled_rule(selector: &str, depth: Depth) -> String {
746    format!(
747        ".{selector}{DISABLED} {{\n{}    color: var(--{});\n    cursor: not-allowed;\n}}\n",
748        rest_declarations(depth),
749        State::Disabled.token()
750    )
751}
752
753/// Every state a selector that answers a click implies: hover, pressed, focus
754/// and disabled, in that order.
755///
756/// All four selectors are specificity (0,2,0), so disabled wins over hover
757/// and pressed by coming last.
758///
759/// Pressed emits [`Depth::pressed`] in full, fill and edge together, so the
760/// pressed fill comes from the description (`--surface-well`).
761///
762/// Hover has no member in the description and is renderer policy. It resolves
763/// against `--hover-surface` and is gated on capability, via
764/// `hover_condition`.
765///
766/// `depth` is the selector's **rest** depth, used to place the focus ring and
767/// to restore the surface under a disabled control. The pressed rule inverts
768/// from [`Depth::Raised`] whatever `depth` is, so a tab at rest
769/// [`Depth::Sunken`] still presses.
770#[must_use]
771pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
772    let mut css = gated(
773        hover_condition(),
774        &format!(".{selector}:hover {{\n    background: var(--hover-surface);\n}}\n"),
775    );
776    css.push_str(&depth_rule(
777        &format!("{selector}:active"),
778        Depth::Raised.pressed(),
779    ));
780    css.push_str(&focus_rule(selector, depth, opts));
781    css.push_str(&disabled_rule(selector, depth));
782    css
783}
784
785/// The compound a card's interactive states are written against: the class
786/// on an element that is itself a control.
787///
788/// `label` for a card wrapping a choice, `[data-act]` for an act a renderer
789/// drew on some other element. Without the class prefix, the way every
790/// selector handed to [`interactive_rules`] is.
791#[must_use]
792pub fn pressable_card(card: &str) -> String {
793    format!("{card}:is(a, button, label, [data-act])")
794}
795
796/// The depth classes' rules, fill and edge together: `.raised` and `.well`.
797/// [`depth_class`] also names `sunken`, which gets no rule here.
798///
799/// No hover, press, focus or disabled rule. `.button`, and `.card` written on
800/// a control, get their states from `surface_rules`.
801#[must_use]
802pub fn depth_rules(opts: &Emit) -> String {
803    let mut css = String::new();
804    for depth in [Depth::Raised, Depth::Well] {
805        let Some(class) = depth_class(depth, opts) else {
806            continue;
807        };
808        css.push_str(&depth_rule(&class, depth));
809    }
810    css
811}
812
813/// The component layer: the rules of every named component. No
814/// scrollbar rules.
815#[must_use]
816pub fn component_rules(opts: &Emit) -> String {
817    let mut css = String::new();
818    css.push_str(&surface_rules(opts));
819    css.push_str(&link_rules(opts));
820    css.push_str(&token_rules(opts));
821    css.push_str(&selector_rules(opts));
822    css.push_str(&row_rules(opts));
823    css.push_str(&run_rules(opts));
824    css.push_str(&meter::progress_rules(opts));
825    css.push_str(&chart::rules(opts));
826    css.push_str(&awaiting_rules(opts));
827    css.push_str(&figure::figure_rules(opts));
828    css.push_str(&facts_rules(opts));
829    css.push_str(&picture_rules(opts));
830    css.push_str(&showing_rules(opts));
831    css.push_str(&track_rules(opts));
832    css.push_str(&state_rules(opts));
833    css.push_str(&table_rules(opts));
834    css.push_str(&facet::facet_rules(opts));
835    css.push_str(&form::group_rules(opts));
836    css.push_str(&form::editor_rules(opts));
837    css.push_str(&form::suggestion_rules(opts));
838    css.push_str(&form::unit_rules(opts));
839    css.push_str(&form::option_detail_rules(opts));
840    css.push_str(&form::note_rules(opts));
841    css.push_str(&banner_rules(opts));
842    css.push_str(&toast_rules(opts));
843    css.push_str(&leaving_rules());
844    css
845}
846
847/// A notice that leaves on its own, floating over the page.
848///
849/// Its look is this crate's and where it floats is the host's: a toast takes
850/// [`Notice::Toast`]'s fill, the control edge, the overlay cast and the notice
851/// layer, and no position. A toned toast is the banner's answer: the tone's
852/// surface under the
853/// theme's own ink, edged in the tone.
854fn toast_rules(opts: &Emit) -> String {
855    let toast = class("toast", opts);
856    let mut css = String::new();
857    putln!(
858        css,
859        ".{toast} {{\n    background: var(--{});\n    color: var(--content);\n    \
860         border: var(--edge-control);\n    box-shadow: var(--elevation-overlay);\n    \
861         padding: var(--gap-peer) var(--gap-group);\n    z-index: var(--layer-notice);\n}}",
862        makeover_layout::Notice::Toast.fill().token()
863    );
864    tone_rules(&mut css, &format!(".{toast}"), toned_surface);
865    css
866}
867
868/// A notice that stays until dealt with, across whatever it is about.
869///
870/// A banner is left-aligned and its words stop at the reading measure while
871/// its ground keeps the width of the
872/// box it was put in. The words are a bare text node beside an optional act, so
873/// the measure is the far padding rather than a cap on a child: what is left of
874/// the box past the measure, or the ordinary inset once the box is narrower
875/// than that.
876///
877/// A status is the chip's answer: `*-surface` under the theme's own ink, edged
878/// in the tone. A status colour is never the colour of words.
879fn banner_rules(opts: &Emit) -> String {
880    let banner = class("banner", opts);
881    let mut css = String::new();
882    putln!(
883        css,
884        ".{banner} {{\n    padding-block: var(--gap-peer);\n    \
885         padding-inline-start: var(--gap-section);\n    \
886         padding-inline-end: max(var(--gap-section), 100% - var(--measure-reading, 42rem));\n    \
887         border-inline-start: {} solid var(--border);\n    \
888         color: var(--content);\n    text-align: start;\n}}",
889        opts.focus_width
890    );
891    tone_rules(&mut css, &format!(".{banner}"), |tone| {
892        format!(
893            "    background: var(--{tone}-surface);\n    border-inline-start-color: var(--{tone});\n"
894        )
895    });
896    css
897}
898
899/// How a transient notice goes away.
900///
901/// `makeover-timing` says that `Moment::Dismiss` is how long a notice lives
902/// *before it starts to leave*, and that the leaving itself is `Motion::Fade`.
903/// The `build` module writes `--motion-fade` into every consumer's
904/// `timing.css`, and this is the rule that reads it. A script sets
905/// `data-leaving` on the notice when its dismiss is up and removes the node
906/// once the fade has run.
907///
908/// The state is an attribute, outside [`Emit::class_prefix`]'s namespace, so
909/// a script sets it without a prefix. The transition sits on the notice and
910/// the opacity on the leaving state.
911///
912/// # Reduced motion
913///
914/// `timing.css` zeroes `--motion-fade` under `prefers-reduced-motion`. The
915/// renderer that sets the attribute must remove the node on a timer, not on
916/// `transitionend`: a zero-length transition may fire no event at all.
917///
918/// The fallback, with no timing sheet, is `0ms`.
919fn leaving_rules() -> String {
920    let mut css = String::new();
921    putln!(
922        css,
923        "[data-notice] {{\n    transition: opacity var(--motion-fade, 0ms) \
924         ease-out;\n}}"
925    );
926    putln!(css, "[data-notice][data-leaving] {{\n    opacity: 0;\n}}");
927    css
928}
929
930/// The ink a native control draws its tick, dot and fill in.
931///
932/// A checkbox, a radio, a range and a `<progress>` are drawn by the browser.
933/// `accent-color` is inherited, so one declaration on `:root` reaches every
934/// native control in the document, including ones no emitter here wrote.
935/// `--content`, not `--action`: the accent is reserved for the primary
936/// action. The browser picks the tick's own colour against that ink.
937const NATIVE_ACCENT: &str = "    accent-color: var(--content);\n";
938
939/// The whole phase-A stylesheet: properties, depth rules and components, in
940/// [`CSS_LAYER`], under a generated-file banner.
941///
942/// The banner sits outside the layer, at the top of the file.
943#[must_use]
944pub fn stylesheet(opts: &Emit) -> String {
945    let body = in_css_layer(&format!(
946        ":root {{\n{}{NATIVE_ACCENT}}}\n\n{}\n{}",
947        bevel_properties(opts),
948        depth_rules(opts),
949        component_rules(opts)
950    ));
951    // Counted from the body rather than through `vocabulary::names`, which
952    // calls back into here.
953    let classes = vocabulary::classes_in_css(&body).len();
954    let version = VERSION;
955    format!(
956        "/* Generated by makeover-webview {version} from makeover-layout, \
957         {classes} classes.\n   \
958         Do not edit. The version and the count are here because a stale\n   \
959         lockfile fails silently: an older emitter writes a well-formed sheet\n   \
960         with components missing, and nothing else in the file says so. If\n   \
961         this version trails what the manifest asks for, re-resolve.\n\n   \
962         Depth is a fill and an edge together; naming them apart is what let\n   \
963         them disagree. See the crate's README and wiki note makeover-layout.\n\n   \
964         Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n   \
965         order once in your own stylesheet, or this layer's position is decided\n   \
966         by whichever generated file the browser happens to see first:\n\n   \
967         @layer {CSS_LAYER}, base, components, responsive; */\n{body}"
968    )
969}
970
971#[cfg(test)]
972mod test_support;
973#[cfg(test)]
974mod tests;