Skip to main content

react_auditor/rules/nextjs/
no_page_link.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 NoPageLink;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-page-link",
11    default_severity: Severity::Warning,
12    category: "nextjs",
13    description: "Use `next/link` instead of `<a>` for internal navigation",
14};
15
16impl Rule for NoPageLink {
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 = PageLinkCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct PageLinkCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for PageLinkCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        let is_a = matches!(
39            &el.name,
40            oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "a"
41        );
42        if !is_a {
43            return;
44        }
45
46        let mut href_value: Option<String> = None;
47        for attr_item in &el.attributes {
48            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item
49                && let oxc_ast::ast::JSXAttributeName::Identifier(ident) = &attr.name
50                && ident.name.as_str() == "href"
51            {
52                if let Some(val) = &attr.value
53                    && let oxc_ast::ast::JSXAttributeValue::StringLiteral(s) = val
54                {
55                    href_value = Some(s.value.to_string());
56                    break;
57                }
58                if let Some(val) = &attr.value
59                    && let oxc_ast::ast::JSXAttributeValue::ExpressionContainer(container) = val
60                    && let oxc_ast::ast::JSXExpression::StringLiteral(s) = &container.expression
61                {
62                    href_value = Some(s.value.to_string());
63                    break;
64                }
65            }
66        }
67
68        if let Some(href) = href_value
69            && (href.starts_with('/') || href.starts_with('.'))
70        {
71            let start = el.span.start as usize;
72            let line = self.source[..start].lines().count().max(1);
73            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
74            self.findings.push(RuleFinding {
75                line,
76                column: col + 1,
77                message: format!(
78                    "Use `next/link` (`<Link href=\"{href}\">`) instead of `<a>` for internal navigation"
79                ),
80            });
81        }
82    }
83}