|
| 1 | +export default class FocusTrap { |
| 2 | + static #isLocked = false; |
| 3 | + static #currentKey = ""; |
| 4 | + |
| 5 | + #container: HTMLElement; |
| 6 | + #key: string; |
| 7 | + #listener: (e: KeyboardEvent) => void; |
| 8 | + |
| 9 | + constructor(container: HTMLElement, start: HTMLElement, end: HTMLElement) { |
| 10 | + this.#container = container; |
| 11 | + this.#key = crypto.getRandomValues(new Uint8Array(10)).join(""); |
| 12 | + this.#listener = (e) => { |
| 13 | + if (e.key.toLowerCase() !== "tab") { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + if (e.shiftKey && document.activeElement === start) { |
| 18 | + e.preventDefault(); |
| 19 | + end.focus(); |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + if (!e.shiftKey && document.activeElement === end) { |
| 24 | + e.preventDefault(); |
| 25 | + start.focus(); |
| 26 | + } |
| 27 | + }; |
| 28 | + } |
| 29 | + |
| 30 | + get isLocked() { |
| 31 | + return FocusTrap.#isLocked; |
| 32 | + } |
| 33 | + |
| 34 | + lock() { |
| 35 | + if (FocusTrap.#isLocked) { |
| 36 | + throw new Error("Focus trap is already locked."); |
| 37 | + } |
| 38 | + |
| 39 | + addEventListener("keydown", this.#listener); |
| 40 | + FocusTrap.#isLocked = true; |
| 41 | + FocusTrap.#currentKey = this.#key; |
| 42 | + |
| 43 | + this.#hideElements(document.body, this.#container); |
| 44 | + } |
| 45 | + |
| 46 | + #hideElements(root: Element, exception: Element) { |
| 47 | + for (const child of root.children) { |
| 48 | + if (child === exception) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if (child.contains(exception)) { |
| 53 | + this.#hideElements(child, exception); |
| 54 | + continue; |
| 55 | + } |
| 56 | + |
| 57 | + child.setAttribute("aria-hidden", "true"); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + unlock() { |
| 62 | + if (!FocusTrap.#isLocked) { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + if (FocusTrap.#currentKey !== this.#key) { |
| 67 | + throw new Error("Cannot unlock a lock set by another focus trap."); |
| 68 | + } |
| 69 | + |
| 70 | + removeEventListener("keydown", this.#listener); |
| 71 | + FocusTrap.#isLocked = false; |
| 72 | + FocusTrap.#currentKey = ""; |
| 73 | + |
| 74 | + this.#unhideElements(document.body, this.#container); |
| 75 | + } |
| 76 | + |
| 77 | + #unhideElements(root: Element, exception: Element) { |
| 78 | + for (const child of root.children) { |
| 79 | + if (child === exception) { |
| 80 | + continue; |
| 81 | + } |
| 82 | + |
| 83 | + if (child.contains(exception)) { |
| 84 | + this.#hideElements(child, exception); |
| 85 | + continue; |
| 86 | + } |
| 87 | + |
| 88 | + child.removeAttribute("aria-hidden"); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + toggleLock() { |
| 93 | + if (FocusTrap.#isLocked) { |
| 94 | + this.unlock(); |
| 95 | + return; |
| 96 | + } |
| 97 | + |
| 98 | + this.lock(); |
| 99 | + } |
| 100 | +} |
0 commit comments