react_auditor/rules/performance/
tabindex_no_positive.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 TabindexNoPositive;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "tabindex-no-positive",
11 default_severity: Severity::Error,
12 category: "accessibility",
13 description: "Avoid positive tabIndex values; only 0 and -1 are valid",
14};
15
16impl Rule for TabindexNoPositive {
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 = TabindexCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct TabindexCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for TabindexCollector<'a> {
37 fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38 for attr in &el.attributes {
39 if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr
40 && let oxc_ast::ast::JSXAttributeName::Identifier(id) = &a.name
41 && id.name.as_str() == "tabIndex"
42 && let Some(value) = &a.value
43 {
44 if let oxc_ast::ast::JSXAttributeValue::ExpressionContainer(expr) = value
45 && let Some(oxc_ast::ast::Expression::NumericLiteral(n)) =
46 expr.expression.as_expression()
47 && n.value > 0.0
48 {
49 let start = el.span.start as usize;
50 let line = self.source[..start].lines().count().max(1);
51 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
52 self.findings.push(RuleFinding {
53 line,
54 column: col + 1,
55 message: format!(
56 "tabIndex={} is positive; use 0 or -1 only",
57 n.value as i64
58 ),
59 });
60 }
61 if let oxc_ast::ast::JSXAttributeValue::StringLiteral(s) = value
62 && let Ok(n) = s.value.parse::<i64>()
63 && n > 0
64 {
65 let start = el.span.start as usize;
66 let line = self.source[..start].lines().count().max(1);
67 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
68 self.findings.push(RuleFinding {
69 line,
70 column: col + 1,
71 message: format!("tabIndex=\"{}\" is positive; use 0 or -1 only", n),
72 });
73 }
74 }
75 }
76 }
77}