/
no-noninteractive-tabindex.js
101 lines (94 loc) · 2.85 KB
/
no-noninteractive-tabindex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* @fileoverview Disallow tabindex on static and noninteractive elements
* @author jessebeach
* @flow
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { dom } from 'aria-query';
import type { JSXOpeningElement } from 'ast-types-flow';
import {
elementType,
getProp,
getLiteralPropValue,
} from 'jsx-ast-utils';
import includes from 'array-includes';
import type { ESLintConfig, ESLintContext, ESLintVisitorSelectorConfig } from '../../flow/eslint';
import isInteractiveElement from '../util/isInteractiveElement';
import isInteractiveRole from '../util/isInteractiveRole';
import isNonLiteralProperty from '../util/isNonLiteralProperty';
import { generateObjSchema, arraySchema } from '../util/schemas';
import getTabIndex from '../util/getTabIndex';
const errorMessage = '`tabIndex` should only be declared on interactive elements.';
const schema = generateObjSchema({
roles: {
...arraySchema,
description: 'An array of ARIA roles',
},
tags: {
...arraySchema,
description: 'An array of HTML tag names',
},
});
export default ({
meta: {
docs: {
url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/no-noninteractive-tabindex.md',
},
schema: [schema],
},
create: (context: ESLintContext): ESLintVisitorSelectorConfig => {
const { options } = context;
return {
JSXOpeningElement: (node: JSXOpeningElement) => {
const type = elementType(node);
const { attributes } = node;
const tabIndexProp = getProp(attributes, 'tabIndex');
const tabIndex = getTabIndex(tabIndexProp);
// Early return;
if (typeof tabIndex === 'undefined') {
return;
}
const role = getLiteralPropValue(getProp(node.attributes, 'role'));
if (!dom.has(type)) {
// Do not test higher level JSX components, as we do not know what
// low-level DOM element this maps to.
return;
}
// Allow for configuration overrides.
const {
tags,
roles,
allowExpressionValues,
} = (options[0] || {});
if (tags && includes(tags, type)) {
return;
}
if (roles && includes(roles, role)) {
return;
}
if (
allowExpressionValues === true
&& isNonLiteralProperty(attributes, 'role')
) {
return;
}
if (
isInteractiveElement(type, attributes)
|| isInteractiveRole(type, attributes)
) {
return;
}
if (
tabIndex >= 0
) {
context.report({
node: tabIndexProp,
message: errorMessage,
});
}
},
};
},
}: ESLintConfig);