next-rust-view 0.1.11

The Next Rust view layer: an escaping-by-default HTML DSL, components, metadata and a streaming renderer.
Documentation
//! Short class names for production builds.
//!
//! Release builds of Tailwind projects rename every utility class to a short,
//! random name (`rounded-lg` → `k7`). The build renames the selectors in the
//! generated CSS and hands the renaming table to the app at startup; the
//! renderer then writes the short names wherever the original ones appear in
//! `class` attributes, in [`active_class`](crate::active_class) values, in
//! `data-nr-class-<name>` attributes and in `class="…"` inside raw HTML.

use std::borrow::Cow;
use std::sync::OnceLock;

/// `(original, short)` pairs, sorted by original name.
pub type ClassNames = &'static [(&'static str, &'static str)];

static CLASS_NAMES: OnceLock<ClassNames> = OnceLock::new();
static KNOWN_CLASSES: OnceLock<&'static [&'static str]> = OnceLock::new();

/// Install the renaming table. Called once by the server at startup; later
/// calls are ignored. An empty table leaves class names unchanged.
pub fn set_class_names(names: ClassNames) {
    if !names.is_empty() {
        debug_assert!(names.is_sorted_by(|a, b| a.0 < b.0), "class names must be sorted");
        let _ = CLASS_NAMES.set(names);
    }
}

/// Install the classes the build found a rule, a script or a static file
/// for (sorted). With it set, the renderer leaves out classes that look
/// generated (`sm:flexx`, `bg-[…]`, `w-1/3`) but are known to nothing: they
/// would style nothing. Called once by the server at startup.
pub fn set_known_classes(classes: &'static [&'static str]) {
    if !classes.is_empty() {
        debug_assert!(classes.is_sorted(), "known classes must be sorted");
        let _ = KNOWN_CLASSES.set(classes);
    }
}

/// Whether the renderer leaves `class` out: it looks generated by Tailwind
/// yet nothing knows it.
pub fn is_dropped(class: &str) -> bool {
    KNOWN_CLASSES.get().is_some_and(|known| looks_generated(class) && known.binary_search(&class).is_err())
}

/// Whether `class` has the shape of a generated Tailwind class: variants
/// (`sm:`, `aria-pressed:`, `[&_.x]:`) before a utility with an arbitrary
/// value (`bg-[…]`), a fraction (`w-1/2`) or `!`. Plain words (`hero`,
/// `g-recaptcha`), format strings, paths and CSS declarations are not.
pub fn looks_generated(class: &str) -> bool {
    let name = class.strip_prefix('!').unwrap_or(class);
    let special = name.contains([':', '[', '/']) || class.starts_with('!');
    if !special
        || !name.starts_with(|c: char| c.is_ascii_lowercase())
        || !name.contains(['-', ':'])
        || name.ends_with([':', '/', '-'])
        || name.contains("//")
        || name.as_bytes().windows(2).any(|w| w[0] == b'.' && w[1].is_ascii_alphabetic())
    {
        return false;
    }
    // Underscores stand for spaces inside brackets only; `(` only in brackets.
    let mut depth = 0i32;
    for c in name.chars() {
        match c {
            '[' => depth += 1,
            ']' => depth -= 1,
            '_' | '(' | ')' | ',' | '%' if depth == 0 => return false,
            c if c.is_ascii_alphanumeric() || "-_:/[]().%,#+".contains(c) => {}
            _ => return false,
        }
        if depth < 0 {
            return false;
        }
    }
    if depth != 0 {
        return false;
    }
    // Split at the colons outside brackets: variants, then the utility.
    let mut segments = Vec::new();
    let (mut depth, mut start) = (0, 0);
    for (i, c) in name.char_indices() {
        match c {
            '[' => depth += 1,
            ']' => depth -= 1,
            ':' if depth == 0 => {
                segments.push(&name[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    segments.push(&name[start..]);
    let Some((utility, variants)) = segments.split_last() else { return false };
    if utility.is_empty()
        || utility.starts_with(|c: char| c.is_ascii_digit() || c == '-')
        || variants.iter().any(|v| v.is_empty() || !v.starts_with(|c: char| c.is_ascii_lowercase() || c == '['))
    {
        return false;
    }
    // A fraction or an opacity: `/` before a digit or a bracket.
    let bytes = utility.as_bytes();
    bytes
        .iter()
        .enumerate()
        .all(|(i, b)| *b != b'/' || bytes.get(i + 1).is_some_and(|n| n.is_ascii_digit() || *n == b'['))
}

fn table() -> Option<ClassNames> {
    CLASS_NAMES.get().copied()
}

fn lookup(names: ClassNames, class: &str) -> Option<&'static str> {
    names.binary_search_by(|(original, _)| (*original).cmp(class)).ok().map(|i| names[i].1)
}

/// The short name of one class, if it has one.
pub fn short_class_name(class: &str) -> Option<&'static str> {
    lookup(table()?, class)
}

/// Rename the classes of a space-separated class list and leave out the
/// dropped ones.
pub(crate) fn map_class_list(list: &str) -> Cow<'_, str> {
    map_list(table(), list)
}

fn map_list<'a>(names: Option<ClassNames>, list: &'a str) -> Cow<'a, str> {
    let changes = |c: &str| names.is_some_and(|n| lookup(n, c).is_some()) || is_dropped(c);
    if !list.split_ascii_whitespace().any(changes) {
        return Cow::Borrowed(list);
    }
    let mut out = String::with_capacity(list.len());
    for class in list.split_ascii_whitespace() {
        if is_dropped(class) {
            continue;
        }
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(names.and_then(|n| lookup(n, class)).unwrap_or(class));
    }
    Cow::Owned(out)
}

