Skip to content

A platform for community discussion. Free, open, simple.

A11Y: Deliver repeated screen reader announcements to live regions (#42120)

Sérgio Saquetim1f51b4f50afb
diff --git a/frontend/discourse/app/services/a11y.js b/frontend/discourse/app/services/a11y.js
index afb73afd9b6..3fa736e51a2 100644
--- a/frontend/discourse/app/services/a11y.js
+++ b/frontend/discourse/app/services/a11y.js
@@ -87,6 +87,12 @@ export default class A11y extends Service {
*/
#timers = trackedMap();
+ /**
+ * Map of pending repeat-restore timers by type
+ * @type {Map<string, EmberRunTimer>}
+ */
+ #restores = new Map();
+
/**
* Sets an announcement message with auto-clearing
* @param {'polite'|'assertive'} type - Type of announcement
@@ -94,12 +100,41 @@ export default class A11y extends Service {
* @param {number} clearDelay - Delay in ms before clearing
*/
setMessage(type, message, clearDelay) {
+ // Two announcements in one tick can queue a restore between this call being scheduled
+ // and it running, so the request-time cancel in `announce` cannot be the only one.
+ this.cancelRestore(type);
+
if (message === "") {
this.#messages.delete(type);
this.#scheduleClear(type, 0);
return;
}
+ // A live region only speaks when its text changes, so writing the same string back is
+ // a DOM no-op that no screen reader picks up. Blank the region and restore it a render
+ // later to give it a change it can act on.
+ if (this.#messages.get(type) === message) {
+ this.#messages.delete(type);
+ this.#restores.set(
+ type,
+ next(() => {
+ this.#restores.delete(type);
+ this.#write(type, message, clearDelay);
+ })
+ );
+ return;
+ }
+
+ this.#write(type, message, clearDelay);
+ }
+
+ /**
+ * Writes the message into the live region and arms its clear timer
+ * @param {'polite'|'assertive'} type - Type of announcement
+ * @param {string} message - Message to announce
+ * @param {number} clearDelay - Delay in ms before clearing
+ */
+ #write(type, message, clearDelay) {
this.#messages.set(type, message);
if (clearAnnouncements) {
@@ -117,7 +152,7 @@ export default class A11y extends Service {
}
/**
- * Clears all announcement clear timers
+ * Clears all pending announcement timers
*/
clearTimers() {
this.#timers.forEach((timer) => {
@@ -126,6 +161,21 @@ export default class A11y extends Service {
}
});
this.#timers.clear();
+
+ this.#restores.forEach((timer) => cancel(timer));
+ this.#restores.clear();
+ }
+
+ /**
+ * Cancels the pending repeat-restore for a type, if there is one
+ * @param {'polite'|'assertive'} type - Type of announcement
+ */
+ cancelRestore(type) {
+ const pendingRestore = this.#restores.get(type);
+ if (pendingRestore) {
+ cancel(pendingRestore);
+ this.#restores.delete(type);
+ }
}
/**
@@ -202,6 +252,12 @@ export default class A11y extends Service {
const trimmed = message.trim();
+ // Drop a pending repeat-restore as soon as a newer message is requested rather than a
+ // tick later when the write below runs, because the restore is already queued ahead of
+ // that write and would otherwise put the older message back first. Restores are held
+ // outside tracked state, so cancelling one here is safe during render.
+ this.#state.cancelRestore(type);
+
// Defer the tracked-state write out of the current render. `announce` is often
// called from a render-driven data load (e.g. an async content resolution), and
// writing tracked state synchronously during render trips Ember's
diff --git a/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs b/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs
index cbf985f07e6..7910c456c5b 100644
--- a/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs
+++ b/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs
@@ -1,15 +1,50 @@
import Component from "@glimmer/component";
import { getOwner } from "@ember/owner";
+import { next, run } from "@ember/runloop";
import { service } from "@ember/service";
-import { render } from "@ember/test-helpers";
+import { find, render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import A11yLiveRegions from "discourse/components/a11y/live-regions";
import { disableClearA11yAnnouncementsInTests } from "discourse/services/a11y";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+const REGIONS = [
+ { type: "polite", selector: "#a11y-announcements-polite" },
+ { type: "assertive", selector: "#a11y-announcements-assertive" },
+];
+
module("Integration | Component | A11y | LiveRegions", function (hooks) {
setupRenderingTest(hooks);
+ let observers = [];
+
+ hooks.afterEach(function () {
+ observers.forEach((observer) => observer.disconnect());
+ observers = [];
+ });
+
+ // A live region only speaks when its DOM text changes, so the mutation count is what a
+ // screen reader reacts to. A text assertion alone cannot tell a delivered repeat from a
+ // write that changed nothing, and the final text cannot tell whether something stale was
+ // spoken on the way there.
+ function watchTextMutations(selector) {
+ const element = find(selector);
+ const state = { count: 0, texts: [] };
+ const observer = new MutationObserver(() => {
+ state.count++;
+ state.texts.push(element.textContent.trim());
+ });
+
+ observer.observe(element, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ observers.push(observer);
+
+ return state;
+ }
+
test("renders polite and assertive live regions", async function (assert) {
await render(<template><A11yLiveRegions /></template>);
@@ -96,4 +131,114 @@ module("Integration | Component | A11y | LiveRegions", function (hooks) {
"the render-time announcement is shown without a backtracking error"
);
});
+
+ REGIONS.forEach(({ type, selector }) => {
+ test(`re-announcing an identical ${type} message still reaches the live region`, async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+ await render(<template><A11yLiveRegions /></template>);
+
+ const mutations = watchTextMutations(selector);
+ const a11y = getOwner(this).lookup("service:a11y");
+
+ a11y.announce("1 result", type);
+ await settled();
+ const afterFirst = mutations.count;
+
+ a11y.announce("1 result", type);
+ await settled();
+
+ assert.true(
+ afterFirst > 0,
+ "the first announcement reaches the region at all"
+ );
+ assert.true(
+ mutations.count > afterFirst,
+ "an identical repeat mutates the region again rather than being swallowed"
+ );
+ assert
+ .dom(selector)
+ .hasText("1 result", "and the region settles on the message");
+ });
+ });
+
+ test("a repeat does not overwrite an announcement made while it was pending", async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+ await render(<template><A11yLiveRegions /></template>);
+
+ const a11y = getOwner(this).lookup("service:a11y");
+
+ a11y.announce("1 result", "polite");
+ await settled();
+
+ // Delivering a repeat takes an extra tick, during which an unrelated caller can write
+ // to the same region. The newest message has to be the one left standing.
+ a11y.announce("1 result", "polite");
+ a11y.announce("2 results", "polite");
+ await settled();
+
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasText(
+ "2 results",
+ "the newest announcement survives the pending repeat"
+ );
+ });
+
+ test("a repeat already in flight is never spoken once a newer announcement arrives", async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+ await render(<template><A11yLiveRegions /></template>);
+
+ const a11y = getOwner(this).lookup("service:a11y");
+
+ a11y.announce("1 result", "polite");
+ await settled();
+
+ const mutations = watchTextMutations("#a11y-announcements-polite");
+
+ // Advance one tick so the repeat has blanked the region but has not restored it yet.
+ // A newer announcement arriving in that window has to win outright: asserting only the
+ // final text would miss the region speaking the stale message on the way there.
+ a11y.announce("1 result", "polite");
+ await new Promise((resolve) => next(resolve));
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasNoText("the repeat blanks the region before restoring it");
+
+ a11y.announce("2 results", "polite");
+ await settled();
+
+ assert.false(
+ mutations.texts.includes("1 result"),
+ "the superseded message is never put back into the region"
+ );
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasText(
+ "2 results",
+ "the newest announcement is what the region ends on"
+ );
+ });
+
+ test("a pending repeat does not write to a destroyed service", async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+
+ const a11y = getOwner(this).lookup("service:a11y");
+
+ a11y.announce("1 result", "polite");
+ await settled();
+
+ // Advance a single tick so the repeat has blanked the region and scheduled its
+ // restore, but the restore has not run yet.
+ a11y.announce("1 result", "polite");
+ await new Promise((resolve) => next(resolve));
+
+ run(() => a11y.destroy());
+ await settled();
+
+ assert.strictEqual(
+ a11y.politeMessage,
+ undefined,
+ "teardown cancels the pending restore instead of letting it write and re-arm a timer"
+ );
+ });
});