react_auditor/rules/performance/
prefer_fragments.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct PreferFragments;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "prefer-fragments",
11 default_severity: Severity::Warning,
12 category: "performance",
13 description: "Use `<></>` over unnecessary wrapper divs",
14};
15
16impl Rule for PreferFragments {
17 fn meta(&self) -> &RuleMeta {
18 &RULE_META
19 }
20
21 fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22 let mut collector = FragmentCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct FragmentCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for FragmentCollector<'a> {
37 fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38 let is_div = matches!(&el.name, oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "div");
39 if !is_div {
40 return;
41 }
42 let has_class = el.attributes.iter().any(|attr| {
43 if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr {
44 matches!(&a.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "className" || id.name.as_str() == "class")
45 } else {
46 false
47 }
48 });
49 if has_class {
50 return;
51 }
52 let has_style = el.attributes.iter().any(|attr| {
53 if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr {
54 matches!(&a.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "style")
55 } else {
56 false
57 }
58 });
59 if !has_class && !has_style {
60 let start = el.span.start as usize;
61 let line = self.source[..start].lines().count().max(1);
62 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
63 self.findings.push(RuleFinding {
64 line,
65 column: col + 1,
66 message: "Unnecessary `<div>` wrapper — use `<></>` Fragment instead".to_string(),
67 });
68 }
69 }
70}