focus-trap.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /**
  2. * @license
  3. * Copyright 2020 Google Inc.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. var FOCUS_SENTINEL_CLASS = 'mdc-dom-focus-sentinel';
  24. /**
  25. * Utility to trap focus in a given root element, e.g. for modal components such
  26. * as dialogs. The root should have at least one focusable child element,
  27. * for setting initial focus when trapping focus.
  28. * Also tracks the previously focused element, and restores focus to that
  29. * element when releasing focus.
  30. */
  31. var FocusTrap = /** @class */ (function () {
  32. function FocusTrap(root, options) {
  33. if (options === void 0) { options = {}; }
  34. this.root = root;
  35. this.options = options;
  36. // Previously focused element before trapping focus.
  37. this.elFocusedBeforeTrapFocus = null;
  38. }
  39. /**
  40. * Traps focus in `root`. Also focuses on either `initialFocusEl` if set;
  41. * otherwises sets initial focus to the first focusable child element.
  42. */
  43. FocusTrap.prototype.trapFocus = function () {
  44. var focusableEls = this.getFocusableElements(this.root);
  45. if (focusableEls.length === 0) {
  46. throw new Error('FocusTrap: Element must have at least one focusable child.');
  47. }
  48. this.elFocusedBeforeTrapFocus =
  49. document.activeElement instanceof HTMLElement ? document.activeElement :
  50. null;
  51. this.wrapTabFocus(this.root, focusableEls);
  52. if (!this.options.skipInitialFocus) {
  53. this.focusInitialElement(focusableEls, this.options.initialFocusEl);
  54. }
  55. };
  56. /**
  57. * Releases focus from `root`. Also restores focus to the previously focused
  58. * element.
  59. */
  60. FocusTrap.prototype.releaseFocus = function () {
  61. [].slice.call(this.root.querySelectorAll("." + FOCUS_SENTINEL_CLASS))
  62. .forEach(function (sentinelEl) {
  63. sentinelEl.parentElement.removeChild(sentinelEl);
  64. });
  65. if (this.elFocusedBeforeTrapFocus) {
  66. this.elFocusedBeforeTrapFocus.focus();
  67. }
  68. };
  69. /**
  70. * Wraps tab focus within `el` by adding two hidden sentinel divs which are
  71. * used to mark the beginning and the end of the tabbable region. When
  72. * focused, these sentinel elements redirect focus to the first/last
  73. * children elements of the tabbable region, ensuring that focus is trapped
  74. * within that region.
  75. */
  76. FocusTrap.prototype.wrapTabFocus = function (el, focusableEls) {
  77. var sentinelStart = this.createSentinel();
  78. var sentinelEnd = this.createSentinel();
  79. sentinelStart.addEventListener('focus', function () {
  80. if (focusableEls.length > 0) {
  81. focusableEls[focusableEls.length - 1].focus();
  82. }
  83. });
  84. sentinelEnd.addEventListener('focus', function () {
  85. if (focusableEls.length > 0) {
  86. focusableEls[0].focus();
  87. }
  88. });
  89. el.insertBefore(sentinelStart, el.children[0]);
  90. el.appendChild(sentinelEnd);
  91. };
  92. /**
  93. * Focuses on `initialFocusEl` if defined and a child of the root element.
  94. * Otherwise, focuses on the first focusable child element of the root.
  95. */
  96. FocusTrap.prototype.focusInitialElement = function (focusableEls, initialFocusEl) {
  97. var focusIndex = 0;
  98. if (initialFocusEl) {
  99. focusIndex = Math.max(focusableEls.indexOf(initialFocusEl), 0);
  100. }
  101. focusableEls[focusIndex].focus();
  102. };
  103. FocusTrap.prototype.getFocusableElements = function (root) {
  104. var focusableEls = [].slice.call(root.querySelectorAll('[autofocus], [tabindex], a, input, textarea, select, button'));
  105. return focusableEls.filter(function (el) {
  106. var isDisabledOrHidden = el.getAttribute('aria-disabled') === 'true' ||
  107. el.getAttribute('disabled') != null ||
  108. el.getAttribute('hidden') != null ||
  109. el.getAttribute('aria-hidden') === 'true';
  110. var isTabbableAndVisible = el.tabIndex >= 0 &&
  111. el.getBoundingClientRect().width > 0 &&
  112. !el.classList.contains(FOCUS_SENTINEL_CLASS) && !isDisabledOrHidden;
  113. var isProgrammaticallyHidden = false;
  114. if (isTabbableAndVisible) {
  115. var style = getComputedStyle(el);
  116. isProgrammaticallyHidden =
  117. style.display === 'none' || style.visibility === 'hidden';
  118. }
  119. return isTabbableAndVisible && !isProgrammaticallyHidden;
  120. });
  121. };
  122. FocusTrap.prototype.createSentinel = function () {
  123. var sentinel = document.createElement('div');
  124. sentinel.setAttribute('tabindex', '0');
  125. // Don't announce in screen readers.
  126. sentinel.setAttribute('aria-hidden', 'true');
  127. sentinel.classList.add(FOCUS_SENTINEL_CLASS);
  128. return sentinel;
  129. };
  130. return FocusTrap;
  131. }());
  132. export { FocusTrap };
  133. //# sourceMappingURL=focus-trap.js.map