@jsxtools/eslint-plugin-jsx-a11y
Version:
Static AST checker for accessibility rules on JSX elements for flat ESLint Config.
82 lines (79 loc) • 2.79 kB
JavaScript
import { dom } from 'aria-query';
import { getProp, getLiteralPropValue } from '../util/module/jsx-ast-utils.js';
import getElementType from '../util/getElementType.js';
import isInteractiveElement from '../util/isInteractiveElement.js';
import isInteractiveRole from '../util/isInteractiveRole.js';
import isNonLiteralProperty from '../util/isNonLiteralProperty.js';
import { generateObjSchema, arraySchema } from '../util/schemas.js';
import getTabIndex from '../util/getTabIndex.js';
const errorMessage = "`tabIndex` should only be declared on interactive elements.";
const schema = generateObjSchema({
roles: {
...arraySchema,
description: "An array of ARIA roles"
},
tags: {
...arraySchema,
description: "An array of HTML tag names"
}
});
const ruleOfNoNoninteractiveTabindex = {
meta: {
docs: {
url: "https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/no-noninteractive-tabindex.md",
description: "`tabIndex` should only be declared on interactive elements."
},
schema: [schema]
},
create: (context) => {
const { options } = context;
const elementType = getElementType(context);
return {
JSXOpeningElement: (node) => {
const type = elementType(node);
const { attributes } = node;
const tabIndexProp = getProp(attributes, "tabIndex");
const tabIndex = getTabIndex(tabIndexProp);
if (typeof tabIndex === "undefined") {
return;
}
const role = getLiteralPropValue(getProp(node.attributes, "role"));
if (!dom.has(type)) {
return;
}
const {
tags,
roles,
allowExpressionValues
} = options[0] || {};
if (tags && tags.includes(type)) {
return;
}
if (roles && roles.includes(role)) {
return;
}
if (allowExpressionValues === true && isNonLiteralProperty(attributes, "role")) {
const roleProp = getProp(attributes, "role");
if (roleProp && roleProp.type === "JSXAttribute" && roleProp.value.type === "JSXExpressionContainer") {
if (roleProp.value.expression.type === "ConditionalExpression") {
if (roleProp.value.expression.consequent.type === "Literal" && roleProp.value.expression.alternate.type === "Literal") {
return;
}
}
}
return;
}
if (isInteractiveElement(type, attributes) || isInteractiveRole(type, attributes)) {
return;
}
if (tabIndex >= 0) {
context.report({
node: tabIndexProp,
message: errorMessage
});
}
}
};
}
};
export { ruleOfNoNoninteractiveTabindex as default };