@jsxtools/eslint-plugin-jsx-a11y
Version:
Static AST checker for accessibility rules on JSX elements for flat ESLint Config.
60 lines (57 loc) • 2.37 kB
JavaScript
const ariaQuery = require('aria-query');
const jsxAstUtils = require('../util/module/jsx-ast-utils.cjs');
const schemas = require('../util/schemas.cjs');
const getElementType = require('../util/getElementType.cjs');
const isSemanticRoleElement = require('../util/isSemanticRoleElement.cjs');
const errorMessage = (role, requiredProps) => `Elements with the ARIA role "${role}" must have the following attributes defined: ${String(requiredProps).toLowerCase()}`;
const schema = schemas.generateObjSchema();
const ruleOfRoleHasRequiredAriaProps = {
meta: {
docs: {
url: "https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/role-has-required-aria-props.md",
description: "Enforce that elements with ARIA roles must have all required attributes for that role."
},
schema: [schema]
},
create: (context) => {
const elementType = getElementType(context);
return {
JSXAttribute: (attribute) => {
const name = jsxAstUtils.propName(attribute).toLowerCase();
if (name !== "role") {
return;
}
const type = elementType(attribute.parent);
if (!ariaQuery.dom.get(type)) {
return;
}
const roleAttrValue = jsxAstUtils.getLiteralPropValue(attribute);
const { attributes } = attribute.parent;
if (roleAttrValue === void 0 || roleAttrValue === null) {
return;
}
const normalizedValues = String(roleAttrValue).toLowerCase().split(" ");
const validRoles = normalizedValues.filter((val) => [...ariaQuery.roles.keys()].indexOf(val) > -1);
if (isSemanticRoleElement(type, attributes)) {
return;
}
validRoles.forEach((role) => {
const {
requiredProps: requiredPropKeyValues
} = ariaQuery.roles.get(role);
const requiredProps = Object.keys(requiredPropKeyValues);
if (requiredProps.length > 0) {
const hasRequiredProps = requiredProps.every((prop) => jsxAstUtils.getProp(attributes, prop));
if (hasRequiredProps === false) {
context.report({
node: attribute,
message: errorMessage(role.toLowerCase(), requiredProps)
});
}
}
});
}
};
}
};
module.exports = ruleOfRoleHasRequiredAriaProps;