/
click-events-have-key-events.js
66 lines (57 loc) · 1.99 KB
/
click-events-have-key-events.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
/**
* @fileoverview Enforce a clickable non-interactive element has at least 1 keyboard event listener.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { dom } from 'aria-query';
import { getProp, hasAnyProp, elementType } from 'jsx-ast-utils';
import includes from 'array-includes';
import { generateObjSchema } from '../util/schemas';
import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader';
import isInteractiveElement from '../util/isInteractiveElement';
import isPresentationRole from '../util/isPresentationRole';
const errorMessage = 'Visible, non-interactive elements with click handlers must have at least one keyboard listener.';
const schema = generateObjSchema();
const domElements = [...dom.keys()];
export default {
meta: {
docs: {
url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/click-events-have-key-events.md',
},
schema: [schema],
},
create: (context) => ({
JSXOpeningElement: (node) => {
const props = node.attributes;
if (getProp(props, 'onclick') === undefined) {
return;
}
const type = elementType(node);
const requiredProps = ['onkeydown', 'onkeyup', 'onkeypress'];
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;
}
if (
isHiddenFromScreenReader(type, props)
|| isPresentationRole(type, props)
) {
return;
}
if (isInteractiveElement(type, props)) {
return;
}
if (hasAnyProp(props, requiredProps)) {
return;
}
// Visible, non-interactive elements with click handlers require one keyboard event listener.
context.report({
node,
message: errorMessage,
});
},
}),
};