Debian Codegraph @

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

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