-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfocus-trap.ts
207 lines (175 loc) · 5.2 KB
/
focus-trap.ts
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
import { debounce } from "./debounce";
import { isFocusable, isHidden } from "./focusable";
import { queryShadowRoot } from "./shadow";
export interface IFocusTrap {
inactive: boolean;
readonly focused: boolean;
focusFirstElement: (() => void);
focusLastElement: (() => void);
getFocusableElements: (() => HTMLElement[]);
}
/**
* Template for the focus trap.
*/
const template = document.createElement("template");
template.innerHTML = `
<div id="start"></div>
<div id="backup"></div>
<slot></slot>
<div id="end"></div>
`;
/**
* Focus trap web component.
* @customElement focus-trap
* @slot - Default content.
*/
export class FocusTrap extends HTMLElement implements IFocusTrap {
// Whenever one of these attributes changes we need to render the template again.
static get observedAttributes () {
return [
"inactive"
];
}
/**
* Determines whether the focus trap is active or not.
* @attr
*/
get inactive () {
return this.hasAttribute("inactive");
}
set inactive (value: boolean) {
value ? this.setAttribute("inactive", "") : this.removeAttribute("inactive");
}
// The backup element is only used if there are no other focusable children
private $backup!: HTMLElement;
// The debounce id is used to distinguish this focus trap from others when debouncing
private debounceId = Math.random().toString();
private $start!: HTMLElement;
private $end!: HTMLElement;
private _focused = false;
/**
* Returns whether the element currently has focus.
*/
get focused (): boolean {
return this._focused;
}
/**
* Attaches the shadow root.
*/
constructor () {
super();
const shadow = this.attachShadow({mode: "open"});
shadow.appendChild(template.content.cloneNode(true));
this.$backup = shadow.querySelector<HTMLElement>("#backup")!;
this.$start = shadow.querySelector<HTMLElement>("#start")!;
this.$end = shadow.querySelector<HTMLElement>("#end")!;
this.focusLastElement = this.focusLastElement.bind(this);
this.focusFirstElement = this.focusFirstElement.bind(this);
this.onFocusIn = this.onFocusIn.bind(this);
this.onFocusOut = this.onFocusOut.bind(this);
}
/**
* Hooks up the element.
*/
connectedCallback () {
this.$start.addEventListener("focus", this.focusLastElement);
this.$end.addEventListener("focus", this.focusFirstElement);
// Focus out is called every time the user tabs around inside the element
this.addEventListener("focusin", this.onFocusIn);
this.addEventListener("focusout", this.onFocusOut);
this.render();
}
/**
* Tears down the element.
*/
disconnectedCallback () {
this.$start.removeEventListener("focus", this.focusLastElement);
this.$end.removeEventListener("focus", this.focusFirstElement);
this.removeEventListener("focusin", this.onFocusIn);
this.removeEventListener("focusout", this.onFocusOut);
}
/**
* When the attributes changes we need to re-render the template.
*/
attributeChangedCallback () {
this.render();
}
/**
* Focuses the first focusable element in the focus trap.
*/
focusFirstElement () {
this.trapFocus();
}
/**
* Focuses the last focusable element in the focus trap.
*/
focusLastElement () {
this.trapFocus(true);
}
/**
* Returns a list of the focusable children found within the element.
*/
getFocusableElements (): HTMLElement[] {
return queryShadowRoot(this, isHidden, isFocusable);
}
/**
* Focuses on either the last or first focusable element.
* @param {boolean} trapToEnd
*/
protected trapFocus (trapToEnd?: boolean) {
if (this.inactive) return;
let focusableElements = this.getFocusableElements();
if (focusableElements.length > 0) {
if (trapToEnd) {
focusableElements[focusableElements.length - 1].focus();
} else {
focusableElements[0].focus();
}
this.$backup.setAttribute("tabindex", "-1");
} else {
// If there are no focusable children we need to focus on the backup
// to trap the focus. This is a useful behavior if the focus trap is
// for example used in a dialog and we don't want the user to tab
// outside the dialog even though there are no focusable children
// in the dialog.
this.$backup.setAttribute("tabindex", "0");
this.$backup.focus();
}
}
/**
* When the element gains focus this function is called.
*/
private onFocusIn () {
this.updateFocused(true);
}
/**
* When the element looses its focus this function is called.
*/
private onFocusOut () {
this.updateFocused(false);
}
/**
* Updates the focused property and updates the view.
* The update is debounced because the focusin and focusout out
* might fire multiple times in a row. We only want to render
* the element once, therefore waiting until the focus is "stable".
* @param value
*/
private updateFocused (value: boolean) {
debounce(() => {
if (this.focused !== value) {
this._focused = value;
this.render();
}
}, 0, this.debounceId);
}
/**
* Updates the template.
*/
protected render () {
this.$start.setAttribute("tabindex", !this.focused || this.inactive ? `-1` : `0`);
this.$end.setAttribute("tabindex", !this.focused || this.inactive ? `-1` : `0`);
this.focused ? this.setAttribute("focused", "") : this.removeAttribute("focused");
}
}
window.customElements.define("focus-trap", FocusTrap);