-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclose-watcher.js
41 lines (35 loc) · 884 Bytes
/
close-watcher.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
if (! (globalThis.CloseWatcher instanceof Function)) {
globalThis.CloseWatcher = class CloseWatcher extends EventTarget {
#controller = new AbortController();
#cancelable = true;
constructor() {
super();
document.addEventListener('keydown', event => {
if (event.key === 'Escape') {
this.requestClose();
}
}, { signal: this.#controller.signal });
}
requestClose() {
if (! this.#controller.signal.aborted) {
const event = new Event('cancel', { cancelable: this.#cancelable });
this.dispatchEvent(event);
this.#cancelable = false;
if (! event.defaultPrevented) {
this.close();
}
}
}
close() {
if (! this.#controller.signal.aborted) {
this.dispatchEvent(new Event('close'));
this.destroy();
}
}
destroy() {
if (! this.#controller.signal.aborted) {
this.#controller.abort();
}
}
};
}