Debian Codegraph @

node/focus-trap/index.js

raw
1 import {
2 tabbable,
3 focusable,
4 isFocusable,
5 isTabbable,
6 getTabIndex,
7 } from 'tabbable';
8
9 const activeFocusTraps = {
10 activateTrap(trapStack, trap) {
11 if (trapStack.length > 0) {
12 const activeTrap = trapStack[trapStack.length - 1];
13 if (activeTrap !== trap) {
14 activeTrap._setPausedState(true);
15 }
16 }
17
18 const trapIndex = trapStack.indexOf(trap);
19 if (trapIndex === -1) {
20 trapStack.push(trap);
21 } else {
22 // move this existing trap to the front of the queue
23 trapStack.splice(trapIndex, 1);
24 trapStack.push(trap);
25 }
26 },
27
28 deactivateTrap(trapStack, trap) {
29 const trapIndex = trapStack.indexOf(trap);
30 if (trapIndex !== -1) {
31 trapStack.splice(trapIndex, 1);
32 }
33
34 if (
35 trapStack.length > 0 &&
36 !trapStack[trapStack.length - 1]._isManuallyPaused()
37 ) {
38 trapStack[trapStack.length - 1]._setPausedState(false);
39 }
40 },
41 };
42
43 const isSelectableInput = function (node) {
44 return (
45 node.tagName &&
46 node.tagName.toLowerCase() === 'input' &&
47 typeof node.select === 'function'
48 );
49 };
50
51 const isEscapeEvent = function (e) {
52 return e?.key === 'Escape' || e?.key === 'Esc' || e?.keyCode === 27;
53 };
54
55 const isTabEvent = function (e) {
56 return e?.key === 'Tab' || e?.keyCode === 9;
57 };
58
59 // checks for TAB by default
60 const isKeyForward = function (e) {
61 return isTabEvent(e) && !e.shiftKey;
62 };
63
64 // checks for SHIFT+TAB by default
65 const isKeyBackward = function (e) {
66 return isTabEvent(e) && e.shiftKey;
67 };
68
69 const delay = function (fn) {
70 return setTimeout(fn, 0);
71 };
72
73 /**
74 * Get an option's value when it could be a plain value, or a handler that provides
75 * the value.
76 * @param {*} value Option's value to check.
77 * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.
78 * @returns {*} The `value`, or the handler's returned value.
79 */
80 const valueOrHandler = function (value, ...params) {
81 return typeof value === 'function' ? value(...params) : value;
82 };
83
84 const getActualTarget = function (event) {
85 // NOTE: If the trap is _inside_ a shadow DOM, event.target will always be the
86 // shadow host. However, event.target.composedPath() will be an array of
87 // nodes "clicked" from inner-most (the actual element inside the shadow) to
88 // outer-most (the host HTML document). If we have access to composedPath(),
89 // then use its first element; otherwise, fall back to event.target (and
90 // this only works for an _open_ shadow DOM; otherwise,
91 // composedPath()[0] === event.target always).
92 return event.target.shadowRoot && typeof event.composedPath === 'function'
93 ? event.composedPath()[0]
94 : event.target;
95 };
96
97 // NOTE: this must be _outside_ `createFocusTrap()` to make sure all traps in this
98 // current instance use the same stack if `userOptions.trapStack` isn't specified
99 const internalTrapStack = [];
100
101 const createFocusTrap = function (elements, userOptions) {
102 // SSR: a live trap shouldn't be created in this type of environment so this
103 // should be safe code to execute if the `document` option isn't specified
104 const doc = userOptions?.document || document;
105
106 const trapStack = userOptions?.trapStack || internalTrapStack;
107
108 const config = {
109 returnFocusOnDeactivate: true,
110 escapeDeactivates: true,
111 delayInitialFocus: true,
112 isKeyForward,
113 isKeyBackward,
114 ...userOptions,
115 };
116
117 const state = {
118 // containers given to createFocusTrap()
119 // @type {Array<HTMLElement>}
120 containers: [],
121
122 // list of objects identifying tabbable nodes in `containers` in the trap
123 // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap
124 // is active, but the trap should never get to a state where there isn't at least one group
125 // with at least one tabbable node in it (that would lead to an error condition that would
126 // result in an error being thrown)
127 // @type {Array<{
128 // container: HTMLElement,
129 // tabbableNodes: Array<HTMLElement>, // empty if none
130 // focusableNodes: Array<HTMLElement>, // empty if none
131 // posTabIndexesFound: boolean,
132 // firstTabbableNode: HTMLElement|undefined,
133 // lastTabbableNode: HTMLElement|undefined,
134 // firstDomTabbableNode: HTMLElement|undefined,
135 // lastDomTabbableNode: HTMLElement|undefined,
136 // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined
137 // }>}
138 containerGroups: [], // same order/length as `containers` list
139
140 // references to objects in `containerGroups`, but only those that actually have
141 // tabbable nodes in them
142 // NOTE: same order as `containers` and `containerGroups`, but __not necessarily__
143 // the same length
144 tabbableGroups: [],
145
146 nodeFocusedBeforeActivation: null,
147 mostRecentlyFocusedNode: null,
148 active: false,
149 paused: false,
150 manuallyPaused: false,
151
152 // timer ID for when delayInitialFocus is true and initial focus in this trap
153 // has been delayed during activation
154 delayInitialFocusTimer: undefined,
155
156 // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any
157 recentNavEvent: undefined,
158 };
159
160 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
161
162 /**
163 * Gets a configuration option value.
164 * @param {Object|undefined} configOverrideOptions If true, and option is defined in this set,
165 * value will be taken from this object. Otherwise, value will be taken from base configuration.
166 * @param {string} optionName Name of the option whose value is sought.
167 * @param {string|undefined} [configOptionName] Name of option to use __instead of__ `optionName`
168 * IIF `configOverrideOptions` is not defined. Otherwise, `optionName` is used.
169 */
170 const getOption = (configOverrideOptions, optionName, configOptionName) => {
171 return configOverrideOptions &&
172 configOverrideOptions[optionName] !== undefined
173 ? configOverrideOptions[optionName]
174 : config[configOptionName || optionName];
175 };
176
177 /**
178 * Finds the index of the container that contains the element.
179 * @param {HTMLElement} element
180 * @param {Event} [event] If available, and `element` isn't directly found in any container,
181 * the event's composed path is used to see if includes any known trap containers in the
182 * case where the element is inside a Shadow DOM.
183 * @returns {number} Index of the container in either `state.containers` or
184 * `state.containerGroups` (the order/length of these lists are the same); -1
185 * if the element isn't found.
186 */
187 const findContainerIndex = function (element, event) {
188 const composedPath =
189 typeof event?.composedPath === 'function'
190 ? event.composedPath()
191 : undefined;
192 // NOTE: search `containerGroups` because it's possible a group contains no tabbable
193 // nodes, but still contains focusable nodes (e.g. if they all have `tabindex=-1`)
194 // and we still need to find the element in there
195 return state.containerGroups.findIndex(
196 ({ container, tabbableNodes }) =>
197 container.contains(element) ||
198 // fall back to explicit tabbable search which will take into consideration any
199 // web components if the `tabbableOptions.getShadowRoot` option was used for
200 // the trap, enabling shadow DOM support in tabbable (`Node.contains()` doesn't
201 // look inside web components even if open)
202 composedPath?.includes(container) ||
203 tabbableNodes.find((node) => node === element)
204 );
205 };
206
207 /**
208 * Gets the node for the given option, which is expected to be an option that
209 * can be either a DOM node, a string that is a selector to get a node, `false`
210 * (if a node is explicitly NOT given), or a function that returns any of these
211 * values.
212 * @param {string} optionName
213 * @param {Object} options
214 * @param {boolean} [options.hasFallback] True if the option could be a selector string
215 * and the option allows for a fallback scenario in the case where the selector is
216 * valid but does not match a node (i.e. the queried node doesn't exist in the DOM).
217 * @param {Array} [options.params] Params to pass to the option if it's a function.
218 * @returns {undefined | null | false | HTMLElement | SVGElement} Returns
219 * `undefined` if the option is not specified; `null` if the option didn't resolve
220 * to a node but `options.hasFallback=true`, `false` if the option resolved to `false`
221 * (node explicitly not given); otherwise, the resolved DOM node.
222 * @throws {Error} If the option is set, not `false`, and is not, or does not
223 * resolve to a node, unless the option is a selector string and `options.hasFallback=true`.
224 */
225 const getNodeForOption = function (
226 optionName,
227 { hasFallback = false, params = [] } = {}
228 ) {
229 let optionValue = config[optionName];
230
231 if (typeof optionValue === 'function') {
232 optionValue = optionValue(...params);
233 }
234
235 if (optionValue === true) {
236 optionValue = undefined; // use default value
237 }
238
239 if (!optionValue) {
240 if (optionValue === undefined || optionValue === false) {
241 return optionValue;
242 }
243 // else, empty string (invalid), null (invalid), 0 (invalid)
244
245 throw new Error(
246 `\`${optionName}\` was specified but was not a node, or did not return a node`
247 );
248 }
249
250 let node = optionValue; // could be HTMLElement, SVGElement, or non-empty string at this point
251
252 if (typeof optionValue === 'string') {
253 try {
254 node = doc.querySelector(optionValue); // resolve to node, or null if fails
255 } catch (err) {
256 throw new Error(
257 `\`${optionName}\` appears to be an invalid selector; error="${err.message}"`
258 );
259 }
260
261 if (!node) {
262 if (!hasFallback) {
263 throw new Error(
264 `\`${optionName}\` as selector refers to no known node`
265 );
266 }
267 // else, `node` MUST be `null` because that's what `Document.querySelector()` returns
268 // if the selector is valid but doesn't match anything
269 }
270 }
271
272 return node;
273 };
274
275 const getInitialFocusNode = function () {
276 let node = getNodeForOption('initialFocus', { hasFallback: true });
277
278 // false explicitly indicates we want no initialFocus at all
279 if (node === false) {
280 return false;
281 }
282
283 if (
284 node === undefined ||
285 (node && !isFocusable(node, config.tabbableOptions))
286 ) {
287 // option not specified nor focusable: use fallback options
288 if (findContainerIndex(doc.activeElement) >= 0) {
289 node = doc.activeElement;
290 } else {
291 const firstTabbableGroup = state.tabbableGroups[0];
292 const firstTabbableNode =
293 firstTabbableGroup && firstTabbableGroup.firstTabbableNode;
294
295 // NOTE: `fallbackFocus` option function cannot return `false` (not supported)
296 node = firstTabbableNode || getNodeForOption('fallbackFocus');
297 }
298 } else if (node === null) {
299 // option is a VALID selector string that doesn't yield a node: use the `fallbackFocus`
300 // option instead of the default behavior when the option isn't specified at all
301 node = getNodeForOption('fallbackFocus');
302 }
303
304 if (!node) {
305 throw new Error(
306 'Your focus-trap needs to have at least one focusable element'
307 );
308 }
309
310 return node;
311 };
312
313 const updateTabbableNodes = function () {
314 state.containerGroups = state.containers.map((container) => {
315 const tabbableNodes = tabbable(container, config.tabbableOptions);
316
317 // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes
318 // are a superset of tabbable nodes since nodes with negative `tabindex` attributes
319 // are focusable but not tabbable
320 const focusableNodes = focusable(container, config.tabbableOptions);
321
322 const firstTabbableNode =
323 tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;
324 const lastTabbableNode =
325 tabbableNodes.length > 0
326 ? tabbableNodes[tabbableNodes.length - 1]
327 : undefined;
328
329 const firstDomTabbableNode = focusableNodes.find((node) =>
330 isTabbable(node)
331 );
332 const lastDomTabbableNode = focusableNodes
333 .slice()
334 .reverse()
335 .find((node) => isTabbable(node));
336
337 const posTabIndexesFound = !!tabbableNodes.find(
338 (node) => getTabIndex(node) > 0
339 );
340
341 return {
342 container,
343 tabbableNodes,
344 focusableNodes,
345
346 /** True if at least one node with positive `tabindex` was found in this container. */
347 posTabIndexesFound,
348
349 /** First tabbable node in container, __tabindex__ order; `undefined` if none. */
350 firstTabbableNode,
351 /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */
352 lastTabbableNode,
353
354 // NOTE: DOM order is NOT NECESSARILY "document position" order, but figuring that out
355 // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
356 // because that API doesn't work with Shadow DOM as well as it should (@see
357 // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,
358 // to address an edge case related to positive tabindex support, this seems like a much easier,
359 // "close enough most of the time" alternative for positive tabindexes which should generally
360 // be avoided anyway...
361 /** First tabbable node in container, __DOM__ order; `undefined` if none. */
362 firstDomTabbableNode,
363 /** Last tabbable node in container, __DOM__ order; `undefined` if none. */
364 lastDomTabbableNode,
365
366 /**
367 * Finds the __tabbable__ node that follows the given node in the specified direction,
368 * in this container, if any.
369 * @param {HTMLElement} node
370 * @param {boolean} [forward] True if going in forward tab order; false if going
371 * in reverse.
372 * @returns {HTMLElement|undefined} The next tabbable node, if any.
373 */
374 nextTabbableNode(node, forward = true) {
375 const nodeIdx = tabbableNodes.indexOf(node);
376 if (nodeIdx < 0) {
377 // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):
378 // since `node` should at least have been focusable, we assume that's the case and mimic
379 // what browsers do, which is set focus to the next node in __document position order__,
380 // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE
381 // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to
382 // basic DOM order
383 if (forward) {
384 return focusableNodes
385 .slice(focusableNodes.indexOf(node) + 1)
386 .find((el) => isTabbable(el));
387 }
388
389 return focusableNodes
390 .slice(0, focusableNodes.indexOf(node))
391 .reverse()
392 .find((el) => isTabbable(el));
393 }
394
395 return tabbableNodes[nodeIdx + (forward ? 1 : -1)];
396 },
397 };
398 });
399
400 state.tabbableGroups = state.containerGroups.filter(
401 (group) => group.tabbableNodes.length > 0
402 );
403
404 // throw if no groups have tabbable nodes and we don't have a fallback focus node either
405 if (
406 state.tabbableGroups.length <= 0 &&
407 !getNodeForOption('fallbackFocus') // returning false not supported for this option
408 ) {
409 throw new Error(
410 'Your focus-trap must have at least one container with at least one tabbable node in it at all times'
411 );
412 }
413
414 // NOTE: Positive tabindexes are only properly supported in single-container traps because
415 // doing it across multiple containers where tabindexes could be all over the place
416 // would require Tabbable to support multiple containers, would require additional
417 // specialized Shadow DOM support, and would require Tabbable's multi-container support
418 // to look at those containers in document position order rather than user-provided
419 // order (as they are treated in Focus-trap, for legacy reasons). See discussion on
420 // https://github.com/focus-trap/focus-trap/issues/375 for more details.
421 if (
422 state.containerGroups.find((g) => g.posTabIndexesFound) &&
423 state.containerGroups.length > 1
424 ) {
425 throw new Error(
426 "At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps."
427 );
428 }
429 };
430
431 /**
432 * Gets the current activeElement. If it's a web-component and has open shadow-root
433 * it will recursively search inside shadow roots for the "true" activeElement.
434 *
435 * @param {Document | ShadowRoot} el
436 *
437 * @returns {HTMLElement} The element that currently has the focus
438 **/
439 const getActiveElement = function (el) {
440 const activeElement = el.activeElement;
441
442 if (!activeElement) {
443 return;
444 }
445
446 if (
447 activeElement.shadowRoot &&
448 activeElement.shadowRoot.activeElement !== null
449 ) {
450 return getActiveElement(activeElement.shadowRoot);
451 }
452
453 return activeElement;
454 };
455
456 const tryFocus = function (node) {
457 if (node === false) {
458 return;
459 }
460
461 if (node === getActiveElement(document)) {
462 return;
463 }
464
465 if (!node || !node.focus) {
466 tryFocus(getInitialFocusNode());
467 return;
468 }
469
470 node.focus({ preventScroll: !!config.preventScroll });
471 // NOTE: focus() API does not trigger focusIn event so set MRU node manually
472 state.mostRecentlyFocusedNode = node;
473
474 if (isSelectableInput(node)) {
475 node.select();
476 }
477 };
478
479 const getReturnFocusNode = function (previousActiveElement) {
480 const node = getNodeForOption('setReturnFocus', {
481 params: [previousActiveElement],
482 });
483 return node ? node : node === false ? false : previousActiveElement;
484 };
485
486 /**
487 * Finds the next node (in either direction) where focus should move according to a
488 * keyboard focus-in event.
489 * @param {Object} params
490 * @param {Node} [params.target] Known target __from which__ to navigate, if any.
491 * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event
492 * will be used to determine the `target`). Ignored if `target` is specified.
493 * @param {boolean} [params.isBackward] True if focus should move backward.
494 * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be
495 * determined given the current state of the trap.
496 */
497 const findNextNavNode = function ({ target, event, isBackward = false }) {
498 target = target || getActualTarget(event);
499 updateTabbableNodes();
500
501 let destinationNode = null;
502
503 if (state.tabbableGroups.length > 0) {
504 // make sure the target is actually contained in a group
505 // NOTE: the target may also be the container itself if it's focusable
506 // with tabIndex='-1' and was given initial focus
507 const containerIndex = findContainerIndex(target, event);
508 const containerGroup =
509 containerIndex >= 0 ? state.containerGroups[containerIndex] : undefined;
510
511 if (containerIndex < 0) {
512 // target not found in any group: quite possible focus has escaped the trap,
513 // so bring it back into...
514 if (isBackward) {
515 // ...the last node in the last group
516 destinationNode =
517 state.tabbableGroups[state.tabbableGroups.length - 1]
518 .lastTabbableNode;
519 } else {
520 // ...the first node in the first group
521 destinationNode = state.tabbableGroups[0].firstTabbableNode;
522 }
523 } else if (isBackward) {
524 // REVERSE
525
526 // is the target the first tabbable node in a group?
527 let startOfGroupIndex = state.tabbableGroups.findIndex(
528 ({ firstTabbableNode }) => target === firstTabbableNode
529 );
530
531 if (
532 startOfGroupIndex < 0 &&
533 (containerGroup.container === target ||
534 (isFocusable(target, config.tabbableOptions) &&
535 !isTabbable(target, config.tabbableOptions) &&
536 !containerGroup.nextTabbableNode(target, false)))
537 ) {
538 // an exception case where the target is either the container itself, or
539 // a non-tabbable node that was given focus (i.e. tabindex is negative
540 // and user clicked on it or node was programmatically given focus)
541 // and is not followed by any other tabbable node, in which
542 // case, we should handle shift+tab as if focus were on the container's
543 // first tabbable node, and go to the last tabbable node of the LAST group
544 startOfGroupIndex = containerIndex;
545 }
546
547 if (startOfGroupIndex >= 0) {
548 // YES: then shift+tab should go to the last tabbable node in the
549 // previous group (and wrap around to the last tabbable node of
550 // the LAST group if it's the first tabbable node of the FIRST group)
551 const destinationGroupIndex =
552 startOfGroupIndex === 0
553 ? state.tabbableGroups.length - 1
554 : startOfGroupIndex - 1;
555
556 const destinationGroup = state.tabbableGroups[destinationGroupIndex];
557
558 destinationNode =
559 getTabIndex(target) >= 0
560 ? destinationGroup.lastTabbableNode
561 : destinationGroup.lastDomTabbableNode;
562 } else if (!isTabEvent(event)) {
563 // user must have customized the nav keys so we have to move focus manually _within_
564 // the active group: do this based on the order determined by tabbable()
565 destinationNode = containerGroup.nextTabbableNode(target, false);
566 }
567 } else {
568 // FORWARD
569
570 // is the target the last tabbable node in a group?
571 let lastOfGroupIndex = state.tabbableGroups.findIndex(
572 ({ lastTabbableNode }) => target === lastTabbableNode
573 );
574
575 if (
576 lastOfGroupIndex < 0 &&
577 (containerGroup.container === target ||
578 (isFocusable(target, config.tabbableOptions) &&
579 !isTabbable(target, config.tabbableOptions) &&
580 !containerGroup.nextTabbableNode(target)))
581 ) {
582 // an exception case where the target is the container itself, or
583 // a non-tabbable node that was given focus (i.e. tabindex is negative
584 // and user clicked on it or node was programmatically given focus)
585 // and is not followed by any other tabbable node, in which
586 // case, we should handle tab as if focus were on the container's
587 // last tabbable node, and go to the first tabbable node of the FIRST group
588 lastOfGroupIndex = containerIndex;
589 }
590
591 if (lastOfGroupIndex >= 0) {
592 // YES: then tab should go to the first tabbable node in the next
593 // group (and wrap around to the first tabbable node of the FIRST
594 // group if it's the last tabbable node of the LAST group)
595 const destinationGroupIndex =
596 lastOfGroupIndex === state.tabbableGroups.length - 1
597 ? 0
598 : lastOfGroupIndex + 1;
599
600 const destinationGroup = state.tabbableGroups[destinationGroupIndex];
601
602 destinationNode =
603 getTabIndex(target) >= 0
604 ? destinationGroup.firstTabbableNode
605 : destinationGroup.firstDomTabbableNode;
606 } else if (!isTabEvent(event)) {
607 // user must have customized the nav keys so we have to move focus manually _within_
608 // the active group: do this based on the order determined by tabbable()
609 destinationNode = containerGroup.nextTabbableNode(target);
610 }
611 }
612 } else {
613 // no groups available
614 // NOTE: the fallbackFocus option does not support returning false to opt-out
615 destinationNode = getNodeForOption('fallbackFocus');
616 }
617
618 return destinationNode;
619 };
620
621 // This needs to be done on mousedown and touchstart instead of click
622 // so that it precedes the focus event.
623 const checkPointerDown = function (e) {
624 const target = getActualTarget(e);
625
626 if (findContainerIndex(target, e) >= 0) {
627 // allow the click since it ocurred inside the trap
628 return;
629 }
630
631 if (valueOrHandler(config.clickOutsideDeactivates, e)) {
632 // immediately deactivate the trap
633 trap.deactivate({
634 // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
635 // which will result in the outside click setting focus to the node
636 // that was clicked (and if not focusable, to "nothing"); by setting
637 // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
638 // on activation (or the configured `setReturnFocus` node), whether the
639 // outside click was on a focusable node or not
640 returnFocus: config.returnFocusOnDeactivate,
641 });
642 return;
643 }
644
645 // This is needed for mobile devices.
646 // (If we'll only let `click` events through,
647 // then on mobile they will be blocked anyways if `touchstart` is blocked.)
648 if (valueOrHandler(config.allowOutsideClick, e)) {
649 // allow the click outside the trap to take place
650 return;
651 }
652
653 // otherwise, prevent the click
654 e.preventDefault();
655 };
656
657 // In case focus escapes the trap for some strange reason, pull it back in.
658 // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected
659 // scrolling if the node that got focused was out of view; there's nothing we can do to
660 // prevent that from happening by the time we discover that focus escaped
661 const checkFocusIn = function (event) {
662 const target = getActualTarget(event);
663 const targetContained = findContainerIndex(target, event) >= 0;
664
665 // In Firefox when you Tab out of an iframe the Document is briefly focused.
666 if (targetContained || target instanceof Document) {
667 if (targetContained) {
668 state.mostRecentlyFocusedNode = target;
669 }
670 } else {
671 // escaped! pull it back in to where it just left
672 event.stopImmediatePropagation();
673
674 // focus will escape if the MRU node had a positive tab index and user tried to nav forward;
675 // it will also escape if the MRU node had a 0 tab index and user tried to nav backward
676 // toward a node with a positive tab index
677 let nextNode; // next node to focus, if we find one
678 let navAcrossContainers = true;
679 if (state.mostRecentlyFocusedNode) {
680 if (getTabIndex(state.mostRecentlyFocusedNode) > 0) {
681 // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...
682 const mruContainerIdx = findContainerIndex(
683 state.mostRecentlyFocusedNode
684 );
685 // there MAY not be any tabbable nodes in the container if there are at least 2 containers
686 // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container
687 // with at least one tabbable node in order to function, so this could be the other container
688 // with nothing tabbable in it)
689 const { tabbableNodes } = state.containerGroups[mruContainerIdx];
690 if (tabbableNodes.length > 0) {
691 // MRU tab index MAY not be found if the MRU node is focusable but not tabbable
692 const mruTabIdx = tabbableNodes.findIndex(
693 (node) => node === state.mostRecentlyFocusedNode
694 );
695 if (mruTabIdx >= 0) {
696 if (config.isKeyForward(state.recentNavEvent)) {
697 if (mruTabIdx + 1 < tabbableNodes.length) {
698 nextNode = tabbableNodes[mruTabIdx + 1];
699 navAcrossContainers = false;
700 }
701 // else, don't wrap within the container as focus should move to next/previous
702 // container
703 } else {
704 if (mruTabIdx - 1 >= 0) {
705 nextNode = tabbableNodes[mruTabIdx - 1];
706 navAcrossContainers = false;
707 }
708 // else, don't wrap within the container as focus should move to next/previous
709 // container
710 }
711 // else, don't find in container order without considering direction too
712 }
713 }
714 // else, no tabbable nodes in that container (which means we must have at least one other
715 // container with at least one tabbable node in it, otherwise focus-trap would've thrown
716 // an error the last time updateTabbableNodes() was run): find next node among all known
717 // containers
718 } else {
719 // check to see if there's at least one tabbable node with a positive tab index inside
720 // the trap because focus seems to escape when navigating backward from a tabbable node
721 // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with
722 // the greatest positive tab index like it should)
723 if (
724 !state.containerGroups.some((g) =>
725 g.tabbableNodes.some((n) => getTabIndex(n) > 0)
726 )
727 ) {
728 // no containers with tabbable nodes with positive tab indexes which means the focus
729 // escaped for some other reason and we should just execute the fallback to the
730 // MRU node or initial focus node, if any
731 navAcrossContainers = false;
732 }
733 }
734 } else {
735 // no MRU node means we're likely in some initial condition when the trap has just
736 // been activated and initial focus hasn't been given yet, in which case we should
737 // fall through to trying to focus the initial focus node, which is what should
738 // happen below at this point in the logic
739 navAcrossContainers = false;
740 }
741
742 if (navAcrossContainers) {
743 nextNode = findNextNavNode({
744 // move FROM the MRU node, not event-related node (which will be the node that is
745 // outside the trap causing the focus escape we're trying to fix)
746 target: state.mostRecentlyFocusedNode,
747 isBackward: config.isKeyBackward(state.recentNavEvent),
748 });
749 }
750
751 if (nextNode) {
752 tryFocus(nextNode);
753 } else {
754 tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
755 }
756 }
757
758 state.recentNavEvent = undefined; // clear
759 };
760
761 // Hijack key nav events on the first and last focusable nodes of the trap,
762 // in order to prevent focus from escaping. If it escapes for even a
763 // moment it can end up scrolling the page and causing confusion so we
764 // kind of need to capture the action at the keydown phase.
765 const checkKeyNav = function (event, isBackward = false) {
766 state.recentNavEvent = event;
767
768 const destinationNode = findNextNavNode({ event, isBackward });
769 if (destinationNode) {
770 if (isTabEvent(event)) {
771 // since tab natively moves focus, we wouldn't have a destination node unless we
772 // were on the edge of a container and had to move to the next/previous edge, in
773 // which case we want to prevent default to keep the browser from moving focus
774 // to where it normally would
775 event.preventDefault();
776 }
777 tryFocus(destinationNode);
778 }
779 // else, let the browser take care of [shift+]tab and move the focus
780 };
781
782 const checkTabKey = function (event) {
783 if (config.isKeyForward(event) || config.isKeyBackward(event)) {
784 checkKeyNav(event, config.isKeyBackward(event));
785 }
786 };
787
788 // we use a different event phase for the Escape key to allow canceling the event and checking for this in escapeDeactivates
789 const checkEscapeKey = function (event) {
790 if (
791 isEscapeEvent(event) &&
792 valueOrHandler(config.escapeDeactivates, event) !== false
793 ) {
794 event.preventDefault();
795 trap.deactivate();
796 }
797 };
798
799 const checkClick = function (e) {
800 const target = getActualTarget(e);
801
802 if (findContainerIndex(target, e) >= 0) {
803 return;
804 }
805
806 if (valueOrHandler(config.clickOutsideDeactivates, e)) {
807 return;
808 }
809
810 if (valueOrHandler(config.allowOutsideClick, e)) {
811 return;
812 }
813
814 e.preventDefault();
815 e.stopImmediatePropagation();
816 };
817
818 //
819 // EVENT LISTENERS
820 //
821
822 const addListeners = function () {
823 if (!state.active) {
824 return;
825 }
826
827 // There can be only one listening focus trap at a time
828 activeFocusTraps.activateTrap(trapStack, trap);
829
830 // Delay ensures that the focused element doesn't capture the event
831 // that caused the focus trap activation.
832 state.delayInitialFocusTimer = config.delayInitialFocus
833 ? delay(function () {
834 tryFocus(getInitialFocusNode());
835 })
836 : tryFocus(getInitialFocusNode());
837
838 doc.addEventListener('focusin', checkFocusIn, true);
839 doc.addEventListener('mousedown', checkPointerDown, {
840 capture: true,
841 passive: false,
842 });
843 doc.addEventListener('touchstart', checkPointerDown, {
844 capture: true,
845 passive: false,
846 });
847 doc.addEventListener('click', checkClick, {
848 capture: true,
849 passive: false,
850 });
851 doc.addEventListener('keydown', checkTabKey, {
852 capture: true,
853 passive: false,
854 });
855 doc.addEventListener('keydown', checkEscapeKey);
856
857 return trap;
858 };
859
860 const removeListeners = function () {
861 if (!state.active) {
862 return;
863 }
864
865 doc.removeEventListener('focusin', checkFocusIn, true);
866 doc.removeEventListener('mousedown', checkPointerDown, true);
867 doc.removeEventListener('touchstart', checkPointerDown, true);
868 doc.removeEventListener('click', checkClick, true);
869 doc.removeEventListener('keydown', checkTabKey, true);
870 doc.removeEventListener('keydown', checkEscapeKey);
871
872 return trap;
873 };
874
875 //
876 // MUTATION OBSERVER
877 //
878
879 const checkDomRemoval = function (mutations) {
880 const isFocusedNodeRemoved = mutations.some(function (mutation) {
881 const removedNodes = Array.from(mutation.removedNodes);
882 return removedNodes.some(function (node) {
883 return node === state.mostRecentlyFocusedNode;
884 });
885 });
886
887 // If the currently focused is removed then browsers will move focus to the
888 // <body> element. If this happens, try to move focus back into the trap.
889 if (isFocusedNodeRemoved) {
890 tryFocus(getInitialFocusNode());
891 }
892 };
893
894 // Use MutationObserver - if supported - to detect if focused node is removed
895 // from the DOM.
896 const mutationObserver =
897 typeof window !== 'undefined' && 'MutationObserver' in window
898 ? new MutationObserver(checkDomRemoval)
899 : undefined;
900
901 const updateObservedNodes = function () {
902 if (!mutationObserver) {
903 return;
904 }
905
906 mutationObserver.disconnect();
907 if (state.active && !state.paused) {
908 state.containers.map(function (container) {
909 mutationObserver.observe(container, {
910 subtree: true,
911 childList: true,
912 });
913 });
914 }
915 };
916
917 //
918 // TRAP DEFINITION
919 //
920
921 trap = {
922 get active() {
923 return state.active;
924 },
925
926 get paused() {
927 return state.paused;
928 },
929
930 activate(activateOptions) {
931 if (state.active) {
932 return this;
933 }
934
935 const onActivate = getOption(activateOptions, 'onActivate');
936 const onPostActivate = getOption(activateOptions, 'onPostActivate');
937 const checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');
938
939 if (!checkCanFocusTrap) {
940 updateTabbableNodes();
941 }
942
943 state.active = true;
944 state.paused = false;
945 state.nodeFocusedBeforeActivation = getActiveElement(doc);
946
947 onActivate?.();
948
949 const finishActivation = () => {
950 if (checkCanFocusTrap) {
951 updateTabbableNodes();
952 }
953 addListeners();
954 updateObservedNodes();
955 onPostActivate?.();
956 };
957
958 if (checkCanFocusTrap) {
959 checkCanFocusTrap(state.containers.concat()).then(
960 finishActivation,
961 finishActivation
962 );
963 return this;
964 }
965
966 finishActivation();
967 return this;
968 },
969
970 deactivate(deactivateOptions) {
971 if (!state.active) {
972 return this;
973 }
974
975 const options = {
976 onDeactivate: config.onDeactivate,
977 onPostDeactivate: config.onPostDeactivate,
978 checkCanReturnFocus: config.checkCanReturnFocus,
979 ...deactivateOptions,
980 };
981
982 clearTimeout(state.delayInitialFocusTimer); // noop if undefined
983 state.delayInitialFocusTimer = undefined;
984
985 removeListeners();
986 state.active = false;
987 state.paused = false;
988 updateObservedNodes();
989
990 activeFocusTraps.deactivateTrap(trapStack, trap);
991
992 const onDeactivate = getOption(options, 'onDeactivate');
993 const onPostDeactivate = getOption(options, 'onPostDeactivate');
994 const checkCanReturnFocus = getOption(options, 'checkCanReturnFocus');
995 const returnFocus = getOption(
996 options,
997 'returnFocus',
998 'returnFocusOnDeactivate'
999 );
1000
1001 onDeactivate?.();
1002
1003 const finishDeactivation = () => {
1004 delay(() => {
1005 if (returnFocus) {
1006 tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));
1007 }
1008 onPostDeactivate?.();
1009 });
1010 };
1011
1012 if (returnFocus && checkCanReturnFocus) {
1013 checkCanReturnFocus(
1014 getReturnFocusNode(state.nodeFocusedBeforeActivation)
1015 ).then(finishDeactivation, finishDeactivation);
1016 return this;
1017 }
1018
1019 finishDeactivation();
1020 return this;
1021 },
1022
1023 pause(pauseOptions) {
1024 if (!state.active) {
1025 return this;
1026 }
1027
1028 state.manuallyPaused = true;
1029
1030 return this._setPausedState(true, pauseOptions);
1031 },
1032
1033 unpause(unpauseOptions) {
1034 if (!state.active) {
1035 return this;
1036 }
1037
1038 state.manuallyPaused = false;
1039
1040 if (trapStack[trapStack.length - 1] !== this) {
1041 return this;
1042 }
1043
1044 return this._setPausedState(false, unpauseOptions);
1045 },
1046
1047 updateContainerElements(containerElements) {
1048 const elementsAsArray = [].concat(containerElements).filter(Boolean);
1049
1050 state.containers = elementsAsArray.map((element) =>
1051 typeof element === 'string' ? doc.querySelector(element) : element
1052 );
1053
1054 if (state.active) {
1055 updateTabbableNodes();
1056 }
1057
1058 updateObservedNodes();
1059
1060 return this;
1061 },
1062 };
1063
1064 Object.defineProperties(trap, {
1065 _isManuallyPaused: {
1066 value() {
1067 return state.manuallyPaused;
1068 },
1069 },
1070 _setPausedState: {
1071 value(paused, options) {
1072 if (state.paused === paused) {
1073 return this;
1074 }
1075
1076 state.paused = paused;
1077 if (paused) {
1078 const onPause = getOption(options, 'onPause');
1079 const onPostPause = getOption(options, 'onPostPause');
1080 onPause?.();
1081
1082 removeListeners();
1083 updateObservedNodes();
1084
1085 onPostPause?.();
1086 } else {
1087 const onUnpause = getOption(options, 'onUnpause');
1088 const onPostUnpause = getOption(options, 'onPostUnpause');
1089
1090 onUnpause?.();
1091
1092 updateTabbableNodes();
1093 addListeners();
1094 updateObservedNodes();
1095
1096 onPostUnpause?.();
1097 }
1098
1099 return this;
1100 },
1101 },
1102 });
1103
1104 // initialize container elements
1105 trap.updateContainerElements(elements);
1106
1107 return trap;
1108 };
1109
1110 export { createFocusTrap };