-
Notifications
You must be signed in to change notification settings - Fork 1
/
ariaNotify-polyfill.js
217 lines (188 loc) · 6.16 KB
/
ariaNotify-polyfill.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// @ts-check
if (!("ariaNotify" in Element.prototype)) {
/** @type {string} */
let uniqueId = `${Date.now()}`;
try {
uniqueId = crypto.randomUUID();
} catch {}
/**
* A unique symbol to prevent unauthorized access to the 'live-region' element.
* @type {Symbol}
*/
const passkey = Symbol();
/** @type {string} */
const liveRegionCustomElementName = `live-region-${uniqueId}`;
/**
* @param {number} ms
* @returns {Promise<void>}
*/
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
class Message {
/** @type {Element} */
element;
/** @type {string} */
message;
/** @type {"important" | "none"} */
priority = "none";
/** @type {"all" | "pending" | "none"} */
interrupt = "none";
/** @type {boolean} */
get #shouldFlushOthers() {
return this.interrupt === "all" || this.interrupt === "pending";
}
/**
* @param {object} message
* @param {Element} message.element
* @param {string} message.message
* @param {"important" | "none"} message.priority
* @param {"all" | "pending" | "none"} message.interrupt
*/
constructor({ element, message, priority = "none", interrupt = "none" }) {
this.element = element;
this.message = message;
this.priority = priority;
this.interrupt = interrupt;
}
/**
* Whether this message and the given message are equivalent.
* @param {Message} message
* @returns {boolean}
*/
matches(message) {
return (
this.element === message.element &&
this.priority === message.priority &&
this.interrupt === message.interrupt
);
}
/**
* Whether this message can be announced.
* @returns {boolean}
*/
#canAnnounce() {
return (
this.element.isConnected &&
// Elements within inert containers should not be announced.
!this.element.closest("[inert]") &&
// If there is a modal element on the page, everything outside of it is implicitly inert.
// This can be checked by seeing if the element is within the modal, if the modal is present.
(this.element.ownerDocument
.querySelector(":modal")
?.contains(this.element) ??
true)
);
}
/** @returns {Promise<void>} */
async announce() {
// Skip an unannounceable message.
if (!this.#canAnnounce()) {
return;
}
// Get root element
let root = /** @type {Element} */ (
this.element.closest("dialog") || this.element.getRootNode()
);
if (!root || root instanceof Document) root = document.body;
// Get 'live-region', if it already exists
/** @type {LiveRegionCustomElement | null} */
let liveRegion = root.querySelector(liveRegionCustomElementName);
// Destroy 'live-region', if it exists and should be flushed
if (this.#shouldFlushOthers && liveRegion) {
liveRegion.remove();
liveRegion = null;
}
// Create (or recreate) 'live-region', if it doesn’t exist
if (!liveRegion) {
liveRegion = /** @type {LiveRegionCustomElement} */ (
document.createElement(liveRegionCustomElementName)
);
root.append(liveRegion);
}
await sleep(250);
liveRegion.handleMessage(passkey, this.message);
}
}
const queue = new (class MessageQueue {
/** @type {Message[]} */
#queue = [];
/** @type {Message | undefined | null} */
#currentMessage;
/**
* Add the given message to the queue.
* @param {Message} message
* @returns {void}
*/
enqueue(message) {
const { priority, interrupt } = message;
if (interrupt === "all" || interrupt === "pending") {
// Remove other messages with the same element, priority, and interrupt
this.#queue = this.#queue.filter(
(message) => !message.matches(message)
);
}
if (priority === "important") {
// Insert after the last important message, or at the beginning
// @ts-ignore: ts(2550)
const lastImportantMessage = this.#queue.findLastIndex(
(message) => message.priority === "important"
);
this.#queue.splice(lastImportantMessage + 1, 0, message);
} else {
// Insert at the end
this.#queue.push(message);
}
if (!this.#currentMessage) {
this.#processNext();
}
}
async #processNext() {
this.#currentMessage = this.#queue.shift();
if (!this.#currentMessage) return;
await this.#currentMessage.announce();
this.#processNext();
}
})();
class LiveRegionCustomElement extends HTMLElement {
#shadowRoot = this.attachShadow({ mode: "closed" });
connectedCallback() {
this.ariaLive = "polite";
this.ariaAtomic = "true";
this.style.marginLeft = "-1px";
this.style.marginTop = "-1px";
this.style.position = "absolute";
this.style.width = "1px";
this.style.height = "1px";
this.style.overflow = "hidden";
this.style.clipPath = "rect(0 0 0 0)";
this.style.overflowWrap = "normal";
}
/**
* @param {Symbol | null} key
* @param {string} message
*/
handleMessage(key = null, message = "") {
if (passkey !== key) return;
// This is a hack due to the way the aria live API works. A screen reader
// will not read a live region again if the text is the same. Adding a
// space character tells the browser that the live region has updated,
// which will cause it to read again, but with no audible difference.
if (this.#shadowRoot.textContent == message) message += "\u00A0";
this.#shadowRoot.textContent = message;
}
}
customElements.define(liveRegionCustomElementName, LiveRegionCustomElement);
/**
* @param {string} message
* @param {object} options
* @param {"important" | "none"} [options.priority]
* @param {"all" | "pending" | "none" } [options.interrupt]
*/
Element.prototype["ariaNotify"] = function (
message,
{ priority = "none", interrupt = "none" } = {}
) {
queue.enqueue(new Message({ element: this, message, priority, interrupt }));
};
}