focus-trap 7.4.3 → 7.5.1

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * focus-trap 7.4.3
2
+ * focus-trap 7.5.1
3
3
  * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
4
4
  */
5
5
  (function (global, factory) {
@@ -94,10 +94,10 @@
94
94
  return node.tagName && node.tagName.toLowerCase() === 'input' && typeof node.select === 'function';
95
95
  };
96
96
  var isEscapeEvent = function isEscapeEvent(e) {
97
- return e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27;
97
+ 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;
98
98
  };
99
99
  var isTabEvent = function isTabEvent(e) {
100
- return e.key === 'Tab' || e.keyCode === 9;
100
+ return (e === null || e === void 0 ? void 0 : e.key) === 'Tab' || (e === null || e === void 0 ? void 0 : e.keyCode) === 9;
101
101
  };
102
102
 
103
103
  // checks for TAB by default
@@ -181,8 +181,11 @@
181
181
  // container: HTMLElement,
182
182
  // tabbableNodes: Array<HTMLElement>, // empty if none
183
183
  // focusableNodes: Array<HTMLElement>, // empty if none
184
- // firstTabbableNode: HTMLElement|null,
185
- // lastTabbableNode: HTMLElement|null,
184
+ // posTabIndexesFound: boolean,
185
+ // firstTabbableNode: HTMLElement|undefined,
186
+ // lastTabbableNode: HTMLElement|undefined,
187
+ // firstDomTabbableNode: HTMLElement|undefined,
188
+ // lastDomTabbableNode: HTMLElement|undefined,
186
189
  // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined
187
190
  // }>}
188
191
  containerGroups: [],
@@ -199,7 +202,9 @@
199
202
  paused: false,
200
203
  // timer ID for when delayInitialFocus is true and initial focus in this trap
201
204
  // has been delayed during activation
202
- delayInitialFocusTimer: undefined
205
+ delayInitialFocusTimer: undefined,
206
+ // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any
207
+ recentNavEvent: undefined
203
208
  };
204
209
  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
205
210
 
@@ -218,7 +223,9 @@
218
223
  /**
219
224
  * Finds the index of the container that contains the element.
220
225
  * @param {HTMLElement} element
221
- * @param {Event} [event]
226
+ * @param {Event} [event] If available, and `element` isn't directly found in any container,
227
+ * the event's composed path is used to see if includes any known trap containers in the
228
+ * case where the element is inside a Shadow DOM.
222
229
  * @returns {number} Index of the container in either `state.containers` or
223
230
  * `state.containerGroups` (the order/length of these lists are the same); -1
224
231
  * if the element isn't found.
@@ -313,14 +320,41 @@
313
320
  var tabbableNodes = tabbable.tabbable(container, config.tabbableOptions);
314
321
 
315
322
  // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes
316
- // are a superset of tabbable nodes
323
+ // are a superset of tabbable nodes since nodes with negative `tabindex` attributes
324
+ // are focusable but not tabbable
317
325
  var focusableNodes = tabbable.focusable(container, config.tabbableOptions);
326
+ var firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;
327
+ var lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : undefined;
328
+ var firstDomTabbableNode = focusableNodes.find(function (node) {
329
+ return tabbable.isTabbable(node);
330
+ });
331
+ var lastDomTabbableNode = focusableNodes.findLast(function (node) {
332
+ return tabbable.isTabbable(node);
333
+ });
334
+ var posTabIndexesFound = !!tabbableNodes.find(function (node) {
335
+ return tabbable.getTabIndex(node) > 0;
336
+ });
318
337
  return {
319
338
  container: container,
320
339
  tabbableNodes: tabbableNodes,
321
340
  focusableNodes: focusableNodes,
322
- firstTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[0] : null,
323
- lastTabbableNode: tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : null,
341
+ /** True if at least one node with positive `tabindex` was found in this container. */
342
+ posTabIndexesFound: posTabIndexesFound,
343
+ /** First tabbable node in container, __tabindex__ order; `undefined` if none. */
344
+ firstTabbableNode: firstTabbableNode,
345
+ /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */
346
+ lastTabbableNode: lastTabbableNode,
347
+ // NOTE: DOM order is NOT NECESSARILY "document position" order, but figuring that out
348
+ // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
349
+ // because that API doesn't work with Shadow DOM as well as it should (@see
350
+ // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,
351
+ // to address an edge case related to positive tabindex support, this seems like a much easier,
352
+ // "close enough most of the time" alternative for positive tabindexes which should generally
353
+ // be avoided anyway...
354
+ /** First tabbable node in container, __DOM__ order; `undefined` if none. */
355
+ firstDomTabbableNode: firstDomTabbableNode,
356
+ /** Last tabbable node in container, __DOM__ order; `undefined` if none. */
357
+ lastDomTabbableNode: lastDomTabbableNode,
324
358
  /**
325
359
  * Finds the __tabbable__ node that follows the given node in the specified direction,
326
360
  * in this container, if any.
@@ -331,30 +365,24 @@
331
365
  */
