Skip to main content

react_auditor/rules/nextjs/
no_img_element.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 NoImgElement;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-img-element",
11    default_severity: Severity::Warning,
12    category: "nextjs",
13    description: "Use `next/image` instead of `<img>` for optimized images",
14};
15
16impl Rule for NoImgElement {
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 = ImgCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct ImgCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for ImgCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        let is_img = matches!(
39            &el.name,
40            oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "img"
41        );
42        if is_img {
43            let start = el.span.start as usize;
44            let line = self.source[..start].lines().count().max(1);
45            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
46            self.findings.push(RuleFinding {
47                line,
48                column: col + 1,
49                message: "Use `next/image` (`<Image />`) instead of `<img>` for optimized images"
50                    .to_string(),
51            });
52        }
53    }
54}