Skip to main content

react_auditor/rules/react/
no_inline_styles.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoInlineStyles;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-inline-styles",
11    default_severity: Severity::Warning,
12    category: "react",
13    description: "Avoid inline `style` prop — use CSS classes",
14};
15
16impl Rule for NoInlineStyles {
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 = InlineStyleCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct InlineStyleCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for InlineStyleCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        for attr_item in &el.attributes {
39            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item {
40                let is_style = matches!(
41                    &attr.name,
42                    oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "style"
43                );
44
45                if is_style && attr.value.is_some() {
46                    let start = attr.span.start as usize;
47                    let line = self.source[..start].lines().count().max(1);
48                    let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
49
50                    self.findings.push(RuleFinding {
51                        line,
52                        column: col + 1,
53                        message: "Avoid inline `style` prop, use a CSS class instead".to_string(),
54                    });
55                }
56            }
57        }
58    }
59}