Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useLiveRegion.ts

41 lines1.4 KB

1import { useEffect, useRef } from "react";
2​
3// NVDA reads a polite region's leftover text again when focus returns from a
4// dialog, so an announcement is cleared once it has had time to be spoken.
5// Clearing doesn't cut off speech that already started.
6const CLEAR_AFTER_MS = 7_000;
7​
8/** A polite live region written straight to the DOM, so speaking never re-renders. */
9export function useLiveRegion() {
10 const regionRef = useRef<HTMLDivElement>(null);
11 const clearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
12​
13 const cancelClear = () => {
14 if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);
15 clearTimerRef.current = null;
16 };
17​
18 const clear = () => {
19 cancelClear();
20 if (regionRef.current !== null) regionRef.current.textContent = "";
21 };
22​
23 const announce = (text: string) => {
24 const region = regionRef.current;
25 if (region === null) return;
26 cancelClear();
27 // Screen readers ignore a write that leaves the text unchanged, so a repeat
28 // gets a trailing non-breaking space to count as new.
29 region.textContent = region.textContent === text ? `${text} ` : text;
30 clearTimerRef.current = setTimeout(clear, CLEAR_AFTER_MS);
31 };
32​
33 useEffect(
34 () => () => {
35 if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);
36 },
37 [],
38 );
39​
40 return { regionRef, announce, clear };