From 523e0b4264248f1a24fca80dcf2e59bf7bee7618 Mon Sep 17 00:00:00 2001 From: Oliver Tacke Date: Sun, 20 Oct 2024 18:00:46 +0200 Subject: [PATCH] Generalize focus trap --- src/scripts/services/focus-trap.js | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/scripts/services/focus-trap.js b/src/scripts/services/focus-trap.js index ea9161a..627d56e 100644 --- a/src/scripts/services/focus-trap.js +++ b/src/scripts/services/focus-trap.js @@ -99,9 +99,11 @@ export default class FocusTrap { return Array.from(container.querySelectorAll(focusableElementsSelector)) .filter((element) => { + return ( element.disabled !== true && - element.getAttribute('tabindex') !== '-1' + element.getAttribute('tabindex') !== '-1' && + this.isElementVisible(element) ); }); } @@ -182,6 +184,8 @@ export default class FocusTrap { return; // we only care about the tab key } + this.currentFocusElement = document.activeElement; + event.preventDefault(); const index = this.focusableElements.findIndex((element) => { @@ -197,4 +201,22 @@ export default class FocusTrap { this.currentFocusElement = this.focusableElements[newIndex]; this.currentFocusElement.focus(); } + + /** + * Check whether element is visible. + * @param {HTMLElement} element Element to check. + * @returns {boolean} True, if element is visible, false otherwise. + */ + isElementVisible(element) { + if (!element) { + return false; + } + + const style = window.getComputedStyle(element); + if (style.display === 'none' || style.visibility === 'hidden') { + return false; + } + + return element.parentElement ? this.isElementVisible(element.parentElement) : true; + } }