/
heading-has-content.js
60 lines (51 loc) · 1.58 KB
/
heading-has-content.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
/**
* @fileoverview Enforce heading (h1, h2, etc) elements contain accessible content.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { elementType } from 'jsx-ast-utils';
import { generateObjSchema, arraySchema } from '../util/schemas';
import hasAccessibleChild from '../util/hasAccessibleChild';
import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader';
const errorMessage = 'Headings must have content and the content must be accessible by a screen reader.';
const headings = [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
];
const schema = generateObjSchema({ components: arraySchema });
export default {
meta: {
docs: {
url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/heading-has-content.md',
},
schema: [schema],
},
create: (context) => ({
JSXOpeningElement: (node) => {
const options = context.options[0] || {};
const componentOptions = options.components || [];
const typeCheck = headings.concat(componentOptions);
const nodeType = elementType(node);
// Only check 'h*' elements and custom types.
if (typeCheck.indexOf(nodeType) === -1) {
return;
}
if (hasAccessibleChild(node.parent)) {
return;
}
if (isHiddenFromScreenReader(nodeType, node.attributes)) {
return;
}
context.report({
node,
message: errorMessage,
});
},
}),
};