-
-
Notifications
You must be signed in to change notification settings - Fork 637
/
click-events-have-key-events.js
69 lines (60 loc) · 2.17 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
67
68
69
/**
* @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 } from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
import getElementType from '../util/getElementType';
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();
export default {
meta: {
docs: {
url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/click-events-have-key-events.md',
description: 'Enforce a clickable non-interactive element has at least one keyboard event listener.',
},
schema: [schema],
},
create: (context) => {
const elementType = getElementType(context);
return {
JSXOpeningElement: (node) => {
const props = node.attributes;
if (getProp(props, 'onclick') === undefined) {
return;
}
const type = elementType(node);
const requiredProps = ['onkeydown', 'onkeyup', 'onkeypress'];
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;
}
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,
});
},
};
},
};