forked from jsx-eslint/eslint-plugin-jsx-a11y
/
prefer-tag-over-role.js
88 lines (73 loc) · 2.22 KB
/
prefer-tag-over-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
87
88
import { roleElements } from 'aria-query';
import { getProp, getPropValue } from 'jsx-ast-utils';
import getElementType from '../util/getElementType';
import { generateObjSchema } from '../util/schemas';
const errorMessage = 'Use {{tag}} instead of the "{{role}}" role to ensure accessibility across all devices.';
const schema = generateObjSchema();
const formatTag = (tag) => {
if (!tag.attributes) {
return `<${tag.name}>`;
}
const [attribute] = tag.attributes;
const value = attribute.value ? `"${attribute.value}"` : '...';
return `<${tag.name} ${attribute.name}=${value}>`;
};
const getLastPropValue = (rawProp) => {
const propValue = getPropValue(rawProp);
if (!propValue) {
return propValue;
}
const lastSpaceIndex = propValue.lastIndexOf(' ');
return lastSpaceIndex === -1
? propValue
: propValue.substring(lastSpaceIndex + 1);
};
export default {
meta: {
docs: {
description: 'Enforces using semantic DOM elements over the ARIA `role` property.',
url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/prefer-tag-over-role.md',
},
schema: [schema],
},
create: (context) => {
const elementType = getElementType(context);
return {
JSXOpeningElement: (node) => {
const role = getLastPropValue(getProp(node.attributes, 'role'));
if (!role) {
return;
}
const matchedTagsSet = roleElements.get(role);
if (!matchedTagsSet) {
return;
}
const matchedTags = Array.from(matchedTagsSet);
if (
matchedTags.some(
(matchedTag) => matchedTag.name === elementType(node),
)
) {
return;
}
context.report({
data: {
tag:
matchedTags.length === 1
? formatTag(matchedTags[0])
: [
matchedTags
.slice(0, matchedTags.length - 1)
.map(formatTag)
.join(', '),
formatTag(matchedTags[matchedTags.length - 1]),
].join(', or '),
role,
},
node,
message: errorMessage,
});
},
};
},
};