makeover-webview 0.130.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser. With the build feature, writes a consumer's generated frontend files and checks the hand-written ones against them.
Documentation
//! Which generated classes a bare element selector reaches, and the classes
//! a selector names or matches.

use super::{selector_arms, vocabulary};
use crate::Emit;
use crate::css_lex::{is_ident, matching_close, top_level};
use std::collections::BTreeSet;

/// Which generated classes each element can plausibly carry.
///
/// Declared, not inferred: no stylesheet says that a chip is rendered as a
/// `<button>`. [`declarations_by_element`](super::declarations_by_element)
/// supplies the other half of the element check.
///
/// Read it as "may carry", not "does carry": the list errs toward including a
/// pairing.
///
/// `div` and `span` are absent, so a bare `div { }` or `span { }` rule is not
/// checked.
pub const ELEMENT_CLASSES: &[(&str, &[&str])] = &[
    // The controls. `a` and `button` are interchangeable in markup for most of
    // these, a link that posts is a button, an act that navigates is an
    // anchor, which is why the two lists overlap as much as they do.
    (
        "a",
        &[
            "link",
            "button",
            "tab",
            "chip",
            "badge",
            "card",
            "row-activate",
            "figure-act",
            "chrome-place",
            "facet-take",
            "facet-prune",
            "facet-join-word",
        ],
    ),
    (
        "button",
        &[
            "button",
            "chip",
            "segment",
            "toggle",
            "tab",
            "link",
            "badge",
            "card",
            "facet-take",
            "facet-prune",
            "facet-join-word",
            "chip-remove",
            "row-activate",
        ],
    ),
    // A disclosure. quasi-webview renders an ask as `<details>` with a
    // `<summary>` that is styled as an act.
    ("details", &["ask"]),
    ("summary", &["button", "ask-open", "ask-body"]),
    // The form controls. `.field` is the well every one of them sits in.
    ("input", &["field", "toggle", "row-select"]),
    ("select", &["field"]),
    ("textarea", &["field"]),
    (
        "label",
        &[
            "form-label",
            "form-checkbox-label",
            "form-radio-label",
            "toggle",
            // A card wrapping a choice, which is how a tier picker is pressed.
            "card",
        ],
    ),
    ("form", &["form"]),
    ("progress", &["progress"]),
    // Text and lists.
    ("p", &["text", "facet-name", "placeholder-text"]),
    ("ul", &["list", "facet-values"]),
    ("ol", &["list"]),
    ("li", &["facet-value"]),
    // A table written in HTML rather than described. quasi-webview renders a
    // described table as divs carrying the same classes, so both spellings of
    // the same table answer to the same rules and both are worth checking.
    ("table", &["table"]),
    ("thead", &["table-head"]),
    ("tr", &["table-row"]),
    ("td", &["cell", "cell-value", "cell-content"]),
    ("th", &["table-heading"]),
    // A figure, likewise: the described picture is divs, the hand-written one
    // is the HTML element that means the same thing.
    ("figure", &["picture", "figure"]),
    ("img", &["picture-img"]),
    ("figcaption", &["picture-caption", "figure-caption"]),
    ("nav", &["chrome-nav"]),
];

/// The generated classes `element` can carry, prefixed the way `opts` prefixes
/// them.
///
/// Empty for an element the design system never renders onto.
#[must_use]
pub fn classes_for_element(element: &str, opts: &Emit) -> BTreeSet<String> {
    if element == UNIVERSAL {
        return vocabulary(opts);
    }
    ELEMENT_CLASSES
        .iter()
        .find(|(name, _)| *name == element)
        .map(|(_, classes)| classes.iter().map(|c| crate::class(c, opts)).collect())
        .unwrap_or_default()
}

/// The element key [`declarations_by_element`](super::declarations_by_element) files a bare `*` rule under.
///
/// [`classes_for_element`] answers it with the whole vocabulary:
/// `* { padding: 0 }` in a layer after `makeover` reaches every generated
/// padding.
pub const UNIVERSAL: &str = "*";

