Skip to content

Commit

Permalink
[Fix] control-has-associated-label: don't accept whitespace as an a…
Browse files Browse the repository at this point in the history
…ccessible label

Fixes #918
  • Loading branch information
wobo-nate committed Jan 25, 2023
1 parent 20b082a commit 93f7885
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
16 changes: 16 additions & 0 deletions __tests__/src/util/mayHaveAccessibleLabel-test.js
Expand Up @@ -41,6 +41,14 @@ describe('mayHaveAccessibleLabel', () => {
JSXAttributeMock('aria-label', ''),
], []))).toBe(false);
});
it('aria-label with only whitespace, should return false', () => {
expect(mayHaveAccessibleLabel(JSXElementMock('div', [
JSXAttributeMock('aria-label', ' '),
], []))).toBe(false);
expect(mayHaveAccessibleLabel(JSXElementMock('div', [
JSXAttributeMock('aria-label', '\n'),
], []))).toBe(false);
});
it('aria-labelledby, should return true', () => {
expect(mayHaveAccessibleLabel(JSXElementMock('div', [
JSXAttributeMock('aria-labelledby', 'elementId'),
Expand Down Expand Up @@ -78,6 +86,14 @@ describe('mayHaveAccessibleLabel', () => {
LiteralMock('A fancy label'),
]))).toBe(true);
});
it('Literal whitespace, should return false', () => {
expect(mayHaveAccessibleLabel(JSXElementMock('div', [], [
LiteralMock(' '),
]))).toBe(false);
expect(mayHaveAccessibleLabel(JSXElementMock('div', [], [
LiteralMock('\n'),
]))).toBe(false);
});
it('JSXText, should return true', () => {
expect(mayHaveAccessibleLabel(JSXElementMock('div', [], [
JSXTextMock('A fancy label'),
Expand Down
10 changes: 7 additions & 3 deletions src/util/mayHaveAccessibleLabel.js
Expand Up @@ -12,6 +12,10 @@ import includes from 'array-includes';
import { getPropValue, propName } from 'jsx-ast-utils';
import type { JSXOpeningElement, Node } from 'ast-types-flow';

function tryTrim(value: any) {
return typeof value === 'string' ? value.trim() : value;
}

function hasLabellingProp(
openingElement: JSXOpeningElement,
additionalLabellingProps?: Array<string> = [],
Expand All @@ -30,7 +34,7 @@ function hasLabellingProp(
// Attribute matches.
if (
includes(labellingProps, propName(attribute))
&& !!getPropValue(attribute)
&& !!tryTrim(getPropValue(attribute))
) {
return true;
}
Expand All @@ -52,7 +56,7 @@ export default function mayHaveAccessibleLabel(
return false;
}
// Check for literal text.
if (node.type === 'Literal' && !!node.value) {
if (node.type === 'Literal' && !!tryTrim(node.value)) {
return true;
}
// Assume an expression container renders a label. It is the best we can
Expand All @@ -62,7 +66,7 @@ export default function mayHaveAccessibleLabel(
}
// Check for JSXText.
// $FlowFixMe Remove after updating ast-types-flow
if (node.type === 'JSXText' && !!node.value) {
if (node.type === 'JSXText' && !!tryTrim(node.value)) {
return true;
}
// Check for labelling props.
Expand Down

0 comments on commit 93f7885

Please sign in to comment.