focus-trap.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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);
  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. Array
  62. .from(this.root.querySelectorAll("." + FOCUS_SENTINEL_CLASS))
  63. .forEach(function (sentinelEl) {
  64. sentinelEl.parentElement.removeChild(sentinelEl);
  65. });
  66. if (!this.options.skipRestoreFocus && this.elFocusedBeforeTrapFocus) {
  67. this.elFocusedBeforeTrapFocus.focus();
  68. }
  69. };
  70. /**
  71. * Wraps tab focus within `el` by adding two hidden sentinel divs which are
  72. * used to mark the beginning and the end of the tabbable region. When
  73. * focused, these sentinel elements redirect focus to the first/last
  74. * children elements of the tabbable region, ensuring that focus is trapped
  75. * within that region.
  76. */
  77. FocusTrap.prototype.wrapTabFocus = function (el) {
  78. var _this = this;
  79. var sentinelStart = this.createSentinel();
  80. var sentinelEnd = this.createSentinel();
  81. sentinelStart.addEventListener('focus', function () {
  82. var focusableEls = _this.getFocusableElements(el);
  83. if (focusableEls.length > 0) {
  84. focusableEls[focusableEls.length - 1].focus();
  85. }
  86. });
  87. sentinelEnd.addEventListener('focus', function () {
  88. var focusableEls = _this.getFocusableElements(el);
  89. if (focusableEls.length > 0) {
  90. focusableEls[0].focus();
  91. }
  92. });
  93. el.insertBefore(sentinelStart, el.children[0]);
  94. el.appendChild(sentinelEnd);
  95. };
  96. /**
  97. * Focuses on `initialFocusEl` if defined and a child of the root element.
  98. * Otherwise, focuses on the first focusable child element of the root.
  99. */
  100. FocusTrap.prototype.focusInitialElement = function (focusableEls, initialFocusEl) {
  101. var focusIndex = 0;
  102. if (initialFocusEl) {
  103. focusIndex = Math.max(focusableEls.indexOf(initialFocusEl), 0);
  104. }
  105. focusableEls[focusIndex].focus();
  106. };
  107. FocusTrap.prototype.getFocusableElements = function (root) {
  108. var focusableEls = Array.from(root.querySelectorAll('[autofocus], [tabindex], a, input, textarea, select, button'));
  109. return focusableEls.filter(function (el) {
  110. var isDisabledOrHidden = el.getAttribute('aria-disabled') === 'true' ||
  111. el.getAttribute('disabled') != null ||
  112. el.getAttribute('hidden') != null ||
  113. el.getAttribute('aria-hidden') === 'true';
  114. var isTabbableAndVisible = el.tabIndex >= 0 &&
  115. el.getBoundingClientRect().width > 0 &&
  116. !el.classList.contains(FOCUS_SENTINEL_CLASS) && !isDisabledOrHidden;
  117. var isProgrammaticallyHidden = false;
  118. if (isTabbableAndVisible) {
  119. var style = getComputedStyle(el);
  120. isProgrammaticallyHidden =
  121. style.display === 'none' || style.visibility === 'hidden';
  122. }
  123. return isTabbableAndVisible && !isProgrammaticallyHidden;
  124. });
  125. };
  126. FocusTrap.prototype.createSentinel = function () {
  127. var sentinel = document.createElement('div');
  128. sentinel.setAttribute('tabindex', '0');
  129. // Don't announce in screen readers.
  130. sentinel.setAttribute('aria-hidden', 'true');
  131. sentinel.classList.add(FOCUS_SENTINEL_CLASS);
  132. return sentinel;
  133. };
  134. return FocusTrap;
  135. }());
  136. export { FocusTrap };
  137. //# sourceMappingURL=focus-trap.js.map