@jsxtools/eslint-plugin-jsx-a11y
Version:
Static AST checker for accessibility rules on JSX elements for flat ESLint Config.
54 lines (51 loc) • 1.51 kB
JavaScript
import { propName, getPropValue } from './module/jsx-ast-utils.js';
function tryTrim(value) {
return typeof value === "string" ? value.trim() : value;
}
function hasLabellingProp(openingElement, additionalLabellingProps = []) {
const labellingProps = [].concat(
"alt",
// Assume alt is used correctly on an image
"aria-label",
"aria-labelledby",
additionalLabellingProps
);
return openingElement.attributes.some((attribute) => {
if (attribute.type !== "JSXAttribute") {
return true;
}
if (labellingProps.includes(propName(attribute)) && !!tryTrim(getPropValue(attribute))) {
return true;
}
return false;
});
}
function mayHaveAccessibleLabel(root, maxDepth = 1, additionalLabellingProps = []) {
function checkElement(node, depth) {
if (depth > maxDepth) {
return false;
}
if (node.type === "Literal" && !!tryTrim(node.value)) {
return true;
}
if (node.type === "JSXExpressionContainer") {
return true;
}
if (node.type === "JSXText" && !!tryTrim(node.value)) {
return true;
}
if (node.openingElement && hasLabellingProp(node.openingElement, additionalLabellingProps)) {
return true;
}
if (node.children) {
for (let i = 0; i < node.children.length; i += 1) {
if (checkElement(node.children[i], depth + 1)) {
return true;
}
}
}
return false;
}
return checkElement(root, 0);
}
export { mayHaveAccessibleLabel as default };