Debian Codegraph @

node/focus-trap/dist/focus-trap.esm.js

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