From cc5019710b4790f9f7143465251ebf2e340f0877 Mon Sep 17 00:00:00 2001 From: Taya Leutina Date: Sat, 28 Dec 2024 12:16:10 +0300 Subject: [PATCH] fix: incorrect focus setting when opening multiple terms sequentially --- src/js/term/utils.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/js/term/utils.ts b/src/js/term/utils.ts index 5a7149ea..c385a8e4 100644 --- a/src/js/term/utils.ts +++ b/src/js/term/utils.ts @@ -173,7 +173,7 @@ export function openDefinition(target: HTMLElement) { definitionElement.classList.toggle(openClass); - trapFocus(definitionElement); + trapFocus(definitionElement, target); } export function closeDefinition(definition: HTMLElement) { @@ -210,13 +210,19 @@ function getCoords(elem: HTMLElement) { return {top: Math.round(top), left: Math.round(left)}; } -export function trapFocus(element: HTMLElement) { +export function trapFocus(element: HTMLElement, termButton: HTMLElement) { const focusableElements = element.querySelectorAll( 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', ); const firstFocusableElement = focusableElements[0] as HTMLElement; const lastFocusableElement = focusableElements[focusableElements.length - 1] as HTMLElement; + // if another term was previously closed, the focus may still be on it + if (!firstFocusableElement && document.activeElement !== termButton) { + termButton.focus(); + return; + } + if (firstFocusableElement) { firstFocusableElement.focus(); }