Skip to content

Commit

Permalink
[New] add attributes setting
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza authored and ljharb committed Sep 4, 2024
1 parent 83fd9c4 commit a1ee7f8
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 25 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ Add `plugin:jsx-a11y/recommended` or `plugin:jsx-a11y/strict` in `extends`:
"CustomButton": "button",
"MyButton": "button",
"RoundButton": "button"
},
"attributes": {
"for": ["htmlFor", "for"]
}
}
}
Expand Down Expand Up @@ -202,6 +205,11 @@ module.exports = [

To enable your custom components to be checked as DOM elements, you can set global settings in your configuration file by mapping each custom component name to a DOM element type.

#### Attribute Mapping

To configure the JSX property to use for attribute checking, you can set global settings in your configuration file by mapping each DOM attribute to the JSX property you want to check.
For example, you may want to allow the `for` attribute in addition to the `htmlFor` attribute for checking label associations.

#### Polymorphic Components

You can optionally use the `polymorphicPropName` setting to define the prop your code uses to create polymorphic components.
Expand Down
12 changes: 12 additions & 0 deletions __tests__/src/rules/label-has-associated-control-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,23 @@ const componentsSettings = {
},
};

const attributesSettings = {
'jsx-a11y': {
attributes: {
for: ['htmlFor', 'for'],
},
},
};

