|
| 1 | +/*! |
| 2 | + * Copyright (c) 2021-present, Okta, Inc. and/or its affiliates. All rights reserved. |
| 3 | + * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.") |
| 4 | + * |
| 5 | + * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. |
| 6 | + * Unless required by applicable law or agreed to in writing, software |
| 7 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 8 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | + * |
| 10 | + * See the License for the specific language governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | + |
| 13 | +type OptionalHTMLElement = HTMLElement | null; |
| 14 | + |
| 15 | +interface UseFocusHook { |
| 16 | + restoreFocus: (current: OptionalHTMLElement) => void; |
| 17 | + setFocus: (elem: OptionalHTMLElement) => OptionalHTMLElement; |
| 18 | +} |
| 19 | + |
| 20 | +const FOCUSABLE_ITEMS = [ |
| 21 | + "button", |
| 22 | + "[href]", |
| 23 | + "input", |
| 24 | + "select", |
| 25 | + "textarea", |
| 26 | + '[tabindex]:not([tabindex="-1"])', |
| 27 | +]; |
| 28 | + |
| 29 | +const FOCUSABLE_ITEMS_SELECTOR = FOCUSABLE_ITEMS.join(","); |
| 30 | + |
| 31 | +/** |
| 32 | + * Set focus on first focusable element inside node tree |
| 33 | + * @param {HTMLElement} elem - parent element that contains focusable child elements |
| 34 | + * @returns {void} |
| 35 | + */ |
| 36 | +function setFocus(elem: OptionalHTMLElement): OptionalHTMLElement { |
| 37 | + if (!elem) { |
| 38 | + return null; |
| 39 | + } |
| 40 | + const focusableItems: NodeListOf<HTMLElement> = elem.querySelectorAll( |
| 41 | + FOCUSABLE_ITEMS_SELECTOR |
| 42 | + ); |
| 43 | + // Capture original focused element before setting focus inside modal dialog |
| 44 | + const lastFocusedElement = document.activeElement; |
| 45 | + if (focusableItems.length > 0) { |
| 46 | + requestAnimationFrame(() => { |
| 47 | + // Focus on first focusable element inside dialog |
| 48 | + focusableItems[0].focus(); |
| 49 | + }); |
| 50 | + } |
| 51 | + return lastFocusedElement as OptionalHTMLElement; |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Restore focus to element with original focus prior to opening modal dialog |
| 56 | + * @param {OptionalHTMLElement} elem |
| 57 | + */ |
| 58 | +function restoreFocus(elem: OptionalHTMLElement): void { |
| 59 | + if (elem && document.contains(elem)) { |
| 60 | + requestAnimationFrame(() => { |
| 61 | + elem.focus(); |
| 62 | + }); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Custom React Hook to provide set/restore focus helper methods |
| 68 | + * @returns {UseFocusHook} |
| 69 | + */ |
| 70 | +export function useFocus(): UseFocusHook { |
| 71 | + return { |
| 72 | + restoreFocus, |
| 73 | + setFocus, |
| 74 | + }; |
| 75 | +} |
0 commit comments