/// The element name of one bare compound arm, if that is what it is.
pub(super) fn bare_element(arm: &str) -> Option<String> {
    // An attribute value or a `:not()` argument can hold anything, including
    // the spaces and dots this then rejects on. Neither changes which element
    // the arm styles, so both go before the test rather than into it.
    let mut flat = String::with_capacity(arm.len());
    let mut depth = 0usize;
    for c in arm.chars() {
        match c {
            '[' | '(' => depth += 1,
            ']' | ')' => depth = depth.saturating_sub(1),
            _ if depth == 0 => flat.push(c),
            _ => {}
        }
    }
    let flat = flat.trim();
    // A lone universal, bare or under a state (`*`, `*:hover`), reaches every
    // element, so it reaches every described one. `*::before` styles a
    // generated box rather than an element, and `* button` is scoped.
    if let Some(rest) = flat.strip_prefix('*') {
        let bare = !rest.contains(['.', '#', '>', '+', '~', '*'])
            && !rest.chars().any(char::is_whitespace)
            && !rest.contains("::");
        return bare.then(|| UNIVERSAL.to_string());
    }
    // A descendant, a child, a class, an id or a scoped universal: not this.
    if flat.is_empty() || flat.contains(['.', '#', '>', '+', '~', '*']) {
        return None;
    }
    if flat.chars().any(char::is_whitespace) {
        return None;
    }
    let name: String = flat
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '-')
        .collect();
    // A pseudo-element on nothing (`::selection`) or a pseudo-class on nothing
    // (`:root`) names no element.
    if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
        return None;
    }
    Some(name.to_ascii_lowercase())
}

/// The class names one selector matches on.
pub(super) fn classes_in_selector(selector: &str) -> Vec<String> {
    let chars: Vec<char> = selector.chars().collect();
    let mut names = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        // A leading digit is a length (`.5rem`), never a class: CSS forbids an
        // identifier starting with one.
        if chars[i] == '.'
            && chars
                .get(i + 1)
                .is_some_and(|c| c.is_alphabetic() || *c == '_')
        {
            let start = i + 1;
            let mut end = start;
            while end < chars.len() && is_ident(chars[end]) {
                end += 1;
            }
            names.push(chars[start..end].iter().collect());
            i = end;
        } else {
            i += 1;
        }
    }
    names
}

/// The class names a rule styles an element *by*: every class in the subject
/// of each selector arm, outside a `:not()` or a `:has()`.
///
/// Unlike [`classes_in_selector`], which reads every class a selector
/// mentions, this reads only the compound the selector ends at:
///
/// - An ancestor is context: `.table-row > .kind-actions { min-inline-size }`
///   styles the cell, not the row.
/// - A `:has()` is a condition on what the element holds: `.row:has(.button)`
///   styles the row.
/// - A negation's argument names the elements a rule refuses:
///   `.group:not(.raised) { box-shadow }` never reaches a raised element.
///
/// `:is()` and `:where()` in the subject match by their arguments, so a class
/// inside one stays counted.
///
/// An arm ending in a pseudo-element reaches no element:
/// `.field::file-selector-button` styles the button box a file input draws,
/// not the input carrying `.field`. Such an arm contributes no class, and the
/// other arms of the same list still do. Only the `::` spelling is read.
pub(super) fn classes_matched_by(selector: &str) -> Vec<String> {
    let subjects: Vec<String> = selector_arms(selector)
        .into_iter()
        .filter(|arm| !arm.contains("::"))
        .map(|arm| without_pseudo(&without_pseudo(subject_of(arm), ":not("), ":has("))
        .collect();
    classes_in_selector(&subjects.join(","))
}

/// The last compound of one selector arm: what follows the final combinator
/// outside any parentheses, brackets or quotes.
fn subject_of(arm: &str) -> &str {
    let arm = arm.trim();
    let start = top_level(arm)
        .filter(|&(_, c)| c.is_whitespace() || matches!(c, '>' | '+' | '~'))
        .last()
        .map_or(0, |(i, c)| i + c.len_utf8());
    &arm[start..]
}

/// `compound` with every `<pseudo>(...)` group taken out, balanced.
fn without_pseudo(compound: &str, pseudo: &str) -> String {
    let mut kept = String::with_capacity(compound.len());
    let mut rest = compound;
    while let Some(at) = rest.find(pseudo) {
        kept.push_str(&rest[..at]);
        let end = matching_close(rest.as_bytes(), at + pseudo.len() - 1, b'(', b')')
            .map_or(rest.len(), |k| k + 1);
        rest = &rest[end..];
    }
    kept.push_str(rest);
    kept
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_subject_is_what_follows_the_last_combinator() {
        assert_eq!(subject_of(".a > .b"), ".b");
        assert_eq!(subject_of(">.b"), ".b");
        assert_eq!(subject_of("~.b"), ".b");
        assert_eq!(subject_of(".b"), ".b");
    }
}