UNPKG

6.13 kBJavaScriptView Raw
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 */
23var 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 */
31var 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 [].slice.call(this.root.querySelectorAll("." + FOCUS_SENTINEL_CLASS))
62 .forEach(function (sentinelEl) {
63 sentinelEl.parentElement.removeChild(sentinelEl);
64 });
65 if (!this.options.skipRestoreFocus && 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) {
77 var _this = this;
78 var sentinelStart = this.createSentinel();
79 var sentinelEnd = this.createSentinel();
80 sentinelStart.addEventListener('focus', function () {
81 var focusableEls = _this.getFocusableElements(el);
82 if (focusableEls.length > 0) {
83 focusableEls[focusableEls.length - 1].focus();
84 }
85 });
86 sentinelEnd.addEventListener('focus', function () {
87 var focusableEls = _this.getFocusableElements(el);
88 if (focusableEls.length > 0) {
89 focusableEls[0].focus();
90 }
91 });
92 el.insertBefore(sentinelStart, el.children[0]);
93 el.appendChild(sentinelEnd);
94 };
95 /**
96 * Focuses on `initialFocusEl` if defined and a child of the root element.
97 * Otherwise, focuses on the first focusable child element of the root.
98 */
99 FocusTrap.prototype.focusInitialElement = function (focusableEls, initialFocusEl) {
100 var focusIndex = 0;
101 if (initialFocusEl) {
102 focusIndex = Math.max(focusableEls.indexOf(initialFocusEl), 0);
103 }
104 focusableEls[focusIndex].focus();
105 };
106 FocusTrap.prototype.getFocusableElements = function (root) {
107 var focusableEls = [].slice.call(root.querySelectorAll('[autofocus], [tabindex], a, input, textarea, select, button'));
108 return focusableEls.filter(function (el) {
109 var isDisabledOrHidden = el.getAttribute('aria-disabled') === 'true' ||
110 el.getAttribute('disabled') != null ||
111 el.getAttribute('hidden') != null ||
112 el.getAttribute('aria-hidden') === 'true';
113 var isTabbableAndVisible = el.tabIndex >= 0 &&
114 el.getBoundingClientRect().width > 0 &&
115 !el.classList.contains(FOCUS_SENTINEL_CLASS) && !isDisabledOrHidden;
116 var isProgrammaticallyHidden = false;
117 if (isTabbableAndVisible) {
118 var style = getComputedStyle(el);
119 isProgrammaticallyHidden =
120 style.display === 'none' || style.visibility === 'hidden';
121 }
122 return isTabbableAndVisible && !isProgrammaticallyHidden;
123 });
124 };
125 FocusTrap.prototype.createSentinel = function () {
126 var sentinel = document.createElement('div');
127 sentinel.setAttribute('tabindex', '0');
128 // Don't announce in screen readers.
129 sentinel.setAttribute('aria-hidden', 'true');
130 sentinel.classList.add(FOCUS_SENTINEL_CLASS);
131 return sentinel;
132 };
133 return FocusTrap;
134}());
135export { FocusTrap };
136//# sourceMappingURL=focus-trap.js.map
\No newline at end of file