Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

AnnouncerController

Announces messages to screen readers through a polite and an assertive live region it inserts.

Reach for it for a sortable list, a filter count or an async status: anything that changes without moving focus and must still be heard.

Import

import { AnnouncerController, createAnnouncerController, DEFAULT_ANNOUNCER_GAP_MS } from '@ecopages/radiant-ui/controllers';

Try it

The regions are visually hidden, so the status line shows what they hold each time one is written. Press Save twice: the same message is announced again. Save and sync sends two messages within the gap, and they are joined into one announcement. Delete announces from the assertive region, which interrupts the screen reader.

Nothing announced yet

<div data-example="announcer">
	<button type="button" data-save>Save</button>
	<button type="button" data-sync>Save and sync</button>
	<button type="button" data-delete>Delete</button>
	<p data-status>Nothing announced yet</p>
</div>
import { AnnouncerController, MutationController } from '@ecopages/radiant-ui/controllers';

export function mount(root: HTMLElement): () => void {
	const status = root.querySelector('[data-status]')!;
	const listeners = new AbortController();
	let heard = 0;

	const announcer = new AnnouncerController({ getContainer: () => root });
	announcer.prepare();

	const regions = new MutationController({
		getTarget: () => root,
		options: { childList: true, subtree: true },
		onMutate: (records) => {
			for (const { target } of records) {
				if (target instanceof HTMLElement && target.hasAttribute('aria-live') && target.textContent) {
					heard += 1;
					status.textContent = `${heard}. ${target.getAttribute('aria-live')}: ${target.textContent}`;
				}
			}
		},
	});
	regions.attach();

	const { signal } = listeners;
	root.querySelector('[data-save]')!.addEventListener('click', () => announcer.announce('Saved'), { signal });
	root.querySelector('[data-sync]')!.addEventListener(
		'click',
		() => {
			announcer.announce('Saved');
			announcer.announce('Synced');
		},
		{ signal },
	);
	root.querySelector('[data-delete]')!.addEventListener(
		'click',
		() => announcer.announce('Item deleted', { assertive: true }),
		{ signal },
	);
	return () => {
		listeners.abort();
		regions.destroy();
		announcer.destroy();
	};
}

The MutationController is only there to show the regions on this page; an announcer needs none.

mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.

Config

OptionDescription
getContainerThe element the two regions are appended to, read by prepare() and announce(). null creates none yet.
classNameA class for both regions, such as a component's BEM element. They are visually hidden with or without it.
gapMilliseconds between clearing a region and writing to it. Default DEFAULT_ANNOUNCER_GAP_MS (100).

Methods

MethodDescription
prepare()Inserts the two empty regions into getContainer(), unless they are already there.
announce(message, { assertive? })Clears the polite region (or, with assertive: true, the assertive one) and writes message into it after gap. An empty message, or one sent while getContainer() returns null, announces nothing.

Behavior

  • A screen reader announces a live region only when its text changes, and ignores a region inserted already holding text. So the regions go in empty, before the first message, and each message clears its region and is written after gap: a repeated message is a real change and is announced again.
  • Messages sent to one region within the gap are joined into one announcement, as sentences: Saved and Synced read Saved. Synced, and a message that already ends in ., ! or ? gets no second period. The last one does not overwrite the rest.
  • Both regions are aria-atomic="true", so the whole message is read. The assertive one is marked data-assertive.
  • The write after the gap prepares again, so a container that appeared, or replaced its children, since the message was sent still gets it.

Lifecycle

attach() creates nothing, because a host's attributes and rendered children are not settled when it runs. Call prepare() from onConnected, or when the owner starts needing announcements; announce() also prepares. destroy() cancels pending messages and removes both regions.

With a host, createAnnouncerController(host, config) destroys it, and removes the regions, on disconnect; see bindController.

// in a RadiantElement subclass
private readonly announcer = createAnnouncerController(this, { getContainer: () => this });

protected override onConnected(): void {
	this.announcer.prepare();
}

Announcing for another controller

A controller that reports to a screen reader takes an announce callback. Point it at the announcer, so a repeated message, such as a second cancel, is heard again:

const announcer = new AnnouncerController({ getContainer: () => list.parentElement });
announcer.prepare();

const sortable = new SortableController({
	getContainer: () => list,
	getItems: () => [...list.children] as HTMLElement[],
	announce: (message) => announcer.announce(message),
	onChange: ({ item, to }) => {
		list.insertBefore(item, [...list.children].filter((child) => child !== item)[to] ?? null);
		item.focus();
	},
});
sortable.attach();

SortableController and CopyController both take it. RuiTagGroup announces its reorder steps through one.

Accessibility: what the controller does and what you must provide

The controller inserts the regions, keeps them out of sight and makes each message a change a screen reader hears. The wording and the language of the messages are yours, and so is the choice of region: keep assertive for what must interrupt, such as an error the user has to act on. Keep an element with role="alert" (an error toast) out of the regions: it announces itself, and a screen reader can read an alert nested in a live region twice.

Protected hooks

None. Change behavior through the config.