Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attributes setting #979

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -103,6 +103,9 @@ Add `plugin:jsx-a11y/recommended` or `plugin:jsx-a11y/strict` in `extends`:
"CustomButton": "button",
"MyButton": "button",
"RoundButton": "button"
},
"attributes": {
"for": ["htmlFor", "for"]
}
}
}
Expand All @@ -113,6 +116,10 @@ Add `plugin:jsx-a11y/recommended` or `plugin:jsx-a11y/strict` in `extends`:

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
Expand Up @@ -35,11 +35,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
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
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
Expand Up @@ -10,7 +10,8 @@ export type ESLintSettings = {
[string]: mixed,
'jsx-a11y'?: {
polymorphicPropName?: string,
components?: {[string]: string},
components?: { [string]: string },
attributes?: { for?: string[] },
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the name “attributes” or “htmlForAttributes”?

},
}

Expand Down
21 changes: 15 additions & 6 deletions src/rules/label-has-associated-control.js
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 @@ -35,11 +35,18 @@ const schema = generateObjSchema({
},
});

const validateId = (node) => {
const htmlForAttr = getProp(node.attributes, 'htmlFor');
const htmlForValue = getPropValue(htmlForAttr);
const validateId = (node, htmlForAttributes) => {
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 htmlForAttr !== false && !!htmlForValue;
}
}

return false;
};

export default ({
Expand All @@ -52,7 +59,9 @@ export default ({
},

create: (context: ESLintContext): ESLintVisitorSelectorConfig => {
const { settings } = context;
const options = context.options[0] || {};
const htmlForAttributes = settings['jsx-a11y']?.attributes?.for ?? ['htmlFor'];
const labelComponents = options.labelComponents || [];
const assertType = options.assert || 'either';
const componentNames = ['label'].concat(labelComponents);
Expand All @@ -75,7 +84,7 @@ export default ({
options.depth === undefined ? 2 : options.depth,
25,
);
const hasLabelId = validateId(node.openingElement);
const hasLabelId = validateId(node.openingElement, htmlForAttributes);
// Check for multiple control components.
const hasNestedControl = controlComponents.some((name) => mayContainChildComponent(
node,
Expand Down
33 changes: 21 additions & 12 deletions src/rules/label-has-for.js
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,40 +45,47 @@ function validateNesting(node) {
return false;
}

const validateId = (node) => {
const htmlForAttr = getProp(node.attributes, 'htmlFor');
const htmlForValue = getPropValue(htmlForAttr);
const validateId = (node, htmlForAttributes) => {
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 htmlForAttr !== false && !!htmlForValue;
}
}

return false;
};

const validate = (node, required, allowChildren, elementType) => {
const validate = (node, required, allowChildren, elementType, htmlForAttributes) => {
if (allowChildren === true) {
return hasAccessibleChild(node.parent, elementType);
}
if (required === 'nesting') {
return validateNesting(node);
}
return validateId(node);
return validateId(node, htmlForAttributes);
};

const getValidityStatus = (node, required, allowChildren, elementType) => {
const getValidityStatus = (node, required, allowChildren, elementType, htmlForAttributes) => {
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, htmlForAttributes));
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, htmlForAttributes));
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, htmlForAttributes);
const message = !isValid
? `Form label must have the following type of associated control: ${required}`
: null;
Expand All @@ -100,7 +107,9 @@ export default {
const elementType = getElementType(context);
return {
JSXOpeningElement: (node) => {
const { settings } = context;
const options = context.options[0] || {};
const htmlForAttributes = settings['jsx-a11y']?.attributes?.for ?? ['htmlFor'];
const componentOptions = options.components || [];
const typesToValidate = ['label'].concat(componentOptions);
const nodeType = elementType(node);
Expand All @@ -113,7 +122,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, htmlForAttributes);
if (!isValid) {
context.report({
node,
Expand Down