Skip to content
This repository has been archived by the owner on Jan 13, 2025. It is now read-only.

Commit

Permalink
feat(dom): Create announcer utility
Browse files Browse the repository at this point in the history
Provide an announcer utility for verbalizing messages to screen readers via aria-live regions
  • Loading branch information
patrickrodee authored Jan 28, 2020
1 parent 47cdff8 commit 32c1df1
Show file tree
Hide file tree
Showing 3 changed files with 183 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/mdc-dom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,12 @@ Method Signature | Description
--- | ---
`trapFocus() => void` | Traps focus in the root element. Also focuses on `initialFocusEl` if set; otherwise, sets initial focus to the first focusable child element.
`releaseFocus() => void` | Releases focus from the root element. Also restores focus to the previously focused element.

## Announce

The `announce` utility file contains a single helper method for announcing a message via an `aria-live` region. It is intended for usage from MDC-internal components.

Method Signature | Description
--- | ---
`announce(message: string, priority?: AnnouncerPriority) => void` | Announces the message via an `aria-live` region with the given priority (defaults to polite)
<!-- TODO(b/148462294): Remove once only exported members are required in docs `say()` --> <!-- | --> <!-- DO NOT USE -->
91 changes: 91 additions & 0 deletions packages/mdc-dom/announce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* @license
* Copyright 2020 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

/**
* Priorities for the announce function
*/
export enum AnnouncerPriority {
POLITE = 'polite',
ASSERTIVE = 'assertive',
}

/**
* Announces the given message with optional priority, defaulting to "polite"
*/
export function announce(message: string, priority?: AnnouncerPriority) {
Announcer.getInstance().say(message, priority);
}

class Announcer {
private static instance: Announcer;
private readonly liveRegions: Map<AnnouncerPriority, Element>;

static getInstance(): Announcer {
if (!Announcer.instance) {
Announcer.instance = new Announcer();
}

return Announcer.instance;
}

// Constructor made private to ensure only the singleton is used
private constructor() {
this.liveRegions = new Map();
}

say(message: string, priority: AnnouncerPriority = AnnouncerPriority.POLITE) {
const liveRegion = this.getLiveRegion(priority);
// Reset the region to pick up the message, even if the message is the
// exact same as before.
liveRegion.textContent = '';
// Timeout is necessary for screen readers like NVDA and VoiceOver.
setTimeout(() => {
liveRegion.textContent = message;
}, 1);
}

private getLiveRegion(priority: AnnouncerPriority): Element {
const existingLiveRegion = this.liveRegions.get(priority);
if (existingLiveRegion &&
document.body.contains(existingLiveRegion as Node)) {
return existingLiveRegion;
}

const liveRegion = this.createLiveRegion(priority);
this.liveRegions.set(priority, liveRegion);
return liveRegion;
}

private createLiveRegion(priority: AnnouncerPriority): Element {
const el = document.createElement('div');
el.style.position = 'absolute';
el.style.top = '-9999px';
el.style.left = '-9999px';
el.style.height = '1px';
el.style.overflow = 'hidden';
el.setAttribute('aria-atomic', 'true');
el.setAttribute('aria-live', priority);
document.body.appendChild(el);
return el;
}
}
83 changes: 83 additions & 0 deletions packages/mdc-dom/test/announce.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* @license
* Copyright 2020 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup';
import {announce, AnnouncerPriority} from '../announce';

describe('announce', () => {
setUpMdcTestEnvironment();

afterEach(() => {
const liveRegions = document.querySelectorAll('[aria-live]');
[].slice.call(liveRegions).forEach((el: Element) => {
el.parentNode!.removeChild(el);
});
});

it('creates an aria-live="polite" region by default', () => {
announce('Foo');
jasmine.clock().tick(1);
const liveRegion = document.querySelector('[aria-live="polite"]');
expect(liveRegion!.textContent).toEqual('Foo');
});

it('creates an aria-live="assertive" region if specified', () => {
announce('Bar', AnnouncerPriority.ASSERTIVE);
jasmine.clock().tick(1);
const liveRegion = document.querySelector('[aria-live="assertive"]');
expect(liveRegion!.textContent).toEqual('Bar');
});

it('sets live region content after a timeout', () => {
announce('Baz');
const liveRegion = document.querySelector('[aria-live="polite"]');
expect(liveRegion!.textContent).toEqual('');
jasmine.clock().tick(1);
expect(liveRegion!.textContent).toEqual('Baz');
});

it('reuses same polite live region on successive calls', () => {
announce('aaa');
announce('bbb');
announce('ccc');
const liveRegions = document.querySelectorAll('[aria-live="polite"]');
expect(liveRegions.length).toEqual(1);
});

it('reuses same assertive live region on successive calls', () => {
announce('aaa', AnnouncerPriority.ASSERTIVE);
announce('bbb', AnnouncerPriority.ASSERTIVE);
announce('ccc', AnnouncerPriority.ASSERTIVE);
const liveRegions = document.querySelectorAll('[aria-live="assertive"]');
expect(liveRegions.length).toEqual(1);
});

it('sets the latest message during immediate successive', () => {
announce('1');
announce('2');
announce('3');
jasmine.clock().tick(1);
const liveRegion = document.querySelector('[aria-live="polite"]');
expect(liveRegion!.textContent).toEqual('3');
});
});

0 comments on commit 32c1df1

Please sign in to comment.