UNPKG

@jsxtools/eslint-plugin-jsx-a11y

Version:

Static AST checker for accessibility rules on JSX elements for flat ESLint Config.

60 lines (57 loc) 2.32 kB
import { dom, roles } from 'aria-query'; import { propName, getLiteralPropValue, getProp } from '../util/module/jsx-ast-utils.js'; import { generateObjSchema } from '../util/schemas.js'; import getElementType from '../util/getElementType.js'; import isSemanticRoleElement from '../util/isSemanticRoleElement.js'; const errorMessage = (role, requiredProps) => `Elements with the ARIA role "${role}" must have the following attributes defined: ${String(requiredProps).toLowerCase()}`; const schema = 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 = propName(attribute).toLowerCase(); if (name !== "role") { return; } const type = elementType(attribute.parent); if (!dom.get(type)) { return; } const roleAttrValue = getLiteralPropValue(attribute); const { attributes } = attribute.parent; if (roleAttrValue === void 0 || roleAttrValue === null) { return; } const normalizedValues = String(roleAttrValue).toLowerCase().split(" "); const validRoles = normalizedValues.filter((val) => [...roles.keys()].indexOf(val) > -1); if (isSemanticRoleElement(type, attributes)) { return; } validRoles.forEach((role) => { const { requiredProps: requiredPropKeyValues } = roles.get(role); const requiredProps = Object.keys(requiredPropKeyValues); if (requiredProps.length > 0) { const hasRequiredProps = requiredProps.every((prop) => getProp(attributes, prop)); if (hasRequiredProps === false) { context.report({ node: attribute, message: errorMessage(role.toLowerCase(), requiredProps) }); } } }); } }; } }; export { ruleOfRoleHasRequiredAriaProps as default };