-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (59 loc) · 1.79 KB
/
Copy pathindex.js
File metadata and controls
70 lines (59 loc) · 1.79 KB
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
const visuallyHiddenCss = `\
:host {
clip-path: inset(50%) !important;
height: 1px !important;
overflow: hidden !important;
position: absolute !important;
white-space: nowrap !important;
width: 1px !important;
user-select: none !important;
}
`;
class LiveAnnouncer extends HTMLElement {
#assertiveRegion;
#politeRegion;
static register(tagName = 'live-announcer', registry) {
if (typeof window !== 'undefined') {
registry ||= customElements;
if (registry.get(tagName) == undefined) {
registry.define(tagName, LiveAnnouncer);
}
}
}
constructor() {
super();
this.#assertiveRegion = this.ownerDocument.createElement('div');
this.#assertiveRegion.setAttribute('aria-live', 'assertive');
this.#politeRegion = this.ownerDocument.createElement('div');
this.#politeRegion.setAttribute('aria-live', 'polite');
this.attachShadow({ mode: 'open' });
this.shadowRoot?.replaceChildren(this.#assertiveRegion, this.#politeRegion);
const stylesheet = new CSSStyleSheet();
stylesheet.replaceSync(visuallyHiddenCss);
this.shadowRoot?.adoptedStyleSheets.push(stylesheet);
}
setup({ target = document.body } = {}) {
target?.appendChild(this);
}
notify(text, { priority = 'none' } = {}) {
const region = priority === 'important' ? this.#assertiveRegion : this.#politeRegion;
region.textContent = text;
setTimeout(() => {
region.textContent = '';
}, 3_000);
}
}
let _announcer;
function setup() {
LiveAnnouncer.register();
if (!document.body.shadowRoot) {
const shadow = document.body.attachShadow({ mode: 'open' });
shadow.appendChild(document.createElement('slot'));
}
_announcer = new LiveAnnouncer();
_announcer.setup({ target: document.body.shadowRoot });
}
function notify(...args) {
_announcer.notify(...args);
}
export { setup, notify, LiveAnnouncer };