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