focus-trap 7.4.3 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 7.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5e2f913: Adds support for nodes with a positive tabindex in single-container traps only ([#375](https://github.com/focus-trap/focus-trap/issues/375))
8
+
3
9
  ## 7.4.3
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -144,6 +144,18 @@ Returns a new focus trap on `element` (one or more "containers" of tabbable node
144
144
 
145
145
  If you have closed shadow roots that you would like considered for tabbable/focusable nodes, use the `tabbableOptions.getShadowRoot` option to provide Tabbable (used internally) with a reference to a given node's shadow root so that it can be searched for candidates.
146
146
 
147
+ #### Positive Tabindexes
148
+
149
+ ⚠️ Using positive tab indexes (i.e. `<button tabindex="1">Label</button>`) [is not recommended](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex#accessibility_concerns), primarily for accessibility reasons. Supporting them properly also means a lot of hoops to jump through when Shadow DOM is used as some key DOM APIs like [Node.compareDocumentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition) [do not](https://github.com/whatwg/dom/issues/320) properly support Shadow DOM.
150
+
151
+ As such, focus-trap considers using positive tabindexes an edge case and only supports them in __single-container__ traps with some caveats for related edge case behavior (see the [demo](https://focus-trap.github.io/focus-trap/#demo-positive-tabindex) for more details).
152
+
153
+ If you try to create a multi-container trap where at least one container has one node with a positive tabindex, an exception will be thrown:
154
+
155
+ ```
156
+ 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.
157
+ ```
158
+
147
159
  ### trap.active
148
160
 
149
161
  ```typescript
@@ -353,7 +365,7 @@ In alphabetical order:
353
365
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/bparish628"><img src="https://avatars1.githubusercontent.com/u/8492971?v=4?s=100" width="100px;" alt="Benjamin Parish"/><br /><sub><b>Benjamin Parish</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/issues?q=author%3Abparish628" title="Bug reports">🐛</a></td>
354
366
  <td align="center" valign="top" width="14.28%"><a href="https://clintgoodman.com"><img src="https://avatars3.githubusercontent.com/u/5473697?v=4?s=100" width="100px;" alt="Clint Goodman"/><br /><sub><b>Clint Goodman</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/commits?author=cgood92" title="Code">💻</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=cgood92" title="Documentation">📖</a> <a href="#example-cgood92" title="Examples">💡</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=cgood92" title="Tests">⚠️</a></td>
355
367
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/Dan503"><img src="https://avatars.githubusercontent.com/u/10610368?v=4?s=100" width="100px;" alt="Daniel Tonon"/><br /><sub><b>Daniel Tonon</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/commits?author=Dan503" title="Documentation">📖</a> <a href="#tool-Dan503" title="Tools">🔧</a> <a href="#a11y-Dan503" title="Accessibility">️️️️♿️</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=Dan503" title="Code">💻</a></td>
356
- <td align="center" valign="top" width="14.28%"><a href="https://github.com/DaviDevMod"><img src="https://avatars.githubusercontent.com/u/98312056?v=4?s=100" width="100px;" alt="DaviDevMod"/><br /><sub><b>DaviDevMod</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/commits?author=DaviDevMod" title="Documentation">📖</a></td>
368
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/DaviDevMod"><img src="https://avatars.githubusercontent.com/u/98312056?v=4?s=100" width="100px;" alt="DaviDevMod"/><br /><sub><b>DaviDevMod</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/commits?author=DaviDevMod" title="Documentation">📖</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=DaviDevMod" title="Code">💻</a> <a href="https://github.com/focus-trap/focus-trap/issues?q=author%3ADaviDevMod" title="Bug reports">🐛</a></td>
357
369
  <td align="center" valign="top" width="14.28%"><a href="http://davidtheclark.com/"><img src="https://avatars2.githubusercontent.com/u/628431?v=4?s=100" width="100px;" alt="David Clark"/><br /><sub><b>David Clark</b></sub></a><br /><a href="https://github.com/focus-trap/focus-trap/commits?author=davidtheclark" title="Code">💻</a> <a href="https://github.com/focus-trap/focus-trap/issues?q=author%3Adavidtheclark" title="Bug reports">🐛</a> <a href="#infra-davidtheclark" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=davidtheclark" title="Tests">⚠️</a> <a href="https://github.com/focus-trap/focus-trap/commits?author=davidtheclark" title="Documentation">📖</a> <a href="#maintenance-davidtheclark" title="Maintenance">🚧</a></td>
358
370
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/features/security"><img src="https://avatars1.githubusercontent.com/u/27347476?v=4?s=100" width="100px;" alt="Dependabot"/><br /><sub><b>Dependabot</b></sub></a><br /><a href="#maintenance-dependabot" title="Maintenance">🚧</a></td>
359
371
  </tr>
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * focus-trap 7.4.3
2
+ * focus-trap 7.5.0
3
3
  * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
4
4
  */
5
- import { isFocusable, tabbable, focusable, isTabbable } from 'tabbable';
5
+ import { isFocusable, tabbable, focusable, isTabbable, getTabIndex } from 'tabbable';
6
6
 
7
7
  function ownKeys(object, enumerableOnly) {
8
8
  var keys = Object.keys(object);
@@ -85,10 +85,10 @@ var isSelectableInput = function isSelectableInput(node) {
85
85
  return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';
86
86
  };
87
87
  var isEscapeEvent = function isEscapeEvent(e) {
88
- return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;
88
+ 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;
89
89
  };
90
90
  var isTabEvent = function isTabEvent(e) {
91
- return e.key === 'Tab' || e.keyCode === 9;
91
+ return (e === null || e === void 0 ? void 0 : e.key) === 'Tab' || (e === null || e === void 0 ? void 0 : e.keyCode) === 9;
92
92
  };
93
93
 
94
94
  // checks for TAB by default
@@ -172,8 +172,11 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
172
172
  // container: HTMLElement,
173
173
  // tabbableNodes: Array<HTMLElement>, // empty if none
174
174
  // focusableNodes: Array<HTMLElement>, // empty if none
175
- // firstTabbableNode: HTMLElement|null,
176
- // lastTabbableNode: HTMLElement|null,
175
+ // posTabIndexesFound: boolean,
176
+ // firstTabbableNode: HTMLElement|undefined,
177
+ // lastTabbableNode: HTMLElement|undefined,
178
+ // firstDomTabbableNode: HTMLElement|undefined,
179
+ // lastDomTabbableNode: HTMLElement|undefined,
177
180
  // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined
178
181
  // }>}
179
182
  containerGroups: [],
@@ -190,7 +193,9 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
190
193
  paused: false,
191
194
  // timer ID for when delayInitialFocus is true and initial focus in this trap
192
195
  // has been delayed during activation
193
- delayInitialFocusTimer: undefined
196
+ delayInitialFocusTimer: undefined,
197
+ // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any
198
+ recentNavEvent: undefined
194
199
  };
195
200
  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
196
201
 
@@ -209,7 +214,9 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
209
214
  /**
210
215
  * Finds the index of the container that contains the element.
211
216
  * @param {HTMLElement} element
212
- * @param {Event} [event]
217
+ * @param {Event} [event] If available, and `element` isn't directly found in any container,
218
+ * the event's composed path is used to see if includes any known trap containers in the
219
+ * case where the element is inside a Shadow DOM.
213
220
  * @returns {number} Index of the container in either `state.containers` or
214
221
  * `state.containerGroups` (the order/length of these lists are the same); -1
215
222
  * if the element isn't found.
@@ -304,14 +311,41 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
304
311
  var tabbableNodes = tabbable(container, config.tabbableOptions);
305
312
 
306
313
  // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes
307
- // are a superset of tabbable nodes
314
+ // are a superset of tabbable nodes since nodes with negative `tabindex` attributes
315
+ // are focusable but not tabbable
308
316
  var focusableNodes = focusable(container, config.tabbableOptions);
317
+ var firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;
318
+ var lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : undefined;
319
+ var firstDomTabbableNode = focusableNodes.find(function (node) {
320
+ return isTabbable(node);
321
+ });
322
+ var lastDomTabbableNode = focusableNodes.findLast(function (node) {
323
+ return isTabbable(node);
324
+ });
325
+ var posTabIndexesFound = !!tabbableNodes.find(function (node) {
326
+ return getTabIndex(node) > 0;
327
+ });
309
328
  return {
310
329
  container: container,
311
330
  tabbableNodes: tabbableNodes,
312
331
  focusableNodes: focusableNodes,
313
- firstTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[0] : null,
314
- lastTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : null,
332
+ /** True if at least one node with positive `tabindex` was found in this container. */
333
+ posTabIndexesFound: posTabIndexesFound,
334
+ /** First tabbable node in container, __tabindex__ order; `undefined` if none. */
335
+ firstTabbableNode: firstTabbableNode,
336
+ /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */
337
+ lastTabbableNode: lastTabbableNode,
338
+ // NOTE: DOM order is NOT NECESSARILY "document position" order, but figuring that out
339
+ // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
340
+ // because that API doesn't work with Shadow DOM as well as it should (@see
341
+ // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,
342
+ // to address an edge case related to positive tabindex support, this seems like a much easier,
343
+ // "close enough most of the time" alternative for positive tabindexes which should generally
344
+ // be avoided anyway...
345
+ /** First tabbable node in container, __DOM__ order; `undefined` if none. */
346
+ firstDomTabbableNode: firstDomTabbableNode,
347
+ /** Last tabbable node in container, __DOM__ order; `undefined` if none. */
348
+ lastDomTabbableNode: lastDomTabbableNode,
315
349
  /**
316
350
  * Finds the __tabbable__ node that follows the given node in the specified direction,
317
351
  * in this container, if any.
@@ -322,30 +356,24 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
322
356
  */
323
357
  nextTabbableNode: function nextTabbableNode(node) {
324
358
  var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
325
- // NOTE: If tabindex is positive (in order to manipulate the tab order separate
326
- // from the DOM order), this __will not work__ because the list of focusableNodes,
327
- // while it contains tabbable nodes, does not sort its nodes in any order other
328
- // than DOM order, because it can't: Where would you place focusable (but not
329
- // tabbable) nodes in that order? They have no order, because they aren't tabbale...
330
- // Support for positive tabindex is already broken and hard to manage (possibly
331
- // not supportable, TBD), so this isn't going to make things worse than they
332
- // already are, and at least makes things better for the majority of cases where
333
- // tabindex is either 0/unset or negative.
334
- // FYI, positive tabindex issue: https://github.com/focus-trap/focus-trap/issues/375
335
- var nodeIdx = focusableNodes.findIndex(function (n) {
336
- return n === node;
337
- });
359
+ var nodeIdx = tabbableNodes.indexOf(node);
338
360
  if (nodeIdx < 0) {
339
- return undefined;
340
- }
341
- if (forward) {
342
- return focusableNodes.slice(nodeIdx + 1).find(function (n) {
343
- return isTabbable(n, config.tabbableOptions);
361
+ // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):
362
+ // since `node` should at least have been focusable, we assume that's the case and mimic
363
+ // what browsers do, which is set focus to the next node in __document position order__,
364
+ // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE
365
+ // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to
366
+ // basic DOM order
367
+ if (forward) {
368
+ return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find(function (el) {
369
+ return isTabbable(el);
370
+ });
371
+ }
372
+ return focusableNodes.slice(0, focusableNodes.indexOf(node)).findLast(function (el) {
373
+ return isTabbable(el);
344
374
  });
345
375
  }
346
- return focusableNodes.slice(0, nodeIdx).reverse().find(function (n) {
347
- return isTabbable(n, config.tabbableOptions);
348
- });
376
+ return tabbableNodes[nodeIdx + (forward ? 1 : -1)];
349
377
  }
350
378
  };
351
379
  });
@@ -358,6 +386,19 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
358
386
  ) {
359
387
  throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');
360
388
  }
389
+
390
+ // NOTE: Positive tabindexes are only properly supported in single-container traps because
391
+ // doing it across multiple containers where tabindexes could be all over the place
392
+ // would require Tabbable to support multiple containers, would require additional
393
+ // specialized Shadow DOM support, and would require Tabbable's multi-container support
394
+ // to look at those containers in document position order rather than user-provided
395
+ // order (as they are treated in Focus-trap, for legacy reasons). See discussion on
396
+ // https://github.com/focus-trap/focus-trap/issues/375 for more details.
397
+ if (state.containerGroups.find(function (g) {
398
+ return g.posTabIndexesFound;
399
+ }) && state.containerGroups.length > 1) {
400
+ 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.");
401
+ }
361
402
  };
362
403
  var tryFocus = function tryFocus(node) {
363
404
  if (node === false) {
@@ -373,6 +414,7 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
373
414
  node.focus({
374
415
  preventScroll: !!config.preventScroll
375
416
  });
417
+ // NOTE: focus() API does not trigger focusIn event so set MRU node manually
376
418
  state.mostRecentlyFocusedNode = node;
377
419
  if (isSelectableInput(node)) {
378
420
  node.select();
@@ -383,64 +425,23 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
383
425
  return node ? node : node === false ? false : previousActiveElement;
384
426
  };
385
427
 
386
- // This needs to be done on mousedown and touchstart instead of click
387
- // so that it precedes the focus event.
388
- var checkPointerDown = function checkPointerDown(e) {
389
- var target = getActualTarget(e);
390
- if (findContainerIndex(target, e) >= 0) {
391
- // allow the click since it ocurred inside the trap
392
- return;
393
- }
394
- if (valueOrHandler(config.clickOutsideDeactivates, e)) {
395
- // immediately deactivate the trap
396
- trap.deactivate({
397
- // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
398
- // which will result in the outside click setting focus to the node
399
- // that was clicked (and if not focusable, to "nothing"); by setting
400
- // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
401
- // on activation (or the configured `setReturnFocus` node), whether the
402
- // outside click was on a focusable node or not
403
- returnFocus: config.returnFocusOnDeactivate
404
- });
405
- return;
406
- }
407
-
408
- // This is needed for mobile devices.
409
- // (If we'll only let `click` events through,
410
- // then on mobile they will be blocked anyways if `touchstart` is blocked.)
411
- if (valueOrHandler(config.allowOutsideClick, e)) {
412
- // allow the click outside the trap to take place
413
- return;
414
- }
415
-
416
- // otherwise, prevent the click
417
- e.preventDefault();
418
- };
419
-
420
- // In case focus escapes the trap for some strange reason, pull it back in.
421
- var checkFocusIn = function checkFocusIn(e) {
422
- var target = getActualTarget(e);
423
- var targetContained = findContainerIndex(target, e) >= 0;
424
-
425
- // In Firefox when you Tab out of an iframe the Document is briefly focused.
426
- if (targetContained || target instanceof Document) {
427
- if (targetContained) {
428
- state.mostRecentlyFocusedNode = target;
429
- }
430
- } else {
431
- // escaped! pull it back in to where it just left
432
- e.stopImmediatePropagation();
433
- tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
434
- }
435
- };
436
-
437
- // Hijack key nav events on the first and last focusable nodes of the trap,
438
- // in order to prevent focus from escaping. If it escapes for even a
439
- // moment it can end up scrolling the page and causing confusion so we
440
- // kind of need to capture the action at the keydown phase.
441
- var checkKeyNav = function checkKeyNav(event) {
442
- var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
443
- var target = getActualTarget(event);
428
+ /**
429
+ * Finds the next node (in either direction) where focus should move according to a
430
+ * keyboard focus-in event.
431
+ * @param {Object} params
432
+ * @param {Node} [params.target] Known target __from which__ to navigate, if any.
433
+ * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event
434
+ * will be used to determine the `target`). Ignored if `target` is specified.
435
+ * @param {boolean} [params.isBackward] True if focus should move backward.
436
+ * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be
437
+ * determined given the current state of the trap.
438
+ */
439
+ var findNextNavNode = function findNextNavNode(_ref2) {
440
+ var target = _ref2.target,
441
+ event = _ref2.event,
442
+ _ref2$isBackward = _ref2.isBackward,
443
+ isBackward = _ref2$isBackward === void 0 ? false : _ref2$isBackward;
444
+ target = target || getActualTarget(event);
444
445
  updateTabbableNodes();
445
446
  var destinationNode = null;
446
447
  if (state.tabbableGroups.length > 0) {
@@ -463,8 +464,8 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
463
464
  // REVERSE
464
465
 
465
466
  // is the target the first tabbable node in a group?
466
- var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref2) {
467
- var firstTabbableNode = _ref2.firstTabbableNode;
467
+ var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
468
+ var firstTabbableNode = _ref3.firstTabbableNode;
468
469
  return target === firstTabbableNode;
469
470
  });
470
471
  if (startOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target, false))) {
@@ -482,7 +483,7 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
482
483
  // the LAST group if it's the first tabbable node of the FIRST group)
483
484
  var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
484
485
  var destinationGroup = state.tabbableGroups[destinationGroupIndex];
485
- destinationNode = destinationGroup.lastTabbableNode;
486
+ destinationNode = getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;
486
487
  } else if (!isTabEvent(event)) {
487
488
  // user must have customized the nav keys so we have to move focus manually _within_
488
489
  // the active group: do this based on the order determined by tabbable()
@@ -492,8 +493,8 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
492
493
  // FORWARD
493
494
 
494
495
  // is the target the last tabbable node in a group?
495
- var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
496
- var lastTabbableNode = _ref3.lastTabbableNode;
496
+ var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref4) {
497
+ var lastTabbableNode = _ref4.lastTabbableNode;
497
498
  return target === lastTabbableNode;
498
499
  });
499
500
  if (lastOfGroupIndex < 0 && (containerGroup.container === target || isFocusable(target, config.tabbableOptions) && !isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target))) {
@@ -511,7 +512,7 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
511
512
  // group if it's the last tabbable node of the LAST group)
512
513
  var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
513
514
  var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];
514
- destinationNode = _destinationGroup.firstTabbableNode;
515
+ destinationNode = getTabIndex(target) >= 0 ? _destinationGroup.firstTabbableNode : _destinationGroup.firstDomTabbableNode;
515
516
  } else if (!isTabEvent(event)) {
516
517
  // user must have customized the nav keys so we have to move focus manually _within_
517
518
  // the active group: do this based on the order determined by tabbable()
@@ -523,6 +524,145 @@ var createFocusTrap = function createFocusTrap(elements, userOptions) {
523
524
  // NOTE: the fallbackFocus option does not support returning false to opt-out
524
525
  destinationNode = getNodeForOption('fallbackFocus');
525
526
  }
527
+ return destinationNode;
528
+ };
529
+
530
+ // This needs to be done on mousedown and touchstart instead of click
531
+ // so that it precedes the focus event.
532
+ var checkPointerDown = function checkPointerDown(e) {
533
+ var target = getActualTarget(e);
534
+ if (findContainerIndex(target, e) >= 0) {
535
+ // allow the click since it ocurred inside the trap
536
+ return;
537
+ }
538
+ if (valueOrHandler(config.clickOutsideDeactivates, e)) {
539
+ // immediately deactivate the trap
540
+ trap.deactivate({
541
+ // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
542
+ // which will result in the outside click setting focus to the node
543
+ // that was clicked (and if not focusable, to "nothing"); by setting
544
+ // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
545
+ // on activation (or the configured `setReturnFocus` node), whether the
546
+ // outside click was on a focusable node or not
547
+ returnFocus: config.returnFocusOnDeactivate
548
+ });
549
+ return;
550
+ }
551
+
552
+ // This is needed for mobile devices.
553
+ // (If we'll only let `click` events through,
554
+ // then on mobile they will be blocked anyways if `touchstart` is blocked.)
555
+ if (valueOrHandler(config.allowOutsideClick, e)) {
556
+ // allow the click outside the trap to take place
557
+ return;
558
+ }
559
+
560
+ // otherwise, prevent the click
561
+ e.preventDefault();
562
+ };
563
+
564
+ // In case focus escapes the trap for some strange reason, pull it back in.
565
+ // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected
566
+ // scrolling if the node that got focused was out of view; there's nothing we can do to
567
+ // prevent that from happening by the time we discover that focus escaped
568
+ var checkFocusIn = function checkFocusIn(event) {
569
+ var target = getActualTarget(event);
570
+ var targetContained = findContainerIndex(target, event) >= 0;
571
+
572
+ // In Firefox when you Tab out of an iframe the Document is briefly focused.
573
+ if (targetContained || target instanceof Document) {
574
+ if (targetContained) {
575
+ state.mostRecentlyFocusedNode = target;
576
+ }
577
+ } else {
578
+ // escaped! pull it back in to where it just left
579
+ event.stopImmediatePropagation();
580
+
581
+ // focus will escape if the MRU node had a positive tab index and user tried to nav forward;
582
+ // it will also escape if the MRU node had a 0 tab index and user tried to nav backward
583
+ // toward a node with a positive tab index
584
+ var nextNode; // next node to focus, if we find one
585
+ var navAcrossContainers = true;
586
+ if (getTabIndex(state.mostRecentlyFocusedNode) > 0) {
587
+ // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...
588
+ var mruContainerIdx = findContainerIndex(state.mostRecentlyFocusedNode);
589
+ // there MAY not be any tabbable nodes in the container if there are at least 2 containers
590
+ // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container
591
+ // with at least one tabbable node in order to function, so this could be the other container
592
+ // with nothing tabbable in it)
593
+ var tabbableNodes = state.containerGroups[mruContainerIdx].tabbableNodes;
594
+ if (tabbableNodes.length > 0) {
595
+ // MRU tab index MAY not be found if the MRU node is focusable but not tabbable
596
+ var mruTabIdx = tabbableNodes.findIndex(function (node) {
597
+ return node === state.mostRecentlyFocusedNode;
598
+ });
599
+ if (mruTabIdx >= 0) {
600
+ if (config.isKeyForward(state.recentNavEvent)) {
601
+ if (mruTabIdx + 1 < tabbableNodes.length) {
602
+ nextNode = tabbableNodes[mruTabIdx + 1];
603
+ navAcrossContainers = false;
604
+ }
605
+ // else, don't wrap within the container as focus should move to next/previous
606
+ // container
607
+ } else {
608
+ if (mruTabIdx - 1 >= 0) {
609
+ nextNode = tabbableNodes[mruTabIdx - 1];
610
+ navAcrossContainers = false;
611
+ }
612
+ // else, don't wrap within the container as focus should move to next/previous
613
+ // container
614
+ }
615
+ // else, don't find in container order without considering direction too
616
+ }
617
+ }
618
+ // else, no tabbable nodes in that container (which means we must have at least one other
619
+ // container with at least one tabbable node in it, otherwise focus-trap would've thrown
620
+ // an error the last time updateTabbableNodes() was run): find next node among all known
621
+ // containers
622
+ } else {
623
+ // check to see if there's at least one tabbable node with a positive tab index inside
624
+ // the trap because focus seems to escape when navigating backward from a tabbable node
625
+ // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with
626
+ // the greatest positive tab index like it should)
627
+ if (!state.containerGroups.some(function (g) {
628
+ return g.tabbableNodes.some(function (n) {
629
+ return getTabIndex(n) > 0;
630
+ });
631
+ })) {
632
+ // no containers with tabbable nodes with positive tab indexes which means the focus
633
+ // escaped for some other reason and we should just execute the fallback to the
634
+ // MRU node or initial focus node, if any
635
+ navAcrossContainers = false;
636
+ }
637
+ }
638
+ if (navAcrossContainers) {
639
+ nextNode = findNextNavNode({
640
+ // move FROM the MRU node, not event-related node (which will be the node that is
641
+ // outside the trap causing the focus escape we're trying to fix)
642
+ target: state.mostRecentlyFocusedNode,
643
+ isBackward: config.isKeyBackward(state.recentNavEvent)
644
+ });
645
+ }
646
+ if (nextNode) {
647
+ tryFocus(nextNode);
648
+ } else {
649
+ tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
650
+ }
651
+ }
652
+ state.recentNavEvent = undefined; // clear
653
+ };
654
+
655
+ // Hijack key nav events on the first and last focusable nodes of the trap,
656
+ // in order to prevent focus from escaping. If it escapes for even a
657
+ // moment it can end up scrolling the page and causing confusion so we
658
+ // kind of need to capture the action at the keydown phase.
659
+ var checkKeyNav = function checkKeyNav(event) {
660
+ var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
661
+ state.recentNavEvent = event;
662
+ var destinationNode = findNextNavNode({
663
+ event: event,
664
+ isBackward: isBackward
665
+ });
526
666
  if (destinationNode) {
527
667
  if (isTabEvent(event)) {
528
668
  // since tab natively moves focus, we wouldn't have a destination node unless we