Skip to main content

next_rust_view/
class_names.rs

1//! Short class names for production builds.
2//!
3//! Release builds of Tailwind projects rename every utility class to a short,
4//! random name (`rounded-lg` → `k7`). The build renames the selectors in the
5//! generated CSS and hands the renaming table to the app at startup; the
6//! renderer then writes the short names wherever the original ones appear in
7//! `class` attributes, in [`active_class`](crate::active_class) values, in
8//! `data-nr-class-<name>` attributes and in `class="…"` inside raw HTML.
9
10use std::borrow::Cow;
11use std::sync::OnceLock;
12
13/// `(original, short)` pairs, sorted by original name.
14pub type ClassNames = &'static [(&'static str, &'static str)];
15
16static CLASS_NAMES: OnceLock<ClassNames> = OnceLock::new();
17
18/// Install the renaming table. Called once by the server at startup; later
19/// calls are ignored. An empty table leaves class names unchanged.
20pub fn set_class_names(names: ClassNames) {
21    if !names.is_empty() {
22        debug_assert!(names.is_sorted_by(|a, b| a.0 < b.0), "class names must be sorted");
23        let _ = CLASS_NAMES.set(names);
24    }
25}
26
27fn table() -> Option<ClassNames> {
28    CLASS_NAMES.get().copied()
29}
30
31fn lookup(names: ClassNames, class: &str) -> Option<&'static str> {
32    names.binary_search_by(|(original, _)| (*original).cmp(class)).ok().map(|i| names[i].1)
33}
34
35/// The short name of one class, if it has one.
36pub fn short_class_name(class: &str) -> Option<&'static str> {
37    lookup(table()?, class)
38}
39
40/// Rename the classes of a space-separated class list.
41pub(crate) fn map_class_list(list: &str) -> Cow<'_, str> {
42    match table() {
43        Some(names) => map_list(names, list),
44        None => Cow::Borrowed(list),
45    }
46}
47
48fn map_list<'a>(names: ClassNames, list: &'a str) -> Cow<'a, str> {
49    if !list.split_ascii_whitespace().any(|c| lookup(names, c).is_some()) {
50        return Cow::Borrowed(list);
51    }
52    let mut out = String::with_capacity(list.len());
53    for class in list.split_ascii_whitespace() {
54        if !out.is_empty() {
55            out.push(' ');
56        }
57        out.push_str(lookup(names, class).unwrap_or(class));
58    }
59    Cow::Owned(out)
60}
61
62/// Rename the classes in `class="…"` / `class='…'` attributes of raw HTML.
63pub(crate) fn map_raw_html(html: &str) -> Cow<'_, str> {
64    match table() {
65        Some(names) if html.contains("class=") => map_html(names, html),
66        _ => Cow::Borrowed(html),
67    }
68}
69
70fn map_html<'a>(names: ClassNames, html: &'a str) -> Cow<'a, str> {
71    let b = html.as_bytes();
72    let mut out: Option<String> = None;
73    let mut copied = 0;
74    let mut search = 0;
75    while let Some(found) = html[search..].find("class=") {
76        let at = search + found;
77        search = at + 6;
78        // Only a `class` attribute inside a tag: preceded by whitespace and
79        // followed by a quote.
80        let attr_start = at > 0 && b[at - 1].is_ascii_whitespace();
81        let Some(&quote) = b.get(at + 6) else { break };
82        if !attr_start || (quote != b'"' && quote != b'\'') {
83            continue;
84        }
85        let value_start = at + 7;
86        let Some(len) = html[value_start..].find(quote as char) else { break };
87        let value = &html[value_start..value_start + len];
88        if let Cow::Owned(mapped) = map_list(names, value) {
89            let out = out.get_or_insert_with(|| String::with_capacity(html.len()));
90            out.push_str(&html[copied..value_start]);
91            out.push_str(&mapped);
92            copied = value_start + len;
93        }
94        search = value_start + len;
95    }
96    match out {
97        Some(mut out) => {
98            out.push_str(&html[copied..]);
99            Cow::Owned(out)
100        }
101        None => Cow::Borrowed(html),
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    const NAMES: ClassNames = &[("hover:underline", "b"), ("mt-4", "a"), ("text-[13px]", "c")];
110
111    #[test]
112    fn maps_known_classes_and_keeps_the_rest() {
113        assert_eq!(map_list(NAMES, "mt-4 card hover:underline"), "a card b");
114        assert!(matches!(map_list(NAMES, "card  tk"), Cow::Borrowed("card  tk")));
115        assert_eq!(map_list(NAMES, "  mt-4\ttext-[13px] "), "a c");
116    }
117
118    #[test]
119    fn maps_class_attributes_in_raw_html() {
120        let html = r#"<p class="mt-4 x">class="mt-4"</p><span data-class="mt-4" class='text-[13px]'>"#;
121        assert_eq!(map_html(NAMES, html), r#"<p class="a x">class="mt-4"</p><span data-class="mt-4" class='c'>"#);
122        assert!(matches!(map_html(NAMES, "<b class=\"tk\">"), Cow::Borrowed(_)));
123    }
124}