UNPKG

@jsxtools/eslint-plugin-jsx-a11y

Version:

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

64 lines (61 loc) 2.82 kB
import { dom } from 'aria-query'; import { eventHandlersByType, propName, hasProp, getPropValue, getProp } from '../util/module/jsx-ast-utils.js'; import { generateObjSchema, arraySchema } from '../util/schemas.js'; import getElementType from '../util/getElementType.js'; import isAbstractRole from '../util/isAbstractRole.js'; import isContentEditable from '../util/isContentEditable.js'; import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader.js'; import isInteractiveElement from '../util/isInteractiveElement.js'; import isInteractiveRole from '../util/isInteractiveRole.js'; import isNonInteractiveElement from '../util/isNonInteractiveElement.js'; import isNonInteractiveRole from '../util/isNonInteractiveRole.js'; import isPresentationRole from '../util/isPresentationRole.js'; const errorMessage = "Non-interactive elements should not be assigned mouse or keyboard event listeners."; const defaultInteractiveProps = [].concat( eventHandlersByType.focus, eventHandlersByType.image, eventHandlersByType.keyboard, eventHandlersByType.mouse ); const schema = generateObjSchema({ handlers: arraySchema }); const ruleOfNoNoninteractiveElementInteractions = { meta: { docs: { url: "https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/no-noninteractive-element-interactions.md", description: "Non-interactive elements should not be assigned mouse or keyboard event listeners." }, schema: [schema] }, create: (context) => { const { options } = context; const elementType = getElementType(context); return { JSXOpeningElement: (node) => { let { attributes } = node; const type = elementType(node); const config = options[0] || {}; const interactiveProps = config.handlers || defaultInteractiveProps; if (Object.hasOwn(config, type)) { attributes = attributes.filter((attr) => attr.type !== "JSXSpreadAttribute" && !config[type].includes(propName(attr))); } const hasInteractiveProps = interactiveProps.some((prop) => hasProp(attributes, prop) && getPropValue(getProp(attributes, prop)) != null); if (!dom.has(type)) { return; } if (!hasInteractiveProps || isContentEditable(type, attributes) || isHiddenFromScreenReader(type, attributes) || isPresentationRole(type, attributes)) { return; } if (isInteractiveElement(type, attributes) || isInteractiveRole(type, attributes) || !isNonInteractiveElement(type, attributes) && !isNonInteractiveRole(type, attributes) || isAbstractRole(type, attributes)) { return; } context.report({ node, message: errorMessage }); } }; } }; export { ruleOfNoNoninteractiveElementInteractions as default };