Skip to main content

tailwindcss_atomic/
tailwind.rs

1//! Tailwind utility grammar used by the compiler.
2//!
3//! There is no closed catalog of Tailwind classes: arbitrary values,
4//! stacked variants, `@theme` tokens and plugins generate names at compile
5//! time. What we *can* know is the shape of a utility (`variant:` + core
6//! plugin prefix / bare word / `[arbitrary]`), which is enough to leave
7//! custom BEM-style classes like `.header-signin` or `.btn-notch` alone.
8//!
9//! Vitest loads this classifier through WASM (`looks_like_tailwind_utility`).
10
11/// Bare utilities (no hyphen) from Tailwind's default theme.
12const BARE_UTILITIES: &[&str] = &[
13    "absolute",
14    "antialiased",
15    "block",
16    "blur",
17    "border",
18    "capitalize",
19    "collapse",
20    "container",
21    "contents",
22    "filter",
23    "fixed",
24    "flex",
25    "grayscale",
26    "grid",
27    "group",
28    "grow",
29    "hidden",
30    "inline",
31    "invert",
32    "invisible",
33    "isolate",
34    "italic",
35    "lowercase",
36    "ordinal",
37    "outline",
38    "overline",
39    "peer",
40    "prose",
41    "relative",
42    "resize",
43    "rounded",
44    "ring",
45    "sepia",
46    "shadow",
47    "shrink",
48    "static",
49    "sticky",
50    "table",
51    "transform",
52    "transition",
53    "truncate",
54    "underline",
55    "uppercase",
56    "visible",
57];
58
59/// Hyphenated utilities that would need a prefix too short or too greedy
60/// (`not-`, `no-`, `line-`, `drop-`) to match safely.
61const EXACT_UTILITIES: &[&str] = &[
62    "border-collapse",
63    "border-separate",
64    "box-border",
65    "box-content",
66    "break-all",
67    "break-keep",
68    "break-normal",
69    "break-words",
70    "caption-bottom",
71    "caption-top",
72    "decoration-clone",
73    "decoration-slice",
74    "diagonal-fractions",
75    "drop-shadow",
76    "flow-root",
77    "inline-block",
78    "inline-flex",
79    "inline-grid",
80    "inline-table",
81    "line-through",
82    "lining-nums",
83    "list-item",
84    "no-underline",
85    "normal-case",
86    "normal-nums",
87    "not-italic",
88    "not-sr-only",
89    "oldstyle-nums",
90    "overflow-ellipsis",
91    "proportional-nums",
92    "ring-inset",
93    "scroll-auto",
94    "scroll-smooth",
95    "slashed-zero",
96    "sr-only",
97    "stacked-fractions",
98    "subpixel-antialiased",
99    "table-auto",
100    "table-fixed",
101    "tabular-nums",
102    "text-balance",
103    "text-nowrap",
104    "text-pretty",
105    "text-wrap",
106];
107
108/// Core plugin prefixes (trailing `-`). Matching is `starts_with`; order
109/// does not matter for a boolean test.
110const UTILITY_PREFIXES: &[&str] = &[
111    "accent-",
112    "align-",
113    "animate-",
114    "appearance-",
115    "aspect-",
116    "auto-cols-",
117    "auto-rows-",
118    "backdrop-blur-",
119    "backdrop-brightness-",
120    "backdrop-contrast-",
121    "backdrop-grayscale-",
122    "backdrop-hue-rotate-",
123    "backdrop-invert-",
124    "backdrop-opacity-",
125    "backdrop-saturate-",
126    "backdrop-sepia-",
127    "backdrop-",
128    "backface-",
129    "basis-",
130    "bg-blend-",
131    "bg-conic-",
132    "bg-gradient-",
133    "bg-linear-",
134    "bg-radial-",
135    "bg-",
136    "blur-",
137    "border-spacing-",
138    "border-x-",
139    "border-y-",
140    "border-s-",
141    "border-e-",
142    "border-t-",
143    "border-r-",
144    "border-b-",
145    "border-l-",
146    "border-",
147    "bottom-",
148    "box-decoration-",
149    "box-",
150    "break-after-",
151    "break-before-",
152    "break-inside-",
153    "break-",
154    "brightness-",
155    "caption-",
156    "caret-",
157    "clear-",
158    "col-end-",
159    "col-span-",
160    "col-start-",
161    "col-",
162    "columns-",
163    "content-",
164    "contrast-",
165    "cursor-",
166    "decoration-",
167    "delay-",
168    "divide-x-",
169    "divide-y-",
170    "divide-",
171    "drop-shadow-",
172    "duration-",
173    "ease-",
174    "end-",
175    "field-sizing-",
176    "fill-",
177    "flex-",
178    "float-",
179    "font-",
180    "forced-color-adjust-",
181    "from-",
182    "gap-x-",
183    "gap-y-",
184    "gap-",
185    "grayscale-",
186    "grid-cols-",
187    "grid-flow-",
188    "grid-rows-",
189    "grow-",
190    "h-",
191    "hue-rotate-",
192    "hyphens-",
193    "indent-",
194    "inline-",
195    "inset-ring-",
196    "inset-shadow-",
197    "inset-x-",
198    "inset-y-",
199    "inset-",
200    "invert-",
201    "items-",
202    "justify-items-",
203    "justify-self-",
204    "justify-",
205    "leading-",
206    "left-",
207    "line-clamp-",
208    "list-image-",
209    "list-",
210    "m-",
211    "mask-",
212    "max-h-",
213    "max-w-",
214    "max-",
215    "mb-",
216    "me-",
217    "min-h-",
218    "min-w-",
219    "min-",
220    "mix-blend-",
221    "ml-",
222    "mr-",
223    "ms-",
224    "mt-",
225    "mx-",
226    "my-",
227    "object-",
228    "opacity-",
229    "order-",
230    "origin-",
231    "outline-offset-",
232    "outline-",
233    "overflow-x-",
234    "overflow-y-",
235    "overflow-",
236    "overscroll-x-",
237    "overscroll-y-",
238    "overscroll-",
239    "p-",
240    "pb-",
241    "pe-",
242    "perspective-",
243    "place-content-",
244    "place-items-",
245    "place-self-",
246    "place-",
247    "placeholder-",
248    "pl-",
249    "pointer-events-",
250    "pr-",
251    "prose-",
252    "ps-",
253    "pt-",
254    "px-",
255    "py-",
256    "resize-",
257    "right-",
258    "ring-offset-",
259    "ring-",
260    "rotate-x-",
261    "rotate-y-",
262    "rotate-z-",
263    "rotate-",
264    "rounded-ss-",
265    "rounded-se-",
266    "rounded-ee-",
267    "rounded-es-",
268    "rounded-tl-",
269    "rounded-tr-",
270    "rounded-br-",
271    "rounded-bl-",
272    "rounded-s-",
273    "rounded-e-",
274    "rounded-t-",
275    "rounded-r-",
276    "rounded-b-",
277    "rounded-l-",
278    "rounded-",
279    "row-end-",
280    "row-span-",
281    "row-start-",
282    "row-",
283    "saturate-",
284    "scale-x-",
285    "scale-y-",
286    "scale-z-",
287    "scale-",
288    "scheme-",
289    "scroll-m-",
290    "scroll-p-",
291    "scroll-px-",
292    "scroll-py-",
293    "scroll-ps-",
294    "scroll-pe-",
295    "scroll-pt-",
296    "scroll-pr-",
297    "scroll-pb-",
298    "scroll-pl-",
299    "scroll-mx-",
300    "scroll-my-",
301    "scroll-ms-",
302    "scroll-me-",
303    "scroll-mt-",
304    "scroll-mr-",
305    "scroll-mb-",
306    "scroll-ml-",
307    "scroll-",
308    "select-",
309    "self-",
310    "sepia-",
311    "shadow-",
312    "shrink-",
313    "size-",
314    "skew-x-",
315    "skew-y-",
316    "skew-",
317    "snap-",
318    "space-x-",
319    "space-y-",
320    "space-",
321    "sr-",
322    "start-",
323    "stroke-",
324    "table-",
325    "text-shadow-",
326    "text-",
327    "to-",
328    "top-",
329    "touch-",
330    "tracking-",
331    "transform-",
332    "transition-",
333    "translate-x-",
334    "translate-y-",
335    "translate-z-",
336    "translate-",
337    "underline-offset-",
338    "via-",
339    "w-",
340    "whitespace-",
341    "will-change-",
342    "z-",
343];
344
345fn variant_colon_index(name: &str) -> Option<usize> {
346    let bytes = name.as_bytes();
347    let mut depth = 0i32;
348    let mut i = 0;
349    while i < bytes.len() {
350        if bytes[i] == b'\\' {
351            i = (i + 2).min(bytes.len());
352            continue;
353        }
354        match bytes[i] {
355            b'[' => depth += 1,
356            b']' if depth > 0 => depth -= 1,
357            b':' if depth == 0 => return Some(i),
358            _ => {}
359        }
360        i += 1;
361    }
362    None
363}
364
365/// Strip stacked variants (`lg:hover:`) and `!important` markers, leaving
366/// the core utility (`flex`, `bg-red-500`, `content-['']`).
367pub fn core_utility_name(name: &str) -> &str {
368    let mut rest = name;
369    loop {
370        rest = rest.strip_prefix('!').unwrap_or(rest);
371        match variant_colon_index(rest) {
372            Some(index) => rest = &rest[index + 1..],
373            None => break,
374        }
375    }
376    rest.strip_prefix('!').unwrap_or(rest)
377}
378
379fn looks_like_tailwind_core(core: &str) -> bool {
380    if core.is_empty() {
381        return false;
382    }
383    if core.starts_with('[') || core.contains('[') {
384        return true;
385    }
386    let unsigned = core.strip_prefix('-').unwrap_or(core);
387    let base = unsigned.split_once('/').map(|(head, _)| head).unwrap_or(unsigned);
388    if BARE_UTILITIES.iter().any(|item| *item == base) {
389        return true;
390    }
391    if EXACT_UTILITIES.iter().any(|item| *item == base) {
392        return true;
393    }
394    UTILITY_PREFIXES
395        .iter()
396        .any(|prefix| base.starts_with(prefix) && base.len() > prefix.len())
397}
398
399/// True for Tailwind-shaped class names, false for custom hyphenated
400/// components (`.header-signin`, `.btn-notch`).
401pub fn looks_like_tailwind_utility(class_name: &str) -> bool {
402    let name = crate::classes::unescape_css_class_name(class_name);
403    if name.is_empty() {
404        return false;
405    }
406    looks_like_tailwind_core(core_utility_name(&name))
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn accepts_default_utilities() {
415        for name in [
416            "flex",
417            "hidden",
418            "rounded",
419            "rounded-md",
420            "rounded-full",
421            "p-4",
422            "-mt-2",
423            "px-4",
424            "items-center",
425            "bg-revamp-primary-default",
426            "w-1/2",
427            "bg-red-500/50",
428            "!px-4",
429            "hover:bg-red-500",
430            "lg:hover:flex",
431            "before:content-['']",
432            "after:content-['*']",
433            "w-[327px]",
434            "[color:red]",
435            "sr-only",
436            "not-sr-only",
437            "inline-flex",
438            "space-y-4",
439            "divide-x-2",
440            "min-h-screen",
441            "max-w-prose",
442            "prose-headings",
443            "data-[state=open]:flex",
444            "sm:grid-cols-[3rem_minmax(0,1fr)_7rem]",
445            "from-primary/[0.05]",
446            "data-[active=true]:font-medium",
447            "aria-selected:bg-red-500",
448            "open:hidden",
449        ] {
450            assert!(
451                looks_like_tailwind_utility(name),
452                "expected Tailwind utility: {name}"
453            );
454        }
455    }
456
457    #[test]
458    fn rejects_custom_hyphenated_components() {
459        for name in [
460            "header-signin",
461            "btn-notch",
462            "eye-line",
463            "pattern-background",
464            "slick-slide",
465            "pokerenchile",
466            "nexi",
467            "hover:header-signin",
468            "lg:btn-notch",
469        ] {
470            assert!(
471                !looks_like_tailwind_utility(name),
472                "expected custom class: {name}"
473            );
474        }
475    }
476}