Skip to main content

react_auditor/rules/performance/
label_associated.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 LabelAssociated;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "label-associated",
11    default_severity: Severity::Warning,
12    category: "accessibility",
13    description: "Form inputs should have associated labels",
14};
15
16impl Rule for LabelAssociated {
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 = LabelCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct LabelCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for LabelCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        let is_input = matches!(&el.name, oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "input" || id.name.as_str() == "select" || id.name.as_str() == "textarea");
39        if !is_input {
40            return;
41        }
42        let has_aria_label = 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() == "aria-label" || id.name.as_str() == "aria-labelledby")
45            } else {
46                false
47            }
48        });
49        let has_id = el.attributes.iter().any(|attr| {
50            if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr {
51                matches!(&a.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "id")
52            } else {
53                false
54            }
55        });
56        if !has_aria_label && !has_id {
57            let start = el.span.start as usize;
58            let line = self.source[..start].lines().count().max(1);
59            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
60            self.findings.push(RuleFinding {
61                line,
62                column: col + 1,
63                message: "Form input is missing an associated `<label>` or `aria-label`"
64                    .to_string(),
65            });
66        }
67    }
68}