Skip to main content

tailwind_atomic/
classes.rs

1use std::collections::HashMap;
2
3const VARIANT_PSEUDOS: &[&str] = &[
4    "hover",
5    "focus",
6    "active",
7    "disabled",
8    "visited",
9    "focus-within",
10    "focus-visible",
11    "checked",
12    "required",
13    "optional",
14    "valid",
15    "invalid",
16    "first",
17    "last",
18    "odd",
19    "even",
20    "empty",
21    "target",
22    "enabled",
23    "indeterminate",
24    "default",
25    "open",
26    "autofill",
27    "placeholder-shown",
28    "read-only",
29    "pressed",
30];
31
32pub fn unescape_css_class_name(value: &str) -> String {
33    let bytes = value.as_bytes();
34    let mut out = String::with_capacity(value.len());
35    let mut i = 0;
36    while i < bytes.len() {
37        if bytes[i] == b'\\' && i + 1 < bytes.len() {
38            let next = bytes[i + 1];
39            if is_hex_digit(next) {
40                let mut j = i + 1;
41                let mut hex = String::new();
42                while j < bytes.len() && hex.len() < 6 && is_hex_digit(bytes[j]) {
43                    hex.push(bytes[j] as char);
44                    j += 1;
45                }
46                if j < bytes.len() && matches!(bytes[j], b' ' | b'\t' | b'\n' | b'\r' | 0x0c) {
47                    j += 1;
48                }
49                if let Ok(code) = u32::from_str_radix(&hex, 16) {
50                    if let Some(ch) = char::from_u32(code) {
51                        out.push(ch);
52                    }
53                }
54                i = j;
55                continue;
56            }
57            if next != b'\n' && next != b'\r' && next != 0x0c {
58                out.push(next as char);
59                i += 2;
60                continue;
61            }
62        }
63        out.push(bytes[i] as char);
64        i += 1;
65    }
66    out
67}
68
69fn is_hex_digit(b: u8) -> bool {
70    matches!(b, b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F')
71}
72
73pub fn strip_redundant_variant_pseudo(key: &str) -> String {
74    let Some(last_colon) = key.rfind(':') else {
75        return key.to_string();
76    };
77    if last_colon == 0 {
78        return key.to_string();
79    }
80    let pseudo = &key[last_colon + 1..];
81    if !VARIANT_PSEUDOS.iter().any(|name| *name == pseudo) {
82        return key.to_string();
83    }
84    let rest = &key[..last_colon];
85    if rest == pseudo
86        || rest.starts_with(&format!("{pseudo}:"))
87        || rest.contains(&format!(":{pseudo}:"))
88        || rest.ends_with(&format!(":{pseudo}"))
89    {
90        return rest.to_string();
91    }
92    key.to_string()
93}
94
95pub fn normalize_arbitrary_hex(key: &str) -> String {
96    let mut out = String::with_capacity(key.len());
97    let bytes = key.as_bytes();
98    let mut i = 0;
99    while i < bytes.len() {
100        if bytes[i] == b'[' && i + 1 < bytes.len() && bytes[i + 1] == b'#' {
101            out.push('[');
102            out.push('#');
103            i += 2;
104            while i < bytes.len() && bytes[i] != b']' {
105                out.push((bytes[i] as char).to_ascii_lowercase());
106                i += 1;
107            }
108            continue;
109        }
110        out.push(bytes[i] as char);
111        i += 1;
112    }
113    out
114}
115
116pub fn normalize_utility_class_name(value: &str) -> String {
117    normalize_arbitrary_hex(&strip_redundant_variant_pseudo(&unescape_css_class_name(
118        value,
119    )))
120}
121
122pub fn lookup_mapped_class<'a>(
123    cls: &str,
124    class_map: &'a HashMap<String, String>,
125) -> Option<&'a str> {
126    if let Some(mapped) = class_map.get(cls) {
127        return Some(mapped.as_str());
128    }
129    let unescaped = unescape_css_class_name(cls);
130    if unescaped != cls {
131        if let Some(mapped) = class_map.get(&unescaped) {
132            return Some(mapped.as_str());
133        }
134    }
135    let normalized = normalize_utility_class_name(cls);
136    class_map.get(&normalized).map(String::as_str)
137}
138
139/// Split Tailwind class lists on whitespace outside `[…]`.
140/// Quotes inside arbitrary values (`before:content-['']`) are part of the token.
141pub fn split_class_tokens(class_str: &str) -> Vec<&str> {
142    let bytes = class_str.as_bytes();
143    let mut tokens = Vec::new();
144    let mut start = 0;
145    let mut i = 0;
146    let mut depth = 0i32;
147    while i < bytes.len() {
148        let b = bytes[i];
149        if b == b'\\' && i + 1 < bytes.len() {
150            i += 2;
151            continue;
152        }
153        if b == b'[' {
154            depth += 1;
155        } else if b == b']' && depth > 0 {
156            depth -= 1;
157        }
158        if depth == 0 && bytes[i].is_ascii_whitespace() {
159            if i > start {
160                tokens.push(&class_str[start..i]);
161            }
162            i += 1;
163            start = i;
164            continue;
165        }
166        i += 1;
167    }
168    if i > start {
169        tokens.push(&class_str[start..i]);
170    }
171    tokens
172}
173
174/// Replace known utilities. Longer keys win when a token could match two
175/// map entries (`bg-red-500/50` before `bg-red-500`).
176pub fn rewrite_class_string(class_str: &str, class_map: &HashMap<String, String>) -> String {
177    if class_str.is_empty() || class_map.is_empty() {
178        return class_str.to_string();
179    }
180
181    split_class_tokens(class_str)
182        .into_iter()
183        .map(|token| {
184            lookup_mapped_class(token, class_map)
185                .unwrap_or(token)
186                .to_string()
187        })
188        .collect::<Vec<_>>()
189        .join(" ")
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn unescapes_variant_colons() {
198        assert_eq!(unescape_css_class_name("hover\\:flex"), "hover:flex");
199        assert_eq!(unescape_css_class_name("\\!px-4"), "!px-4");
200    }
201
202    #[test]
203    fn strips_trailing_variant_pseudos() {
204        assert_eq!(
205            strip_redundant_variant_pseudo("hover:bg-red-500:hover"),
206            "hover:bg-red-500"
207        );
208        assert_eq!(strip_redundant_variant_pseudo("flex"), "flex");
209    }
210
211    #[test]
212    fn rewrites_known_tokens() {
213        let mut map = HashMap::new();
214        map.insert("flex".into(), "_aaaaaa".into());
215        map.insert("hover:bg-red-500".into(), "_bbbbbb".into());
216        assert_eq!(
217            rewrite_class_string("flex extra hover:bg-red-500", &map),
218            "_aaaaaa extra _bbbbbb"
219        );
220    }
221
222    #[test]
223    fn keeps_quoted_arbitrary_content_on_before_after() {
224        let mut map = HashMap::new();
225        map.insert("before:content-['']".into(), "_before".into());
226        map.insert("after:content-['*']".into(), "_after".into());
227        map.insert("before:absolute".into(), "_abs".into());
228        assert_eq!(
229            rewrite_class_string("before:absolute before:content-[''] after:content-['*']", &map),
230            "_abs _before _after"
231        );
232        assert_eq!(
233            split_class_tokens("before:content-['hello world'] flex"),
234            vec!["before:content-['hello world']", "flex"]
235        );
236    }
237}