Skip to main content

react_auditor/rules/nextjs/
no_head_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 NoHeadElement;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-head-element",
11    default_severity: Severity::Warning,
12    category: "nextjs",
13    description: "Use `next/head` (`<Head>`) instead of `<head>`",
14};
15
16impl Rule for NoHeadElement {
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 = HeadCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct HeadCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for HeadCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        let is_head = matches!(
39            &el.name,
40            oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "head"
41        );
42        if is_head {
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/head` (`<Head />`) instead of `<head>`".to_string(),
50            });
51        }
52    }
53}