/
no-noninteractive-element-to-interactive-role.js
86 lines (79 loc) · 2.73 KB
/
no-noninteractive-element-to-interactive-role.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
/**
* @fileoverview Disallow inherently non-interactive elements to be assigned
* interactive roles.
* @author Jesse Beach
* @flow
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { dom } from 'aria-query';
import {
elementType,
propName,
} from 'jsx-ast-utils';
import type { JSXIdentifier } from 'ast-types-flow';
import includes from 'array-includes';
import has from 'has';
import type { ESLintConfig, ESLintContext, ESLintVisitorSelectorConfig } from '../../flow/eslint';
import type { ESLintJSXAttribute } from '../../flow/eslint-jsx';
import getExplicitRole from '../util/getExplicitRole';
import isNonInteractiveElement from '../util/isNonInteractiveElement';
import isInteractiveRole from '../util/isInteractiveRole';
const errorMessage = 'Non-interactive elements should not be assigned interactive roles.';
const domElements = [...dom.keys()];
export default ({
meta: {
docs: {
url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/no-noninteractive-element-to-interactive-role.md',
description: 'Non-interactive elements should not be assigned interactive roles.',
errorOptions: true,
},
schema: [{
type: 'object',
additionalProperties: {
type: 'array',
items: {
type: 'string',
},
uniqueItems: true,
},
}],
},
create: (context: ESLintContext): ESLintVisitorSelectorConfig => {
const { options } = context;
return {
JSXAttribute: (attribute: ESLintJSXAttribute) => {
const attributeName: JSXIdentifier = propName(attribute);
// $FlowFixMe: [TODO] Mark propName as a JSXIdentifier, not a string.
if (attributeName !== 'role') {
return;
}
const node = attribute.parent;
const { attributes } = node;
const type = elementType(node);
const role = getExplicitRole(type, node.attributes);
if (!includes(domElements, type)) {
// Do not test higher level JSX components, as we do not know what
// low-level DOM element this maps to.
return;
}
// Allow overrides from rule configuration for specific elements and
// roles.
const allowedRoles = (options[0] || {});
if (has(allowedRoles, type) && includes(allowedRoles[type], role)) {
return;
}
if (
isNonInteractiveElement(type, attributes)
&& isInteractiveRole(type, attributes)
) {
context.report({
node: attribute,
message: errorMessage,
});
}
},
};
},
}: ESLintConfig);