-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialog.js
111 lines (84 loc) · 2.72 KB
/
dialog.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
export class Dialog {
dialogElement;
overlayElement;
focusedElementBeforeOpen;
focusableElements;
firstFocusableElement;
lastFocusableElement;
constructor(dialogElement, overlayElement) {
this.dialogElement = dialogElement;
this.overlayElement = overlayElement;
var focusableElements = this.dialogElement.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]');
this.focusableElements = Array.prototype.slice.call(focusableElements);
this.firstFocusableElement = this.focusableElements[0];
this.lastFocusableElement = this.focusableElements[this.focusableElements.length - 1];
this.close(); // Reset
}
open() {
this.dialogElement.removeAttribute('aria-hidden');
this.overlayElement.removeAttribute('aria-hidden');
this.focusedElementBeforeOpen = document.activeElement;
this.dialogElement.addEventListener('keydown', (e) => {
this._handleKeyDown(e);
});
this.overlayElement.addEventListener('click', () => {
this.close();
});
this.firstFocusableElement.focus();
}
close() {
this.dialogElement.setAttribute('aria-hidden', true);
this.overlayElement.setAttribute('aria-hidden', true);
if (this.focusedElementBeforeOpen) {
this.focusedElementBeforeOpen.focus();
}
}
_handleKeyDown(event) {
const KEY_TAB = 9;
const KEY_ESC = 27;
switch (event.keyCode) {
case KEY_TAB:
if (this.focusableElements.length === 1) {
event.preventDefault();
break;
}
if (event.shiftKey) {
this._handleBackwardTab(event);
} else {
this._handleForwardTab(event);
}
break;
case KEY_ESC:
this.close();
break;
default:
break;
}
}
_handleBackwardTab(event) {
if (document.activeElement === this.firstFocusableElement) {
event.preventDefault();
this.lastFocusableElement.focus();
}
}
_handleForwardTab(event) {
if (document.activeElement === this.lastFocusableElement) {
event.preventDefault();
this.firstFocusableElement.focus();
}
}
addEventListeners(openDialogSelector, closeDialogSelector) {
const openDialogElements = document.querySelectorAll(openDialogSelector);
for (var i = 0; i < openDialogElements.length; i++) {
openDialogElements[i].addEventListener('click', () => {
this.open();
});
}
const closeDialogElements = document.querySelectorAll(closeDialogSelector);
for (var i = 0; i < closeDialogElements.length; i++) {
closeDialogElements[i].addEventListener('click', () => {
this.close();
});
}
}
}