332
366
  nextTabbableNode: function nextTabbableNode(node) {
333
367
  var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
334
- // NOTE: If tabindex is positive (in order to manipulate the tab order separate
335
- // from the DOM order), this __will not work__ because the list of focusableNodes,
336
- // while it contains tabbable nodes, does not sort its nodes in any order other
337
- // than DOM order, because it can't: Where would you place focusable (but not
338
- // tabbable) nodes in that order? They have no order, because they aren't tabbale...
339
- // Support for positive tabindex is already broken and hard to manage (possibly
340
- // not supportable, TBD), so this isn't going to make things worse than they
341
- // already are, and at least makes things better for the majority of cases where
342
- // tabindex is either 0/unset or negative.
343
- // FYI, positive tabindex issue: https://github.com/focus-trap/focus-trap/issues/375
344
- var nodeIdx = focusableNodes.findIndex(function (n) {
345
- return n === node;
346
- });
368
+ var nodeIdx = tabbableNodes.indexOf(node);
347
369
  if (nodeIdx < 0) {
348
- return undefined;
349
- }
350
- if (forward) {
351
- return focusableNodes.slice(nodeIdx + 1).find(function (n) {
352
- return tabbable.isTabbable(n, config.tabbableOptions);
370
+ // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):
371
+ // since `node` should at least have been focusable, we assume that's the case and mimic
372
+ // what browsers do, which is set focus to the next node in __document position order__,
373
+ // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE
374
+ // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to
375
+ // basic DOM order
376
+ if (forward) {
377
+ return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find(function (el) {
378
+ return tabbable.isTabbable(el);
379
+ });
380
+ }
381
+ return focusableNodes.slice(0, focusableNodes.indexOf(node)).findLast(function (el) {
382
+ return tabbable.isTabbable(el);
353
383
  });
354
384
  }
355
- return focusableNodes.slice(0, nodeIdx).reverse().find(function (n) {
356
- return tabbable.isTabbable(n, config.tabbableOptions);
357
- });
385
+ return tabbableNodes[nodeIdx + (forward ? 1 : -1)];
358
386
  }
359
387
  };
360
388
  });
@@ -367,6 +395,19 @@
367
395
  ) {
368
396
  throw new Error('Your focus-trap must have at least one container with at least one tabbable node in it at all times');
369
397
  }
398
+
399
+ // NOTE: Positive tabindexes are only properly supported in single-container traps because
400
+ // doing it across multiple containers where tabindexes could be all over the place
401
+ // would require Tabbable to support multiple containers, would require additional
402
+ // specialized Shadow DOM support, and would require Tabbable's multi-container support
403
+ // to look at those containers in document position order rather than user-provided
404
+ // order (as they are treated in Focus-trap, for legacy reasons). See discussion on
405
+ // https://github.com/focus-trap/focus-trap/issues/375 for more details.
406
+ if (state.containerGroups.find(function (g) {
407
+ return g.posTabIndexesFound;
408
+ }) && state.containerGroups.length > 1) {
409
+ 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.");
410
+ }
370
411
  };
