UNPKG

@jsxtools/eslint-plugin-jsx-a11y

Version:

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

82 lines (79 loc) 2.87 kB
const ariaQuery = require('aria-query'); const jsxAstUtils = require('../util/module/jsx-ast-utils.cjs'); const getElementType = require('../util/getElementType.cjs'); const isInteractiveElement = require('../util/isInteractiveElement.cjs'); const isInteractiveRole = require('../util/isInteractiveRole.cjs'); const isNonLiteralProperty = require('../util/isNonLiteralProperty.cjs'); const schemas = require('../util/schemas.cjs'); const getTabIndex = require('../util/getTabIndex.cjs'); const errorMessage = "`tabIndex` should only be declared on interactive elements."; const schema = schemas.generateObjSchema({ roles: { ...schemas.arraySchema, description: "An array of ARIA roles" }, tags: { ...schemas.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 = jsxAstUtils.getProp(attributes, "tabIndex"); const tabIndex = getTabIndex(tabIndexProp); if (typeof tabIndex === "undefined") { return; } const role = jsxAstUtils.getLiteralPropValue(jsxAstUtils.getProp(node.attributes, "role")); if (!ariaQuery.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 = jsxAstUtils.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 }); } } }; } }; module.exports = ruleOfNoNoninteractiveTabindex;