const htmlForValid = [
{ code: '<label htmlFor="js_id"><span><span><span>A label</span></span></span></label>', options: [{ depth: 4 }] },
{ code: '<label htmlFor="js_id" aria-label="A label" />' },
{ code: '<label htmlFor="js_id" aria-labelledby="A label" />' },
{ code: '<div><label htmlFor="js_id">A label</label><input id="js_id" /></div>' },
{ code: '<label for="js_id"><span><span><span>A label</span></span></span></label>', options: [{ depth: 4 }], settings: attributesSettings },
{ code: '<label for="js_id" aria-label="A label" />', settings: attributesSettings },
{ code: '<label for="js_id" aria-labelledby="A label" />', settings: attributesSettings },
{ code: '<div><label for="js_id">A label</label><input id="js_id" /></div>', settings: attributesSettings },
// Custom label component.
{ code: '<CustomLabel htmlFor="js_id" aria-label="A label" />', options: [{ labelComponents: ['CustomLabel'] }] },
{ code: '<CustomLabel htmlFor="js_id" label="A label" />', options: [{ labelAttributes: ['label'], labelComponents: ['CustomLabel'] }] },
Expand Down
12 changes: 12 additions & 0 deletions __tests__/src/rules/label-has-for-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,28 @@ const optionsChildrenAllowed = [{
allowChildren: true,
}];

const attributesSettings = {
'jsx-a11y': {
attributes: {
for: ['htmlFor', 'for'],
},
},
};

ruleTester.run('label-has-for', rule, {
valid: parsers.all([].concat(
// DEFAULT ELEMENT 'label' TESTS
{ code: '<div />' },
{ code: '<label htmlFor="foo"><input /></label>' },
{ code: '<label htmlFor="foo"><textarea /></label>' },
{ code: '<label for="foo"><input /></label>', settings: attributesSettings },
{ code: '<label for="foo"><textarea /></label>', settings: attributesSettings },
{ code: '<Label />' }, // lower-case convention refers to real HTML elements.
{ code: '<Label htmlFor="foo" />' },
{ code: '<Label for="foo" />', settings: attributesSettings },
{ code: '<Descriptor />' },
{ code: '<Descriptor htmlFor="foo">Test!</Descriptor>' },
{ code: '<Descriptor for="foo">Test!</Descriptor>', settings: attributesSettings },
{ code: '<UX.Layout>test</UX.Layout>' },

// CUSTOM ELEMENT ARRAY OPTION TESTS
Expand Down
2 changes: 1 addition & 1 deletion docs/rules/label-has-for.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Enforce label tags have associated control.
There are two supported ways to associate a label with a control:

- nesting: by wrapping a control in a label tag
- id: by using the prop `htmlFor` as in `htmlFor=[ID of control]`
- id: by using the prop `htmlFor` (or any configured attribute) as in `htmlFor=[ID of control]`

To fully cover 100% of assistive devices, you're encouraged to validate for both nesting and id.

Expand Down
3 changes: 2 additions & 1 deletion flow/eslint.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export type ESLintSettings = {
[string]: mixed,
'jsx-a11y'?: {
polymorphicPropName?: string,
components?: {[string]: string},
components?: { [string]: string },
attributes?: { for?: string[] },
},
}

Expand Down
24 changes: 17 additions & 7 deletions src/rules/label-has-associated-control.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// Rule Definition
// ----------------------------------------------------------------------------

import { getProp, getPropValue } from 'jsx-ast-utils';
import { hasProp, getProp, getPropValue } from 'jsx-ast-utils';
import type { JSXElement } from 'ast-types-flow';
import { generateObjSchema, arraySchema } from '../util/schemas';
import type { ESLintConfig, ESLintContext, ESLintVisitorSelectorConfig } from '../../flow/eslint';
Expand All @@ -36,12 +36,22 @@ const schema = generateObjSchema({
},
});

const validateId = (node) => {
const htmlForAttr = getProp(node.attributes, 'htmlFor');
const htmlForValue = getPropValue(htmlForAttr);
function validateID(node, context) {
const { settings } = context;
const htmlForAttributes = settings['jsx-a11y']?.attributes?.for ?? ['htmlFor'];

return htmlForAttr !== false && !!htmlForValue;
};
for (let i = 0; i < htmlForAttributes.length; i += 1) {
const attribute = htmlForAttributes[i];
if (hasProp(node.attributes, attribute)) {
const htmlForAttr = getProp(node.attributes, attribute);
const htmlForValue = getPropValue(htmlForAttr);

return htmlForAttr !== false && !!htmlForValue;
}
}

return false;
}

export default ({
meta: {
Expand Down Expand Up @@ -76,7 +86,7 @@ export default ({
options.depth === undefined ? 2 : options.depth,
25,
);
const hasLabelId = validateId(node.openingElement);
const hasLabelId = validateID(node.openingElement, context);
// Check for multiple control components.
const hasNestedControl = controlComponents.some((name) => mayContainChildComponent(
node,
Expand Down
42 changes: 26 additions & 16 deletions src/rules/label-has-for.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// Rule Definition
// ----------------------------------------------------------------------------

import { getProp, getPropValue } from 'jsx-ast-utils';
import { hasProp, getProp, getPropValue } from 'jsx-ast-utils';
import { generateObjSchema, arraySchema, enumArraySchema } from '../util/schemas';
import getElementType from '../util/getElementType';
import hasAccessibleChild from '../util/hasAccessibleChild';
Expand Down Expand Up @@ -45,45 +45,55 @@ function validateNesting(node) {
return false;
}

const validateId = (node) => {
const htmlForAttr = getProp(node.attributes, 'htmlFor');
const htmlForValue = getPropValue(htmlForAttr);
function validateID({ attributes }, context) {
const { settings } = context;
const htmlForAttributes = settings['jsx-a11y']?.attributes?.for ?? ['htmlFor'];

return htmlForAttr !== false && !!htmlForValue;
};
for (let i = 0; i < htmlForAttributes.length; i += 1) {
const attribute = htmlForAttributes[i];
if (hasProp(attributes, attribute)) {
const htmlForAttr = getProp(attributes, attribute);
const htmlForValue = getPropValue(htmlForAttr);

return htmlForAttr !== false && !!htmlForValue;
}
}

const validate = (node, required, allowChildren, elementType) => {
return false;
}

function validate(node, required, allowChildren, elementType, context) {
if (allowChildren === true) {
return hasAccessibleChild(node.parent, elementType);
}
if (required === 'nesting') {
return validateNesting(node);
}
return validateId(node);
};
return validateID(node, context);
}

const getValidityStatus = (node, required, allowChildren, elementType) => {
function getValidityStatus(node, required, allowChildren, elementType, context) {
if (Array.isArray(required.some)) {
const isValid = required.some.some((rule) => validate(node, rule, allowChildren, elementType));
const isValid = required.some.some((rule) => validate(node, rule, allowChildren, elementType, context));
const message = !isValid
? `Form label must have ANY of the following types of associated control: ${required.some.join(', ')}`
: null;
return { isValid, message };
}
if (Array.isArray(required.every)) {
const isValid = required.every.every((rule) => validate(node, rule, allowChildren, elementType));
const isValid = required.every.every((rule) => validate(node, rule, allowChildren, elementType, context));
const message = !isValid
? `Form label must have ALL of the following types of associated control: ${required.every.join(', ')}`
: null;
return { isValid, message };
}

const isValid = validate(node, required, allowChildren, elementType);
const isValid = validate(node, required, allowChildren, elementType, context);
const message = !isValid
? `Form label must have the following type of associated control: ${required}`
: null;
return { isValid, message };
};
}

export default {
meta: {
Expand All @@ -99,7 +109,7 @@ export default {
create: (context) => {
const elementType = getElementType(context);
return {
JSXOpeningElement: (node) => {
JSXOpeningElement(node) {
const options = context.options[0] || {};
const componentOptions = options.components || [];
const typesToValidate = ['label'].concat(componentOptions);
Expand All @@ -113,7 +123,7 @@ export default {
const required = options.required || { every: ['nesting', 'id'] };
const allowChildren = options.allowChildren || false;

const { isValid, message } = getValidityStatus(node, required, allowChildren, elementType);
const { isValid, message } = getValidityStatus(node, required, allowChildren, elementType, context);
if (!isValid) {
context.report({
node,
Expand Down

0 comments on commit a1ee7f8

Please sign in to comment.