1use std::sync::LazyLock;
14
15use rustc_hash::{FxHashMap, FxHashSet};
16
17use crate::ExportName;
18use crate::css::extract_css_module_exports;
19
20static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
24 crate::static_regex(
25 r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
26 )
27});
28
29fn has_scoped_attr(attrs: &str) -> bool {
32 attrs
33 .split(|c: char| c.is_whitespace() || c == '=' || c == '"' || c == '\'')
34 .any(|token| token.eq_ignore_ascii_case("scoped"))
35}
36
37fn has_non_css_lang(attrs: &str) -> bool {
41 let lower = attrs.to_ascii_lowercase();
42 has_preprocessor_lang_value(&lower)
43 || [
44 "lang=\"stylus\"",
45 "lang='stylus'",
46 "lang=\"postcss\"",
47 "lang='postcss'",
48 ]
49 .iter()
50 .any(|needle| lower.contains(needle))
51}
52
53fn has_preprocessor_lang(attrs: &str) -> bool {
54 has_preprocessor_lang_value(&attrs.to_ascii_lowercase())
55}
56
57fn has_preprocessor_lang_value(lower_attrs: &str) -> bool {
58 [
59 "lang=\"scss\"",
60 "lang='scss'",
61 "lang=\"sass\"",
62 "lang='sass'",
63 "lang=\"less\"",
64 "lang='less'",
65 ]
66 .iter()
67 .any(|needle| lower_attrs.contains(needle))
68}
69
70fn block_escapes_scope(body: &str) -> bool {
74 body.contains(":global")
75 || body.contains(":deep")
76 || body.contains("::v-deep")
77 || body.contains("/deep/")
78 || body.contains("@apply")
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct ScopedUnusedClasses {
84 pub classes: Vec<String>,
86 pub line: u32,
89}
90
91#[must_use]
95pub fn scoped_unused_classes(source: &str) -> Vec<String> {
96 scoped_unused_classes_at(source).map_or_else(Vec::new, |found| found.classes)
97}
98
99#[must_use]
102pub fn scoped_unused_classes_at(source: &str) -> Option<ScopedUnusedClasses> {
103 let mut scoped_classes: FxHashMap<String, usize> = FxHashMap::default();
105 let mut style_ranges: Vec<(usize, usize)> = Vec::new();
108
109 for caps in STYLE_BLOCK_RE.captures_iter(source) {
110 if let Some(whole) = caps.get(0) {
111 style_ranges.push((whole.start(), whole.end()));
112 }
113 let attrs = caps.name("attrs").map_or("", |m| m.as_str());
114 let Some(body) = caps.name("body") else {
115 continue;
116 };
117 if !has_scoped_attr(attrs) || has_non_css_lang(attrs) || block_escapes_scope(body.as_str())
118 {
119 continue;
120 }
121 for export in extract_css_module_exports(body.as_str(), false) {
122 if let ExportName::Named(name) = export.name {
123 let offset = body.start() + export.span.start as usize;
124 scoped_classes
125 .entry(name)
126 .and_modify(|first| *first = (*first).min(offset))
127 .or_insert(offset);
128 }
129 }
130 }
131
132 if scoped_classes.is_empty() {
133 return None;
134 }
135
136 let search = blank_ranges(source, &style_ranges);
137 let transition_classes = vue_transition_classes(&search);
138 let mut candidates: Vec<(String, usize)> = scoped_classes
139 .into_iter()
140 .filter(|(class, _)| {
141 !transition_classes.contains(class) && !class_token_appears(&search, class)
142 })
143 .collect();
144 let first_offset = candidates.iter().map(|(_, offset)| *offset).min()?;
145 candidates.sort_unstable();
146 let line_offsets = fallow_types::extract::compute_line_offsets(source);
147 let (line, _) = fallow_types::extract::byte_offset_to_line_col(
148 &line_offsets,
149 u32::try_from(first_offset).unwrap_or(u32::MAX),
150 );
151 Some(ScopedUnusedClasses {
152 classes: candidates.into_iter().map(|(class, _)| class).collect(),
153 line,
154 })
155}
156
157static TRANSITION_TAG_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
161 crate::static_regex(
162 r#"<(?P<tag>TransitionGroup|transition-group|Transition|transition)(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>"#,
163 )
164});
165
166static TAG_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
169 crate::static_regex(
170 r#"(?P<key>[^\s=/>"']+)(?:\s*=\s*(?:"(?P<dq>[^"]*)"|'(?P<sq>[^']*)'|(?P<uq>[^\s>"']+)))?"#,
171 )
172});
173
174const TRANSITION_CLASS_SUFFIXES: [&str; 6] = [
176 "enter-from",
177 "enter-active",
178 "enter-to",
179 "leave-from",
180 "leave-active",
181 "leave-to",
182];
183
184const TRANSITION_GROUP_MOVE_SUFFIX: &str = "move";
186
187const DEFAULT_TRANSITION_NAME: &str = "v";
189
190const TRANSITION_CLASS_PROPS: [&str; 20] = [
193 "enter-from-class",
194 "enter-active-class",
195 "enter-to-class",
196 "leave-from-class",
197 "leave-active-class",
198 "leave-to-class",
199 "appear-from-class",
200 "appear-active-class",
201 "appear-to-class",
202 "move-class",
203 "enterFromClass",
204 "enterActiveClass",
205 "enterToClass",
206 "leaveFromClass",
207 "leaveActiveClass",
208 "leaveToClass",
209 "appearFromClass",
210 "appearActiveClass",
211 "appearToClass",
212 "moveClass",
213];
214
215enum TransitionName<'a> {
217 Absent,
218 Literal(&'a str),
219 Bound,
220}
221
222#[must_use]
231pub fn vue_transition_classes(source: &str) -> FxHashSet<String> {
232 let mut out = FxHashSet::default();
233 for caps in TRANSITION_TAG_RE.captures_iter(source) {
234 let attrs = caps.name("attrs").map_or("", |m| m.as_str());
235 if attrs
236 .chars()
237 .next()
238 .is_some_and(|c| !c.is_whitespace() && c != '/')
239 {
240 continue;
241 }
242 let is_group = caps
243 .name("tag")
244 .is_some_and(|m| matches!(m.as_str(), "TransitionGroup" | "transition-group"));
245 collect_transition_tag_classes(attrs, is_group, &mut out);
246 }
247 out
248}
249
250fn is_bound_name_attr(key: &str) -> bool {
254 if key == "v-bind" {
255 return true;
256 }
257 let Some(arg) = key
258 .strip_prefix(':')
259 .or_else(|| key.strip_prefix("v-bind:"))
260 else {
261 return false;
262 };
263 arg.split('.').next() == Some("name")
264}
265
266fn collect_transition_tag_classes(attrs: &str, is_group: bool, out: &mut FxHashSet<String>) {
267 let mut name = TransitionName::Absent;
268 for caps in TAG_ATTR_RE.captures_iter(attrs) {
269 let key = caps.name("key").map_or("", |m| m.as_str());
270 let value = caps
271 .name("dq")
272 .or_else(|| caps.name("sq"))
273 .or_else(|| caps.name("uq"))
274 .map(|m| m.as_str());
275 match (key, value) {
276 ("name", Some(value)) => name = TransitionName::Literal(value.trim()),
277 (key, _) if is_bound_name_attr(key) => name = TransitionName::Bound,
278 (key, Some(value)) if TRANSITION_CLASS_PROPS.contains(&key) => {
279 out.extend(value.split_whitespace().map(str::to_string));
280 }
281 _ => {}
282 }
283 }
284 let prefix = match name {
285 TransitionName::Bound => return,
286 TransitionName::Absent | TransitionName::Literal("") => DEFAULT_TRANSITION_NAME,
287 TransitionName::Literal(value) if value.contains(char::is_whitespace) => return,
288 TransitionName::Literal(value) => value,
289 };
290 out.extend(
291 TRANSITION_CLASS_SUFFIXES
292 .iter()
293 .map(|suffix| format!("{prefix}-{suffix}")),
294 );
295 if is_group {
296 out.insert(format!("{prefix}-{TRANSITION_GROUP_MOVE_SUFFIX}"));
297 }
298}
299
300#[must_use]
307pub fn sfc_virtual_stylesheet(source: &str) -> Option<String> {
308 virtual_stylesheet(source, |attrs| !has_non_css_lang(attrs))
309}
310
311#[must_use]
314pub fn sfc_preprocessor_virtual_stylesheet(source: &str) -> Option<String> {
315 virtual_stylesheet(source, has_preprocessor_lang)
316}
317
318fn virtual_stylesheet(source: &str, keep: impl Fn(&str) -> bool) -> Option<String> {
327 let mut out = String::new();
328 let mut current_line: usize = 1;
329 let mut found = false;
330 for caps in STYLE_BLOCK_RE.captures_iter(source) {
331 let attrs = caps.name("attrs").map_or("", |m| m.as_str());
332 if !keep(attrs) {
333 continue;
334 }
335 let Some(body) = caps.name("body") else {
336 continue;
337 };
338 found = true;
339 let block_line = 1 + source[..body.start()]
340 .bytes()
341 .filter(|&b| b == b'\n')
342 .count();
343 while current_line < block_line {
344 out.push('\n');
345 current_line += 1;
346 }
347 out.push_str(body.as_str());
348 current_line += body.as_str().bytes().filter(|&b| b == b'\n').count();
349 }
350 found.then_some(out)
351}
352
353fn blank_ranges(source: &str, ranges: &[(usize, usize)]) -> String {
357 let mut out = source.as_bytes().to_vec();
358 for &(start, end) in ranges {
359 if start <= end && end <= out.len() {
360 for byte in &mut out[start..end] {
361 *byte = b' ';
362 }
363 }
364 }
365 String::from_utf8(out).unwrap_or_else(|_| source.to_string())
368}
369
370fn class_token_appears(text: &str, name: &str) -> bool {
374 if name.is_empty() {
375 return false;
376 }
377 let bytes = text.as_bytes();
378 let len = name.len();
379 let mut from = 0;
380 while let Some(offset) = text[from..].find(name) {
381 let start = from + offset;
382 let end = start + len;
383 let before_ok = start == 0 || !is_identifier_byte(bytes[start - 1]);
384 let after_ok = end >= bytes.len() || !is_identifier_byte(bytes[end]);
385 if before_ok && after_ok {
386 return true;
387 }
388 from = start + 1;
389 if from >= text.len() {
390 break;
391 }
392 }
393 false
394}
395
396fn is_identifier_byte(byte: u8) -> bool {
397 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'
398}
399
400#[cfg(all(test, not(miri)))]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn scoped_unused_classes_have_the_line_of_the_first_definition() {
406 let found = scoped_unused_classes_at(
407 "<template>\n <div class=\"card\"></div>\n</template>\n\n<style scoped>\n\
408 .card {\n padding: 16px;\n}\n.card__badge {\n color: green;\n}\n\
409 .card__old {\n color: red;\n}\n</style>\n",
410 )
411 .expect("two classes are unused");
412 assert_eq!(found.classes, vec!["card__badge", "card__old"]);
413 assert_eq!(found.line, 9);
414 assert!(scoped_unused_classes_at("<style scoped>.a {}</style><p class=\"a\">").is_none());
415 }
416
417 #[test]
418 fn flags_unused_scoped_class() {
419 let dead = scoped_unused_classes(
420 "<template><div class=\"used\"></div></template>\n\
421 <style scoped>.used { color: red; } .dead { color: blue; }</style>",
422 );
423 assert_eq!(dead, vec!["dead".to_string()]);
424 }
425
426 #[test]
427 fn class_used_in_dynamic_binding_is_not_flagged() {
428 let dead = scoped_unused_classes(
430 "<template><div :class=\"{ active: isActive }\"></div></template>\n\
431 <style scoped>.active { color: red; }</style>",
432 );
433 assert!(dead.is_empty(), "got {dead:?}");
434 }
435
436 #[test]
437 fn class_used_in_svelte_directive_is_not_flagged() {
438 let dead = scoped_unused_classes(
439 "<button class:selected={on}>x</button>\n\
440 <style>.selected { color: red; }</style>",
441 );
442 assert!(dead.is_empty(), "got {dead:?}");
445 }
446
447 #[test]
448 fn class_referenced_in_script_is_not_flagged() {
449 let dead = scoped_unused_classes(
450 "<script>const c = \"highlight\";</script>\n\
451 <template><div :class=\"c\"></div></template>\n\
452 <style scoped>.highlight { color: red; }</style>",
453 );
454 assert!(dead.is_empty(), "got {dead:?}");
455 }
456
457 #[test]
458 fn global_selector_block_is_skipped() {
459 let dead = scoped_unused_classes(
460 "<template><div></div></template>\n\
461 <style scoped>:global(.x) { color: red; } .y { color: blue; }</style>",
462 );
463 assert!(dead.is_empty(), "blocks with :global are skipped wholesale");
464 }
465
466 #[test]
467 fn scss_scoped_block_is_skipped() {
468 let dead = scoped_unused_classes(
469 "<template><div></div></template>\n\
470 <style scoped lang=\"scss\">.dead { color: red; }</style>",
471 );
472 assert!(dead.is_empty(), "scss is not parsed");
473 }
474
475 #[test]
476 fn non_scoped_block_is_not_analyzed() {
477 let dead = scoped_unused_classes(
478 "<template><div></div></template>\n\
479 <style>.dead { color: red; }</style>",
480 );
481 assert!(dead.is_empty(), "only scoped blocks are analyzed");
482 }
483
484 #[test]
485 fn virtual_stylesheet_places_rules_at_sfc_lines() {
486 let source = "<template>\n <div/>\n</template>\n<style>\n.a { color: red; }\n</style>";
489 let vcss = super::sfc_virtual_stylesheet(source).expect("has a plain-CSS style block");
490 let line_of_a = 1 + vcss[..vcss.find(".a").unwrap()]
491 .bytes()
492 .filter(|&b| b == b'\n')
493 .count();
494 let sfc_line_of_a = 1 + source[..source.find(".a").unwrap()]
495 .bytes()
496 .filter(|&b| b == b'\n')
497 .count();
498 assert_eq!(line_of_a, sfc_line_of_a, "vcss={vcss:?}");
499 }
500
501 #[test]
502 fn virtual_stylesheet_none_without_plain_css_block() {
503 assert!(super::sfc_virtual_stylesheet("<template><div/></template>").is_none());
504 assert!(
505 super::sfc_virtual_stylesheet("<style lang=\"scss\">.a { .b {} }</style>").is_none(),
506 "scss-only SFC yields no virtual stylesheet"
507 );
508 }
509
510 #[test]
511 fn preprocessor_virtual_stylesheet_keeps_sfc_lines() {
512 let source =
513 "<template>\n <div/>\n</template>\n<style lang=\"scss\">\n.a { .b {} }\n</style>";
514 let vcss = super::sfc_preprocessor_virtual_stylesheet(source)
515 .expect("has a preprocessor style block");
516 let line_of_a = 1 + vcss[..vcss.find(".a").unwrap()]
517 .bytes()
518 .filter(|&b| b == b'\n')
519 .count();
520 let sfc_line_of_a = 1 + source[..source.find(".a").unwrap()]
521 .bytes()
522 .filter(|&b| b == b'\n')
523 .count();
524 assert_eq!(line_of_a, sfc_line_of_a, "vcss={vcss:?}");
525 }
526
527 #[test]
528 fn stylus_and_postcss_blocks_reach_neither_virtual_stylesheet() {
529 for source in [
534 "<template>\n <div/>\n</template>\n<style lang=\"stylus\">\n.a\n color red\n</style>",
535 "<template>\n <div/>\n</template>\n<style lang=\"postcss\">\n.a { color: red; }\n</style>",
536 ] {
537 assert!(
538 super::sfc_virtual_stylesheet(source).is_none(),
539 "plain-CSS sheet must skip it: {source:?}"
540 );
541 assert!(
542 super::sfc_preprocessor_virtual_stylesheet(source).is_none(),
543 "preprocessor sheet must skip it: {source:?}"
544 );
545 }
546 }
547
548 #[test]
549 fn hyphenated_class_token_boundary() {
550 let dead = scoped_unused_classes(
552 "<template><div class=\"foo-bar\"></div></template>\n\
553 <style scoped>.foo { color: red; } .foo-bar { color: blue; }</style>",
554 );
555 assert_eq!(dead, vec!["foo".to_string()]);
556 }
557
558 #[test]
559 fn literal_transition_name_credits_generated_classes() {
560 let dead = scoped_unused_classes(
561 "<template><Transition name=\"fade\"><div v-if=\"v\" class=\"panel\"/></Transition></template>\n\
562 <style scoped>.panel {} .fade-enter-active { transition: opacity 1s; } \
563 .fade-enter-from, .fade-leave-to { opacity: 0; } .fade-move {} .stale {}</style>",
564 );
565 assert_eq!(dead, vec!["fade-move".to_string(), "stale".to_string()]);
567 }
568
569 #[test]
570 fn kebab_transition_group_credits_move_class() {
571 let dead = scoped_unused_classes(
572 "<template><transition-group name='list' tag=\"ul\"><li/></transition-group></template>\n\
573 <style scoped>.list-move {} .list-leave-active {} .other-move {}</style>",
574 );
575 assert_eq!(dead, vec!["other-move".to_string()]);
576 }
577
578 #[test]
579 fn unnamed_transition_credits_v_prefix() {
580 let dead = scoped_unused_classes(
581 "<template><TransitionGroup><li/></TransitionGroup></template>\n\
582 <style scoped>.v-enter-active {} .v-move {} .fade-enter-active {}</style>",
583 );
584 assert_eq!(dead, vec!["fade-enter-active".to_string()]);
585 }
586
587 #[test]
588 fn bound_transition_name_with_modifier_credits_nothing() {
589 let dead = scoped_unused_classes(
590 "<template><Transition :name.camel=\"kind\"><div/></Transition>\
591 <Transition v-bind:name.prop=\"kind\"><div/></Transition></template>\n\
592 <style scoped>.v-enter-active {}</style>",
593 );
594 assert_eq!(dead, vec!["v-enter-active".to_string()]);
595 }
596
597 #[test]
598 fn bound_transition_name_credits_nothing() {
599 let dead = scoped_unused_classes(
600 "<template><Transition :name=\"kind\"><div/></Transition></template>\n\
601 <style scoped>.fade-enter-active {} .v-enter-active {}</style>",
602 );
603 assert_eq!(
604 dead,
605 vec![
606 "fade-enter-active".to_string(),
607 "v-enter-active".to_string()
608 ]
609 );
610 }
611
612 #[test]
613 fn transition_prefixed_component_is_not_a_transition() {
614 let dead = scoped_unused_classes(
615 "<template><TransitionWrapper name=\"fade\"/></template>\n\
616 <style scoped>.fade-enter-active {}</style>",
617 );
618 assert_eq!(dead, vec!["fade-enter-active".to_string()]);
619 }
620
621 #[test]
622 fn vue_transition_classes_reads_custom_class_props() {
623 let classes = vue_transition_classes(
624 "<Transition name=\"x\" enter-active-class=\"animate__animated animate__bounce\" \
625 leaveToClass=\"gone\"><p/></Transition>\
626 <TransitionGroup :name=\"n\" move-class=\"shuffle\"/>",
627 );
628 let mut sorted: Vec<&str> = classes.iter().map(String::as_str).collect();
629 sorted.sort_unstable();
630 assert_eq!(
631 sorted,
632 vec![
633 "animate__animated",
634 "animate__bounce",
635 "gone",
636 "shuffle",
637 "x-enter-active",
638 "x-enter-from",
639 "x-enter-to",
640 "x-leave-active",
641 "x-leave-from",
642 "x-leave-to",
643 ]
644 );
645 }
646}