/// Rename the classes in `class="…"` / `class='…'` attributes of raw HTML.
pub(crate) fn map_raw_html(html: &str) -> Cow<'_, str> {
    if table().is_none() && KNOWN_CLASSES.get().is_none() {
        return Cow::Borrowed(html);
    }
    map_html(table(), html)
}

fn map_html<'a>(names: Option<ClassNames>, html: &'a str) -> Cow<'a, str> {
    let b = html.as_bytes();
    let mut out: Option<String> = None;
    let mut copied = 0;
    let mut search = 0;
    while let Some(found) = html[search..].find("class=") {
        let at = search + found;
        search = at + 6;
        // Only a `class` attribute inside a tag: preceded by whitespace and
        // followed by a quote.
        let attr_start = at > 0 && b[at - 1].is_ascii_whitespace();
        let Some(&quote) = b.get(at + 6) else { break };
        if !attr_start || (quote != b'"' && quote != b'\'') {
            continue;
        }
        let value_start = at + 7;
        let Some(len) = html[value_start..].find(quote as char) else { break };
        let value = &html[value_start..value_start + len];
        if let Cow::Owned(mapped) = map_list(names, value) {
            let out = out.get_or_insert_with(|| String::with_capacity(html.len()));
            out.push_str(&html[copied..value_start]);
            out.push_str(&mapped);
            copied = value_start + len;
        }
        search = value_start + len;
    }
    match out {
        Some(mut out) => {
            out.push_str(&html[copied..]);
            Cow::Owned(out)
        }
        None => Cow::Borrowed(html),
    }
}

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

    const NAMES: ClassNames = &[("hover:underline", "b"), ("mt-4", "a"), ("text-[13px]", "c")];

    #[test]
    fn maps_known_classes_and_keeps_the_rest() {
        assert_eq!(map_list(Some(NAMES), "mt-4 card hover:underline"), "a card b");
        assert!(matches!(map_list(Some(NAMES), "card  tk"), Cow::Borrowed("card  tk")));
        assert_eq!(map_list(Some(NAMES), "  mt-4\ttext-[13px] "), "a c");
    }

    #[test]
    fn maps_class_attributes_in_raw_html() {
        let html = r#"<p class="mt-4 x">class="mt-4"</p><span data-class="mt-4" class='text-[13px]'>"#;
        assert_eq!(map_html(Some(NAMES), html), r#"<p class="a x">class="mt-4"</p><span data-class="mt-4" class='c'>"#);
        assert!(matches!(map_html(Some(NAMES), "<b class=\"tk\">"), Cow::Borrowed(_)));
    }

    #[test]
    fn drops_generated_looking_classes_nothing_knows() {
        set_known_classes(&["hover:underline", "mt-4", "sm:flex", "text-[13px]"]);
        assert_eq!(
            map_list(None, "mt-4 sm:flex sm:flexx bg-[x] w-1/3 !p-0 card g-recaptcha"),
            "mt-4 sm:flex card g-recaptcha"
        );
        assert_eq!(map_list(Some(NAMES), "aria-pressed:glass mt-4"), "a");
        assert_eq!(map_html(None, r#"<p class="card md:x">"#), r#"<p class="card">"#);
        for kept in ["%H:%M", "$20/month", "*/*", "src/page.rs", "a/b", "hero", "g-recaptcha", "https://x.y/z", "v1.0"]
        {
            assert!(!looks_generated(kept), "{kept}");
        }
        for generated in ["sm:flexx", "bg-[var(--x)]", "w-1/2", "!p-0", "aria-pressed:glass", "text-[1.5rem]"] {
            assert!(looks_generated(generated), "{generated}");
        }
    }
}