forked from focus-trap/focus-trap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
630 lines (522 loc) · 17.8 KB
/
index.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import { tabbable, isFocusable } from 'tabbable';
const activeFocusTraps = (function () {
const trapQueue = [];
return {
activateTrap(trap) {
if (trapQueue.length > 0) {
const activeTrap = trapQueue[trapQueue.length - 1];
if (activeTrap !== trap) {
activeTrap.pause();
}
}
const trapIndex = trapQueue.indexOf(trap);
if (trapIndex === -1) {
trapQueue.push(trap);
} else {
// move this existing trap to the front of the queue
trapQueue.splice(trapIndex, 1);
trapQueue.push(trap);
}
},
deactivateTrap(trap) {
const trapIndex = trapQueue.indexOf(trap);
if (trapIndex !== -1) {
trapQueue.splice(trapIndex, 1);
}
if (trapQueue.length > 0) {
trapQueue[trapQueue.length - 1].unpause();
}
},
};
})();
const isSelectableInput = function (node) {
return (
node.tagName &&
node.tagName.toLowerCase() === 'input' &&
typeof node.select === 'function'
);
};
const isEscapeEvent = function (e) {
return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;
};
const isTabEvent = function (e) {
return e.key === 'Tab' || e.keyCode === 9;
};
const delay = function (fn) {
return setTimeout(fn, 0);
};
// Array.find/findIndex() are not supported on IE; this replicates enough
// of Array.findIndex() for our needs
const findIndex = function (arr, fn) {
let idx = -1;
arr.every(function (value, i) {
if (fn(value)) {
idx = i;
return false; // break
}
return true; // next
});
return idx;
};
/**
* Get an option's value when it could be a plain value, or a handler that provides
* the value.
* @param {*} value Option's value to check.
* @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.
* @returns {*} The `value`, or the handler's returned value.
*/
const valueOrHandler = function (value, ...params) {
return typeof value === 'function' ? value(...params) : value;
};
const createFocusTrap = function (elements, userOptions) {
const doc = document;
const config = {
returnFocusOnDeactivate: true,
escapeDeactivates: true,
delayInitialFocus: true,
...userOptions,
};
const state = {
// @type {Array<HTMLElement>}
containers: [],
// list of objects identifying the first and last tabbable nodes in all containers/groups in
// the trap
// NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap
// is active, but the trap should never get to a state where there isn't at least one group
// with at least one tabbable node in it (that would lead to an error condition that would
// result in an error being thrown)
// @type {Array<{ container: HTMLElement, firstTabbableNode: HTMLElement|null, lastTabbableNode: HTMLElement|null }>}
tabbableGroups: [],
nodeFocusedBeforeActivation: null,
mostRecentlyFocusedNode: null,
active: false,
paused: false,
// timer ID for when delayInitialFocus is true and initial focus in this trap
// has been delayed during activation
delayInitialFocusTimer: undefined,
};
let trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later
const getOption = (configOverrideOptions, optionName, configOptionName) => {
return configOverrideOptions &&
configOverrideOptions[optionName] !== undefined
? configOverrideOptions[optionName]
: config[configOptionName || optionName];
};
const containersContain = function (element) {
return state.containers.some((container) => container.contains(element));
};
const getNodeForOption = function (optionName) {
const optionValue = config[optionName];
if (!optionValue) {
return null;
}
let node = optionValue;
if (typeof optionValue === 'string') {
node = doc.querySelector(optionValue);
if (!node) {
throw new Error(`\`${optionName}\` refers to no known node`);
}
}
if (typeof optionValue === 'function') {
node = optionValue();
if (!node) {
throw new Error(`\`${optionName}\` did not return a node`);
}
}
return node;
};
const getInitialFocusNode = function () {
let node;
// false indicates we want no initialFocus at all
if (getOption({}, 'initialFocus') === false) {
return false;
}
if (getNodeForOption('initialFocus') !== null) {
node = getNodeForOption('initialFocus');
} else if (containersContain(doc.activeElement)) {
node = doc.activeElement;
} else {
const firstTabbableGroup = state.tabbableGroups[0];
const firstTabbableNode =
firstTabbableGroup && firstTabbableGroup.firstTabbableNode;
node = firstTabbableNode || getNodeForOption('fallbackFocus');
}
if (!node) {
throw new Error(
'Your focus-trap needs to have at least one focusable element'
);
}
return node;
};
const updateTabbableNodes = function () {
state.tabbableGroups = state.containers
.map((container) => {
const tabbableNodes = tabbable(container);
if (tabbableNodes.length > 0) {
return {
container,
firstTabbableNode: tabbableNodes[0],
lastTabbableNode: tabbableNodes[tabbableNodes.length - 1],
};
}
return undefined;
})
.filter((group) => !!group); // remove groups with no tabbable nodes
// throw if no groups have tabbable nodes and we don't have a fallback focus node either
if (
state.tabbableGroups.length <= 0 &&
!getNodeForOption('fallbackFocus')
) {
throw new Error(
'Your focus-trap must have at least one container with at least one tabbable node in it at all times'
);
}
};
const tryFocus = function (node) {
if (node === false) {
return;
}
if (node === doc.activeElement) {
return;
}
if (!node || !node.focus) {
tryFocus(getInitialFocusNode());
return;
}
node.focus({ preventScroll: !!config.preventScroll });
state.mostRecentlyFocusedNode = node;
if (isSelectableInput(node)) {
node.select();
}
};
const getReturnFocusNode = function (previousActiveElement) {
const node = getNodeForOption('setReturnFocus');
return node ? node : previousActiveElement;
};
// This needs to be done on mousedown and touchstart instead of click
// so that it precedes the focus event.
const checkPointerDown = function (e) {
if (containersContain(e.target)) {
// allow the click since it ocurred inside the trap
return;
}
if (valueOrHandler(config.clickOutsideDeactivates, e)) {
// immediately deactivate the trap
trap.deactivate({
// if, on deactivation, we should return focus to the node originally-focused
// when the trap was activated (or the configured `setReturnFocus` node),
// then assume it's also OK to return focus to the outside node that was
// just clicked, causing deactivation, as long as that node is focusable;
// if it isn't focusable, then return focus to the original node focused
// on activation (or the configured `setReturnFocus` node)
// NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
// which will result in the outside click setting focus to the node
// that was clicked, whether it's focusable or not; by setting
// `returnFocus: true`, we'll attempt to re-focus the node originally-focused
// on activation (or the configured `setReturnFocus` node)
returnFocus: config.returnFocusOnDeactivate && !isFocusable(e.target),
});
return;
}
// This is needed for mobile devices.
// (If we'll only let `click` events through,
// then on mobile they will be blocked anyways if `touchstart` is blocked.)
if (valueOrHandler(config.allowOutsideClick, e)) {
// allow the click outside the trap to take place
return;
}
// otherwise, prevent the click
e.preventDefault();
};
// In case focus escapes the trap for some strange reason, pull it back in.
const checkFocusIn = function (e) {
const targetContained = containersContain(e.target);
// In Firefox when you Tab out of an iframe the Document is briefly focused.
if (targetContained || e.target instanceof Document) {
if (targetContained) {
state.mostRecentlyFocusedNode = e.target;
}
} else {
// escaped! pull it back in to where it just left
e.stopImmediatePropagation();
tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
}
};
// Hijack Tab events on the first and last focusable nodes of the trap,
// in order to prevent focus from escaping. If it escapes for even a
// moment it can end up scrolling the page and causing confusion so we
// kind of need to capture the action at the keydown phase.
const checkTab = function (e) {
updateTabbableNodes();
let destinationNode = null;
if (state.tabbableGroups.length > 0) {
// make sure the target is actually contained in a group
// NOTE: the target may also be the container itself if it's tabbable
// with tabIndex='-1' and was given initial focus
const containerIndex = findIndex(state.tabbableGroups, ({ container }) =>
container.contains(e.target)
);
if (containerIndex < 0) {
// target not found in any group: quite possible focus has escaped the trap,
// so bring it back in to...
if (e.shiftKey) {
// ...the last node in the last group
destinationNode =
state.tabbableGroups[state.tabbableGroups.length - 1]
.lastTabbableNode;
} else {
// ...the first node in the first group
destinationNode = state.tabbableGroups[0].firstTabbableNode;
}
} else if (e.shiftKey) {
// REVERSE
// is the target the first tabbable node in a group?
let startOfGroupIndex = findIndex(
state.tabbableGroups,
({ firstTabbableNode }) => e.target === firstTabbableNode
);
if (
startOfGroupIndex < 0 &&
state.tabbableGroups[containerIndex].container === e.target
) {
// an exception case where the target is the container itself, in which
// case, we should handle shift+tab as if focus were on the container's
// first tabbable node, and go to the last tabbable node of the LAST group
startOfGroupIndex = containerIndex;
}
if (startOfGroupIndex >= 0) {
// YES: then shift+tab should go to the last tabbable node in the
// previous group (and wrap around to the last tabbable node of
// the LAST group if it's the first tabbable node of the FIRST group)
const destinationGroupIndex =
startOfGroupIndex === 0
? state.tabbableGroups.length - 1
: startOfGroupIndex - 1;
const destinationGroup = state.tabbableGroups[destinationGroupIndex];
destinationNode = destinationGroup.lastTabbableNode;
}
} else {
// FORWARD
// is the target the last tabbable node in a group?
let lastOfGroupIndex = findIndex(
state.tabbableGroups,
({ lastTabbableNode }) => e.target === lastTabbableNode
);
if (
lastOfGroupIndex < 0 &&
state.tabbableGroups[containerIndex].container === e.target
) {
// an exception case where the target is the container itself, in which
// case, we should handle tab as if focus were on the container's
// last tabbable node, and go to the first tabbable node of the FIRST group
lastOfGroupIndex = containerIndex;
}
if (lastOfGroupIndex >= 0) {
// YES: then tab should go to the first tabbable node in the next
// group (and wrap around to the first tabbable node of the FIRST
// group if it's the last tabbable node of the LAST group)
const destinationGroupIndex =
lastOfGroupIndex === state.tabbableGroups.length - 1
? 0
: lastOfGroupIndex + 1;
const destinationGroup = state.tabbableGroups[destinationGroupIndex];
destinationNode = destinationGroup.firstTabbableNode;
}
}
} else {
destinationNode = getNodeForOption('fallbackFocus');
}
if (destinationNode) {
e.preventDefault();
tryFocus(destinationNode);
}
// else, let the browser take care of [shift+]tab and move the focus
};
const checkKey = function (e) {
if (
isEscapeEvent(e) &&
valueOrHandler(config.escapeDeactivates) !== false
) {
e.preventDefault();
trap.deactivate();
return;
}
if (isTabEvent(e)) {
checkTab(e);
return;
}
};
const checkClick = function (e) {
if (valueOrHandler(config.clickOutsideDeactivates, e)) {
return;
}
if (containersContain(e.target)) {
return;
}
if (valueOrHandler(config.allowOutsideClick, e)) {
return;
}
e.preventDefault();
e.stopImmediatePropagation();
};
//
// EVENT LISTENERS
//
const addListeners = function () {
if (!state.active) {
return;
}
// There can be only one listening focus trap at a time
activeFocusTraps.activateTrap(trap);
// Delay ensures that the focused element doesn't capture the event
// that caused the focus trap activation.
state.delayInitialFocusTimer = config.delayInitialFocus
? delay(function () {
tryFocus(getInitialFocusNode());
})
: tryFocus(getInitialFocusNode());
doc.addEventListener('focusin', checkFocusIn, true);
doc.addEventListener('mousedown', checkPointerDown, {
capture: true,
passive: false,
});
doc.addEventListener('touchstart', checkPointerDown, {
capture: true,
passive: false,
});
doc.addEventListener('click', checkClick, {
capture: true,
passive: false,
});
doc.addEventListener('keydown', checkKey, {
capture: true,
passive: false,
});
return trap;
};
const removeListeners = function () {
if (!state.active) {
return;
}
doc.removeEventListener('focusin', checkFocusIn, true);
doc.removeEventListener('mousedown', checkPointerDown, true);
doc.removeEventListener('touchstart', checkPointerDown, true);
doc.removeEventListener('click', checkClick, true);
doc.removeEventListener('keydown', checkKey, true);
return trap;
};
//
// TRAP DEFINITION
//
trap = {
activate(activateOptions) {
if (state.active) {
return this;
}
const onActivate = getOption(activateOptions, 'onActivate');
const onPostActivate = getOption(activateOptions, 'onPostActivate');
const checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');
if (!checkCanFocusTrap) {
updateTabbableNodes();
}
state.active = true;
state.paused = false;
state.nodeFocusedBeforeActivation = doc.activeElement;
if (onActivate) {
onActivate();
}
const finishActivation = () => {
if (checkCanFocusTrap) {
updateTabbableNodes();
}
addListeners();
if (onPostActivate) {
onPostActivate();
}
};
if (checkCanFocusTrap) {
checkCanFocusTrap(state.containers.concat()).then(
finishActivation,
finishActivation
);
return this;
}
finishActivation();
return this;
},
deactivate(deactivateOptions) {
if (!state.active) {
return this;
}
clearTimeout(state.delayInitialFocusTimer); // noop if undefined
state.delayInitialFocusTimer = undefined;
removeListeners();
state.active = false;
state.paused = false;
activeFocusTraps.deactivateTrap(trap);
const onDeactivate = getOption(deactivateOptions, 'onDeactivate');
const onPostDeactivate = getOption(deactivateOptions, 'onPostDeactivate');
const checkCanReturnFocus = getOption(
deactivateOptions,
'checkCanReturnFocus'
);
if (onDeactivate) {
onDeactivate();
}
const returnFocus = getOption(
deactivateOptions,
'returnFocus',
'returnFocusOnDeactivate'
);
const finishDeactivation = () => {
delay(() => {
if (returnFocus) {
tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));
}
if (onPostDeactivate) {
onPostDeactivate();
}
});
};
if (returnFocus && checkCanReturnFocus) {
checkCanReturnFocus(
getReturnFocusNode(state.nodeFocusedBeforeActivation)
).then(finishDeactivation, finishDeactivation);
return this;
}
finishDeactivation();
return this;
},
pause() {
if (state.paused || !state.active) {
return this;
}
state.paused = true;
removeListeners();
return this;
},
unpause() {
if (!state.paused || !state.active) {
return this;
}
state.paused = false;
updateTabbableNodes();
addListeners();
return this;
},
updateContainerElements(containerElements) {
const elementsAsArray = [].concat(containerElements).filter(Boolean);
state.containers = elementsAsArray.map((element) =>
typeof element === 'string' ? doc.querySelector(element) : element
);
if (state.active) {
updateTabbableNodes();
}
return this;
},
};
// initialize container elements
trap.updateContainerElements(elements);
return trap;
};
export { createFocusTrap };