Skip to content

Commit

Permalink
fix(aria-describer): better handling of non-string values (#9959)
Browse files Browse the repository at this point in the history
Currently the `AriaDescriber` assumes that any values being described are going to be strings, however that may not be the case if a value is being passed it directly from the view. These changes add an extra check in order to avoid having to do null checks on consumption (see #9957).
  • Loading branch information
crisbeto authored and jelbourn committed Feb 18, 2018
1 parent e6e2091 commit c819267
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/cdk/a11y/aria-describer/aria-describer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ describe('AriaDescriber', () => {
expect(getMessageElements()).toBe(null);
});

it('should not register non-string values', () => {
expect(() => ariaDescriber.describe(component.element1, null!)).not.toThrow();
expect(getMessageElements()).toBe(null);
});

it('should not throw when trying to remove non-string value', () => {
expect(() => ariaDescriber.removeDescription(component.element1, null!)).not.toThrow();
});

it('should de-dupe a message registered multiple times', () => {
ariaDescriber.describe(component.element1, 'My Message');
ariaDescriber.describe(component.element2, 'My Message');
Expand Down
10 changes: 8 additions & 2 deletions src/cdk/a11y/aria-describer/aria-describer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class AriaDescriber {
* message element.
*/
describe(hostElement: Element, message: string) {
if (hostElement.nodeType !== this._document.ELEMENT_NODE || !message.trim()) {
if (!this._canBeDescribed(hostElement, message)) {
return;
}

Expand All @@ -75,7 +75,7 @@ export class AriaDescriber {

/** Removes the host element's aria-describedby reference to the message element. */
removeDescription(hostElement: Element, message: string) {
if (hostElement.nodeType !== this._document.ELEMENT_NODE || !message.trim()) {
if (!this._canBeDescribed(hostElement, message)) {
return;
}

Expand Down Expand Up @@ -196,6 +196,12 @@ export class AriaDescriber {
return !!messageId && referenceIds.indexOf(messageId) != -1;
}

/** Determines whether a message can be described on a particular element. */
private _canBeDescribed(element: Element, message: string): boolean {
return element.nodeType === this._document.ELEMENT_NODE && message != null &&
!!`${message}`.trim();
}

}

/** @docs-private */
Expand Down

0 comments on commit c819267

Please sign in to comment.