Skip to content
Source
Sign inSign up

accessibilityAnnouncements.ts

36 lines1.3 KB

1let latestOpen = false;
2let firstWritePending = false;
3​
4/** Alternating atomic live regions allow repeated user actions to be announced, as in VS Code aria.ts. */
5export function announceSidebarVisibility(open: boolean) {
6 latestOpen = open;
7 if (firstWritePending) return;
8 let container = document.getElementById("workspace-visibility-alerts");
9 const created = !container;
10 if (!container) {
11 container = document.createElement("div");
12 container.id = "workspace-visibility-alerts";
13 container.className = "sr-only";
14 for (let index = 0; index < 2; index++) {
15 const alert = document.createElement("div");
16 alert.setAttribute("aria-live", "polite");
17 alert.setAttribute("aria-atomic", "true");
18 container.append(alert);
19 }
20 document.body.append(container);
21 }
22 const [first, second] = Array.from(container.children);
23 const write = () => {
24 firstWritePending = false;
25 const next = first!.textContent ? second! : first!;
26 first!.textContent = "";
27 second!.textContent = "";
28 next.textContent = `Sidebar ${latestOpen ? "shown" : "hidden"}`;
29 };
30 // Screen readers ignore text written in the same task that inserts its live region.
31 // Toggles during that delay only update the state the pending write announces.
32 if (created) {
33 firstWritePending = true;
34 setTimeout(write, 100);
35 } else write();