@jsxtools/eslint-plugin-jsx-a11y
Version:
Static AST checker for accessibility rules on JSX elements for flat ESLint Config.
64 lines (61 loc) • 2.93 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 isAbstractRole = require('../util/isAbstractRole.cjs');
const isContentEditable = require('../util/isContentEditable.cjs');
const isHiddenFromScreenReader = require('../util/isHiddenFromScreenReader.cjs');
const isInteractiveElement = require('../util/isInteractiveElement.cjs');
const isInteractiveRole = require('../util/isInteractiveRole.cjs');
const isNonInteractiveElement = require('../util/isNonInteractiveElement.cjs');
const isNonInteractiveRole = require('../util/isNonInteractiveRole.cjs');
const isPresentationRole = require('../util/isPresentationRole.cjs');
const errorMessage = "Non-interactive elements should not be assigned mouse or keyboard event listeners.";
const defaultInteractiveProps = [].concat(
jsxAstUtils.eventHandlersByType.focus,
jsxAstUtils.eventHandlersByType.image,
jsxAstUtils.eventHandlersByType.keyboard,
jsxAstUtils.eventHandlersByType.mouse
);
const schema = schemas.generateObjSchema({
handlers: schemas.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(jsxAstUtils.propName(attr)));
}
const hasInteractiveProps = interactiveProps.some((prop) => jsxAstUtils.hasProp(attributes, prop) && jsxAstUtils.getPropValue(jsxAstUtils.getProp(attributes, prop)) != null);
if (!ariaQuery.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
});
}
};
}
};
module.exports = ruleOfNoNoninteractiveElementInteractions;