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();
17static KNOWN_CLASSES: OnceLock<&'static [&'static str]> = OnceLock::new();
18
19/// Install the renaming table. Called once by the server at startup; later
20/// calls are ignored. An empty table leaves class names unchanged.
21pub fn set_class_names(names: ClassNames) {
22    if !names.is_empty() {
23        debug_assert!(names.is_sorted_by(|a, b| a.0 < b.0), "class names must be sorted");
24        let _ = CLASS_NAMES.set(names);
25    }
26}
27
28/// Install the classes the build found a rule, a script or a static file
29/// for (sorted). With it set, the renderer leaves out classes that look
30/// generated (`sm:flexx`, `bg-[…]`, `w-1/3`) but are known to nothing: they
31/// would style nothing. Called once by the server at startup.
32pub fn set_known_classes(classes: &'static [&'static str]) {
33    if !classes.is_empty() {
34        debug_assert!(classes.is_sorted(), "known classes must be sorted");
35        let _ = KNOWN_CLASSES.set(classes);
36    }
37}
38
39/// Whether the renderer leaves `class` out: it looks generated by Tailwind
40/// yet nothing knows it.
41pub fn is_dropped(class: &str) -> bool {
42    KNOWN_CLASSES.get().is_some_and(|known| looks_generated(class) && known.binary_search(&class).is_err())
43}
44
45/// Whether `class` has the shape of a generated Tailwind class: variants
46/// (`sm:`, `aria-pressed:`, `[&_.x]:`) before a utility with an arbitrary
47/// value (`bg-[…]`), a fraction (`w-1/2`) or `!`. Plain words (`hero`,
48/// `g-recaptcha`), format strings, paths and CSS declarations are not.
49pub fn looks_generated(class: &str) -> bool {
50    let name = class.strip_prefix('!').unwrap_or(class);
51    let special = name.contains([':', '[', '/']) || class.starts_with('!');
52    if !special
53        || !name.starts_with(|c: char| c.is_ascii_lowercase())
54        || !name.contains(['-', ':'])
55        || name.ends_with([':', '/', '-'])
56        || name.contains("//")
57        || name.as_bytes().windows(2).any(|w| w[0] == b'.' && w[1].is_ascii_alphabetic())
58    {
59        return false;
60    }
61    // Underscores stand for spaces inside brackets only; `(` only in brackets.
62    let mut depth = 0i32;
63    for c in name.chars() {
64        match c {
65            '[' => depth += 1,
66            ']' => depth -= 1,
67            '_' | '(' | ')' | ',' | '%' if depth == 0 => return false,
68            c if c.is_ascii_alphanumeric() || "-_:/[]().%,#+".contains(c) => {}
69            _ => return false,
70        }
71        if depth < 0 {
72            return false;
73        }
74    }
75    if depth != 0 {
76        return false;
77    }
78    // Split at the colons outside brackets: variants, then the utility.
79    let mut segments = Vec::new();
80    let (mut depth, mut start) = (0, 0);
81    for (i, c) in name.char_indices() {
82        match c {
83            '[' => depth += 1,
84            ']' => depth -= 1,
85            ':' if depth == 0 => {
86                segments.push(&name[start..i]);
87                start = i + 1;
88            }
89            _ => {}
90        }
91    }
92    segments.push(&name[start..]);
93    let Some((utility, variants)) = segments.split_last() else { return false };
94    if utility.is_empty()
95        || utility.starts_with(|c: char| c.is_ascii_digit() || c == '-')
96        || variants.iter().any(|v| v.is_empty() || !v.starts_with(|c: char| c.is_ascii_lowercase() || c == '['))
97    {
98        return false;
99    }
100    // A fraction or an opacity: `/` before a digit or a bracket.
101    let bytes = utility.as_bytes();
102    bytes
103        .iter()
104        .enumerate()
105        .all(|(i, b)| *b != b'/' || bytes.get(i + 1).is_some_and(|n| n.is_ascii_digit() || *n == b'['))
106}
107
108fn table() -> Option<ClassNames> {
109    CLASS_NAMES.get().copied()
110}
111
112fn lookup(names: ClassNames, class: &str) -> Option<&'static str> {
113    names.binary_search_by(|(original, _)| (*original).cmp(class)).ok().map(|i| names[i].1)
114}
115
116/// The short name of one class, if it has one.
117pub fn short_class_name(class: &str) -> Option<&'static str> {
118    lookup(table()?, class)
119}
120
121/// Rename the classes of a space-separated class list and leave out the
122/// dropped ones.
123pub(crate) fn map_class_list(list: &str) -> Cow<'_, str> {
124    map_list(table(), list)
125}
126
127fn map_list<'a>(names: Option<ClassNames>, list: &'a str) -> Cow<'a, str> {
128    let changes = |c: &str| names.is_some_and(|n| lookup(n, c).is_some()) || is_dropped(c);
129    if !list.split_ascii_whitespace().any(changes) {
130        return Cow::Borrowed(list);
131    }
132    let mut out = String::with_capacity(list.len());
133    for class in list.split_ascii_whitespace() {
134        if is_dropped(class) {
135            continue;
136        }
137        if !out.is_empty() {
138            out.push(' ');
139        }
140        out.push_str(names.and_then(|n| lookup(n, class)).unwrap_or(class));
141    }
142    Cow::Owned(out)
143}
144
145/// Rename the classes in `class="…"` / `class='…'` attributes of raw HTML.
146pub(crate) fn map_raw_html(html: &str) -> Cow<'_, str> {
147    if table().is_none() && KNOWN_CLASSES.get().is_none() {
148        return Cow::Borrowed(html);
149    }
150    map_html(table(), html)
151}
152
153fn map_html<'a>(names: Option<ClassNames>, html: &'a str) -> Cow<'a, str> {
154    let b = html.as_bytes();
155    let mut out: Option<String> = None;
156    let mut copied = 0;
157    let mut search = 0;
158    while let Some(found) = html[search..].find("class=") {
159        let at = search + found;
160        search = at + 6;
161        // Only a `class` attribute inside a tag: preceded by whitespace and
162        // followed by a quote.
163        let attr_start = at > 0 && b[at - 1].is_ascii_whitespace();
164        let Some(&quote) = b.get(at + 6) else { break };
165        if !attr_start || (quote != b'"' && quote != b'\'') {
166            continue;
167        }
168        let value_start = at + 7;
169        let Some(len) = html[value_start..].find(quote as char) else { break };
170        let value = &html[value_start..value_start + len];
171        if let Cow::Owned(mapped) = map_list(names, value) {
172            let out = out.get_or_insert_with(|| String::with_capacity(html.len()));
173            out.push_str(&html[copied..value_start]);
174            out.push_str(&mapped);
175            copied = value_start + len;
176        }
177        search = value_start + len;
178    }
179    match out {
180        Some(mut out) => {
181            out.push_str(&html[copied..]);
182            Cow::Owned(out)
183        }
184        None => Cow::Borrowed(html),
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    const NAMES: ClassNames = &[("hover:underline", "b"), ("mt-4", "a"), ("text-[13px]", "c")];
193
194    #[test]
195    fn maps_known_classes_and_keeps_the_rest() {
196        assert_eq!(map_list(Some(NAMES), "mt-4 card hover:underline"), "a card b");
197        assert!(matches!(map_list(Some(NAMES), "card  tk"), Cow::Borrowed("card  tk")));
198        assert_eq!(map_list(Some(NAMES), "  mt-4\ttext-[13px] "), "a c");
199    }
200
201    #[test]
202    fn maps_class_attributes_in_raw_html() {
203        let html = r#"<p class="mt-4 x">class="mt-4"</p><span data-class="mt-4" class='text-[13px]'>"#;
204        assert_eq!(map_html(Some(NAMES), html), r#"<p class="a x">class="mt-4"</p><span data-class="mt-4" class='c'>"#);
205        assert!(matches!(map_html(Some(NAMES), "<b class=\"tk\">"), Cow::Borrowed(_)));
206    }
207
208    #[test]
209    fn drops_generated_looking_classes_nothing_knows() {
210        set_known_classes(&["hover:underline", "mt-4", "sm:flex", "text-[13px]"]);
211        assert_eq!(
212            map_list(None, "mt-4 sm:flex sm:flexx bg-[x] w-1/3 !p-0 card g-recaptcha"),
213            "mt-4 sm:flex card g-recaptcha"
214        );
215        assert_eq!(map_list(Some(NAMES), "aria-pressed:glass mt-4"), "a");
216        assert_eq!(map_html(None, r#"<p class="card md:x">"#), r#"<p class="card">"#);
217        for kept in ["%H:%M", "$20/month", "*/*", "src/page.rs", "a/b", "hero", "g-recaptcha", "https://x.y/z", "v1.0"]
218        {
219            assert!(!looks_generated(kept), "{kept}");
220        }
221        for generated in ["sm:flexx", "bg-[var(--x)]", "w-1/2", "!p-0", "aria-pressed:glass", "text-[1.5rem]"] {
222            assert!(looks_generated(generated), "{generated}");
223        }
224    }
225}