Skip to main content

tailwind_atomic/
html.rs

1use std::collections::HashMap;
2
3use crate::classes::rewrite_class_string;
4
5fn is_ident_char(ch: char) -> bool {
6    ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'
7}
8
9fn starts_with_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
10    haystack.len() >= needle.len() && haystack[..needle.len()].eq_ignore_ascii_case(needle)
11}
12
13/// Rewrite `class` / `className` attributes in HTML-like markup.
14/// Keeps quotes and surrounding source intact (same role as mangle's htmlHandler).
15pub fn rewrite_html_classes(html: &str, class_map: &HashMap<String, String>) -> String {
16    if html.is_empty() || class_map.is_empty() {
17        return html.to_string();
18    }
19
20    let mut out = String::with_capacity(html.len());
21    let chars: Vec<char> = html.chars().collect();
22    let mut i = 0;
23    while i < chars.len() {
24        let rest: String = chars[i..].iter().collect();
25        let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
26        let attr = if prev_ok && starts_with_ignore_ascii_case(&rest, "classname") {
27            Some("className")
28        } else if prev_ok && starts_with_ignore_ascii_case(&rest, "class") {
29            let after = rest.get("class".len()..).unwrap_or("");
30            if after.starts_with('=') || after.chars().next().is_some_and(|ch| ch.is_whitespace()) {
31                Some("class")
32            } else {
33                None
34            }
35        } else {
36            None
37        };
38
39        if let Some(name) = attr {
40            let name_len = name.len();
41            let mut j = i + name_len;
42            while j < chars.len() && chars[j].is_whitespace() {
43                j += 1;
44            }
45            if j < chars.len() && chars[j] == '=' {
46                j += 1;
47                while j < chars.len() && chars[j].is_whitespace() {
48                    j += 1;
49                }
50                if j < chars.len() && (chars[j] == '"' || chars[j] == '\'') {
51                    let quote = chars[j];
52                    j += 1;
53                    let value_start = j;
54                    while j < chars.len() && chars[j] != quote {
55                        j += 1;
56                    }
57                    let value: String = chars[value_start..j].iter().collect();
58                    let rewritten = rewrite_class_string(&value, class_map);
59                    out.push_str(&chars[i..value_start].iter().collect::<String>());
60                    out.push_str(&rewritten);
61                    if j < chars.len() {
62                        out.push(quote);
63                        i = j + 1;
64                    } else {
65                        i = j;
66                    }
67                    continue;
68                }
69            }
70        }
71
72        out.push(chars[i]);
73        i += 1;
74    }
75    out
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn rewrites_html_and_jsx_class_attributes() {
84        let mut map = HashMap::new();
85        map.insert("flex".into(), "_aaaaaa".into());
86        map.insert("p-6".into(), "_bbbbbb".into());
87        assert_eq!(
88            rewrite_html_classes(
89                r#"<div class="flex p-6" className="flex" id="flex"></div>"#,
90                &map
91            ),
92            r#"<div class="_aaaaaa _bbbbbb" className="_aaaaaa" id="flex"></div>"#
93        );
94    }
95
96    #[test]
97    fn rewrites_before_after_content_classes() {
98        let mut map = HashMap::new();
99        map.insert("before:content-['']".into(), "_bemp01".into());
100        map.insert("after:content-['*']".into(), "_astar1".into());
101        assert_eq!(
102            rewrite_html_classes(
103                r#"<i class="before:content-[''] after:content-['*']"></i>"#,
104                &map
105            ),
106            r#"<i class="_bemp01 _astar1"></i>"#
107        );
108    }
109}