react_auditor/rules/performance/
html_has_lang.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 HtmlHasLang;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "html-has-lang",
11 default_severity: Severity::Error,
12 category: "accessibility",
13 description: "<html> element must have a lang attribute",
14};
15
16impl Rule for HtmlHasLang {
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 = HtmlLangCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct HtmlLangCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for HtmlLangCollector<'a> {
37 fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38 let is_html = matches!(&el.name, oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "html");
39 if !is_html {
40 return;
41 }
42 let has_lang = 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() == "lang")
45 } else {
46 false
47 }
48 });
49 if !has_lang {
50 let start = el.span.start as usize;
51 let line = self.source[..start].lines().count().max(1);
52 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
53 self.findings.push(RuleFinding {
54 line,
55 column: col + 1,
56 message: "<html> element is missing the lang attribute".to_string(),
57 });
58 }
59 }
60}