/
role-supports-aria-props.js
87 lines (75 loc) · 2.65 KB
/
role-supports-aria-props.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
/**
* @fileoverview Enforce that elements with explicit or implicit roles defined contain only
* `aria-*` properties supported by that `role`.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import {
aria,
roles,
} from 'aria-query';
import {
getProp,
getLiteralPropValue,
getPropValue,
elementType,
propName,
} from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
import getImplicitRole from '../util/getImplicitRole';
const errorMessage = (attr, role, tag, isImplicit) => {
if (isImplicit) {
return `The attribute ${attr} is not supported by the role ${role}. \
This role is implicit on the element ${tag}.`;
}
return `The attribute ${attr} is not supported by the role ${role}.`;
};
const schema = generateObjSchema();
export default {
meta: {
docs: {
url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/role-supports-aria-props.md',
},
schema: [schema],
},
create: (context) => ({
JSXOpeningElement: (node) => {
// If role is not explicitly defined, then try and get its implicit role.
const type = elementType(node);
const role = getProp(node.attributes, 'role');
const roleValue = role ? getLiteralPropValue(role) : getImplicitRole(type, node.attributes);
const isImplicit = roleValue && role === undefined;
// If there is no explicit or implicit role, then assume that the element
// can handle the global set of aria-* properties.
// This actually isn't true - should fix in future release.
if (
typeof roleValue !== 'string'
|| roles.get(roleValue) === undefined
) {
return;
}
// Make sure it has no aria-* properties defined outside of its property set.
const {
props: propKeyValues,
} = roles.get(roleValue);
const propertySet = Object.keys(propKeyValues);
const invalidAriaPropsForRole = [...aria.keys()]
.filter((attribute) => propertySet.indexOf(attribute) === -1);
node.attributes.forEach((prop) => {
// Ignore the attribute if its value is null or undefined.
if (getPropValue(prop) == null) return;
// Ignore the attribute if it's a spread.
if (prop.type === 'JSXSpreadAttribute') return;
const name = propName(prop);
if (invalidAriaPropsForRole.indexOf(name) > -1) {
context.report({
node,
message: errorMessage(name, roleValue, type, isImplicit),
});
}
});
},
}),
};