|
| 1 | +/** |
| 2 | + * |
| 3 | + * Copyright 2016 Google Inc. All rights reserved. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | + |
| 19 | +/** |
| 20 | + * Usage: |
| 21 | + * const detabinator = new Detabinator(element); |
| 22 | + * detabinator.inert = true; // Sets all focusable children of element to tabindex=-1 |
| 23 | + * detabinator.inert = false; // Restores all focusable children of element |
| 24 | + * Limitations: Doesn't support Shadow DOM v0 :P |
| 25 | + */ |
| 26 | + |
| 27 | +class Detabinator { |
| 28 | + constructor(element) { |
| 29 | + if (!element) { |
| 30 | + throw new Error('Missing required argument. new Detabinator needs an element reference'); |
| 31 | + } |
| 32 | + this._inert = false; |
| 33 | + this._focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex], [contenteditable]'; |
| 34 | + this._focusableElements = Array.from( |
| 35 | + element.querySelectorAll(this._focusableElementsString) |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + get inert() { |
| 40 | + return this._inert; |
| 41 | + } |
| 42 | + |
| 43 | + set inert(isInert) { |
| 44 | + if (this._inert === isInert) { |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + this._inert = isInert; |
| 49 | + |
| 50 | + this._focusableElements.forEach((child) => { |
| 51 | + if (isInert) { |
| 52 | + // If the child has an explict tabindex save it |
| 53 | + if (child.hasAttribute('tabindex')) { |
| 54 | + child.__savedTabindex = child.tabIndex; |
| 55 | + } |
| 56 | + // Set ALL focusable children to tabindex -1 |
| 57 | + child.setAttribute('tabindex', -1); |
| 58 | + } else { |
| 59 | + // If the child has a saved tabindex, restore it |
| 60 | + // Because the value could be 0, explicitly check that it's not false |
| 61 | + if (child.__savedTabindex === 0 || child.__savedTabindex) { |
| 62 | + return child.setAttribute('tabindex', child.__savedTabindex); |
| 63 | + } else { |
| 64 | + // Remove tabindex from ANY REMAINING children |
| 65 | + child.removeAttribute('tabindex'); |
| 66 | + } |
| 67 | + } |
| 68 | + }); |
| 69 | + } |
| 70 | +} |
0 commit comments