371
412
  var tryFocus = function tryFocus(node) {
372
413
  if (node === false) {
@@ -382,6 +423,7 @@
382
423
  node.focus({
383
424
  preventScroll: !!config.preventScroll
384
425
  });
426
+ // NOTE: focus() API does not trigger focusIn event so set MRU node manually
385
427
  state.mostRecentlyFocusedNode = node;
386
428
  if (isSelectableInput(node)) {
387
429
  node.select();
@@ -392,64 +434,23 @@
392
434
  return node ? node : node === false ? false : previousActiveElement;
393
435
  };
394
436
 
395
- // This needs to be done on mousedown and touchstart instead of click
396
- // so that it precedes the focus event.
397
- var checkPointerDown = function checkPointerDown(e) {
398
- var target = getActualTarget(e);
399
- if (findContainerIndex(target, e) >= 0) {
400
- // allow the click since it ocurred inside the trap
401
- return;
402
- }
403
- if (valueOrHandler(config.clickOutsideDeactivates, e)) {
404
- // immediately deactivate the trap
405
- trap.deactivate({
406
- // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
407
- // which will result in the outside click setting focus to the node
408
- // that was clicked (and if not focusable, to "nothing"); by setting
409
- // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
410
- // on activation (or the configured `setReturnFocus` node), whether the
411
- // outside click was on a focusable node or not
412
- returnFocus: config.returnFocusOnDeactivate
413
- });
414
- return;
415
- }
416
-
417
- // This is needed for mobile devices.
418
- // (If we'll only let `click` events through,
419
- // then on mobile they will be blocked anyways if `touchstart` is blocked.)
420
- if (valueOrHandler(config.allowOutsideClick, e)) {
421
- // allow the click outside the trap to take place
422
- return;
423
- }
424
-
425
- // otherwise, prevent the click
426
- e.preventDefault();
427
- };
428
-
429
- // In case focus escapes the trap for some strange reason, pull it back in.
430
- var checkFocusIn = function checkFocusIn(e) {
431
- var target = getActualTarget(e);
432
- var targetContained = findContainerIndex(target, e) >= 0;
433
-
434
- // In Firefox when you Tab out of an iframe the Document is briefly focused.
435
- if (targetContained || target instanceof Document) {
436
- if (targetContained) {
437
- state.mostRecentlyFocusedNode = target;
438
- }
439
- } else {
440
- // escaped! pull it back in to where it just left
441
- e.stopImmediatePropagation();
442
- tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
443
- }
444
- };
445
-
446
- // Hijack key nav events on the first and last focusable nodes of the trap,
447
- // in order to prevent focus from escaping. If it escapes for even a
448
- // moment it can end up scrolling the page and causing confusion so we
449
- // kind of need to capture the action at the keydown phase.
450
- var checkKeyNav = function checkKeyNav(event) {
451
- var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
452
- var target = getActualTarget(event);
437
+ /**
438
+ * Finds the next node (in either direction) where focus should move according to a
439
+ * keyboard focus-in event.
440
+ * @param {Object} params
441
+ * @param {Node} [params.target] Known target __from which__ to navigate, if any.
442
+ * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event
443
+ * will be used to determine the `target`). Ignored if `target` is specified.
444
+ * @param {boolean} [params.isBackward] True if focus should move backward.
445
+ * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be
446
+ * determined given the current state of the trap.
447
+ */
448
+ var findNextNavNode = function findNextNavNode(_ref2) {
449
+ var target = _ref2.target,
450
+ event = _ref2.event,
451
+ _ref2$isBackward = _ref2.isBackward,
452
+ isBackward = _ref2$isBackward === void 0 ? false : _ref2$isBackward;
453
+ target = target || getActualTarget(event);
453
454
  updateTabbableNodes();
454
455
  var destinationNode = null;
455
456
  if (state.tabbableGroups.length > 0) {
@@ -472,8 +473,8 @@
472
473
  // REVERSE
473
474
 
474
475
  // is the target the first tabbable node in a group?
475
- var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref2) {
476
- var firstTabbableNode = _ref2.firstTabbableNode;
476
+ var startOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
477
+ var firstTabbableNode = _ref3.firstTabbableNode;
477
478
  return target === firstTabbableNode;
478
479
  });
479
480
  if (startOfGroupIndex < 0 && (containerGroup.container === target || tabbable.isFocusable(target, config.tabbableOptions) && !tabbable.isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target, false))) {
@@ -491,7 +492,7 @@
491
492
  // the LAST group if it's the first tabbable node of the FIRST group)
492
493
  var destinationGroupIndex = startOfGroupIndex === 0 ? state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
493
494
  var destinationGroup = state.tabbableGroups[destinationGroupIndex];
494
- destinationNode = destinationGroup.lastTabbableNode;
495
+ destinationNode = tabbable.getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;
495
496
  } else if (!isTabEvent(event)) {
496
497
  // user must have customized the nav keys so we have to move focus manually _within_
497
498
  // the active group: do this based on the order determined by tabbable()
@@ -501,8 +502,8 @@
501
502
  // FORWARD
502
503
 
503
504
  // is the target the last tabbable node in a group?
504
- var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref3) {
505
- var lastTabbableNode = _ref3.lastTabbableNode;
505
+ var lastOfGroupIndex = findIndex(state.tabbableGroups, function (_ref4) {
506
+ var lastTabbableNode = _ref4.lastTabbableNode;
506
507
  return target === lastTabbableNode;
507
508
  });
508
509
  if (lastOfGroupIndex < 0 && (containerGroup.container === target || tabbable.isFocusable(target, config.tabbableOptions) && !tabbable.isTabbable(target, config.tabbableOptions) && !containerGroup.nextTabbableNode(target))) {
@@ -520,7 +521,7 @@
520
521
  // group if it's the last tabbable node of the LAST group)
521
522
  var _destinationGroupIndex = lastOfGroupIndex === state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
522
523
  var _destinationGroup = state.tabbableGroups[_destinationGroupIndex];
523
- destinationNode = _destinationGroup.firstTabbableNode;
524
+ destinationNode = tabbable.getTabIndex(target) >= 0 ? _destinationGroup.firstTabbableNode : _destinationGroup.firstDomTabbableNode;
524
525
  } else if (!isTabEvent(event)) {
525
526
  // user must have customized the nav keys so we have to move focus manually _within_
526
527
  // the active group: do this based on the order determined by tabbable()
@@ -532,6 +533,153 @@
532
533
  // NOTE: the fallbackFocus option does not support returning false to opt-out
533
534
  destinationNode = getNodeForOption('fallbackFocus');
534
535
  }
536
+ return destinationNode;
537
+ };
538
+
539
+ // This needs to be done on mousedown and touchstart instead of click
540
+ // so that it precedes the focus event.
541
+ var checkPointerDown = function checkPointerDown(e) {
542
+ var target = getActualTarget(e);
543
+ if (findContainerIndex(target, e) >= 0) {
544
+ // allow the click since it ocurred inside the trap
545
+ return;
546
+ }
547
+ if (valueOrHandler(config.clickOutsideDeactivates, e)) {
548
+ // immediately deactivate the trap
549
+ trap.deactivate({
550
+ // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,
551
+ // which will result in the outside click setting focus to the node
552
+ // that was clicked (and if not focusable, to "nothing"); by setting
553
+ // `returnFocus: true`, we'll attempt to re-focus the node originally-focused
554
+ // on activation (or the configured `setReturnFocus` node), whether the
555
+ // outside click was on a focusable node or not
556
+ returnFocus: config.returnFocusOnDeactivate
557
+ });
558
+ return;
559
+ }
560
+
561
+ // This is needed for mobile devices.
562
+ // (If we'll only let `click` events through,
563
+ // then on mobile they will be blocked anyways if `touchstart` is blocked.)
564
+ if (valueOrHandler(config.allowOutsideClick, e)) {
565
+ // allow the click outside the trap to take place
566
+ return;
567
+ }
568
+
569
+ // otherwise, prevent the click
570
+ e.preventDefault();
571
+ };
572
+
573
+ // In case focus escapes the trap for some strange reason, pull it back in.
574
+ // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected
575
+ // scrolling if the node that got focused was out of view; there's nothing we can do to
576
+ // prevent that from happening by the time we discover that focus escaped
577
+ var checkFocusIn = function checkFocusIn(event) {
578
+ var target = getActualTarget(event);
579
+ var targetContained = findContainerIndex(target, event) >= 0;
580
+
581
+ // In Firefox when you Tab out of an iframe the Document is briefly focused.
582
+ if (targetContained || target instanceof Document) {
583
+ if (targetContained) {
584
+ state.mostRecentlyFocusedNode = target;
585
+ }
586
+ } else {
587
+ // escaped! pull it back in to where it just left
588
+ event.stopImmediatePropagation();
589
+
590
+ // focus will escape if the MRU node had a positive tab index and user tried to nav forward;
591
+ // it will also escape if the MRU node had a 0 tab index and user tried to nav backward
592
+ // toward a node with a positive tab index
593
+ var nextNode; // next node to focus, if we find one
594
+ var navAcrossContainers = true;
595
+ if (state.mostRecentlyFocusedNode) {
596
+ if (tabbable.getTabIndex(state.mostRecentlyFocusedNode) > 0) {
597
+ // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...
598
+ var mruContainerIdx = findContainerIndex(state.mostRecentlyFocusedNode);
599
+ // there MAY not be any tabbable nodes in the container if there are at least 2 containers
600
+ // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container
601
+ // with at least one tabbable node in order to function, so this could be the other container
602
+ // with nothing tabbable in it)
603
+ var tabbableNodes = state.containerGroups[mruContainerIdx].tabbableNodes;
604
+ if (tabbableNodes.length > 0) {
605
+ // MRU tab index MAY not be found if the MRU node is focusable but not tabbable
606
+ var mruTabIdx = tabbableNodes.findIndex(function (node) {
607
+ return node === state.mostRecentlyFocusedNode;
608
+ });
609
+ if (mruTabIdx >= 0) {
610
+ if (config.isKeyForward(state.recentNavEvent)) {
611
+ if (mruTabIdx + 1 < tabbableNodes.length) {
612
+ nextNode = tabbableNodes[mruTabIdx + 1];
613
+ navAcrossContainers = false;
614
+ }
615
+ // else, don't wrap within the container as focus should move to next/previous
616
+ // container
617
+ } else {
618
+ if (mruTabIdx - 1 >= 0) {
619
+ nextNode = tabbableNodes[mruTabIdx - 1];
620
+ navAcrossContainers = false;
621
+ }
622
+ // else, don't wrap within the container as focus should move to next/previous
623
+ // container
624
+ }
625
+ // else, don't find in container order without considering direction too
626
+ }
627
+ }
628
+ // else, no tabbable nodes in that container (which means we must have at least one other
629
+ // container with at least one tabbable node in it, otherwise focus-trap would've thrown
630
+ // an error the last time updateTabbableNodes() was run): find next node among all known
631
+ // containers
632
+ } else {
633
+ // check to see if there's at least one tabbable node with a positive tab index inside
634
+ // the trap because focus seems to escape when navigating backward from a tabbable node
635
+ // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with
636
+ // the greatest positive tab index like it should)
637
+ if (!state.containerGroups.some(function (g) {
638
+ return g.tabbableNodes.some(function (n) {
639
+ return tabbable.getTabIndex(n) > 0;
640
+ });
641
+ })) {
642
+ // no containers with tabbable nodes with positive tab indexes which means the focus
643
+ // escaped for some other reason and we should just execute the fallback to the
644
+ // MRU node or initial focus node, if any
645
+ navAcrossContainers = false;
646
+ }
647
+ }
648
+ } else {
649
+ // no MRU node means we're likely in some initial condition when the trap has just
650
+ // been activated and initial focus hasn't been given yet, in which case we should
651
+ // fall through to trying to focus the initial focus node, which is what should
652
+ // happen below at this point in the logic
653
+ navAcrossContainers = false;
654
+ }
655
+ if (navAcrossContainers) {
656
+ nextNode = findNextNavNode({
657
+ // move FROM the MRU node, not event-related node (which will be the node that is
658
+ // outside the trap causing the focus escape we're trying to fix)
659
+ target: state.mostRecentlyFocusedNode,
660
+ isBackward: config.isKeyBackward(state.recentNavEvent)
661
+ });
662
+ }
663
+ if (nextNode) {
664
+ tryFocus(nextNode);
665
+ } else {
666
+ tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());
667
+ }
668
+ }
669
+ state.recentNavEvent = undefined; // clear
670
+ };
671
+
672
+ // Hijack key nav events on the first and last focusable nodes of the trap,
673
+ // in order to prevent focus from escaping. If it escapes for even a
674
+ // moment it can end up scrolling the page and causing confusion so we
675
+ // kind of need to capture the action at the keydown phase.
676
+ var checkKeyNav = function checkKeyNav(event) {
677
+ var isBackward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
678
+ state.recentNavEvent = event;
679
+ var destinationNode = findNextNavNode({
680
+ event: event,
681
+ isBackward: isBackward
682
+ });
535
683
  if (destinationNode) {
536
684
  if (isTabEvent(event)) {
537
685
  // since tab natively moves focus, we wouldn't have a destination node unless we