Skip to content

Commit

Permalink
Fixing the event target when using the WebComponent mode
Browse files Browse the repository at this point in the history
  • Loading branch information
dandara-navarro committed Jul 16, 2024
1 parent a96e3be commit 7148bcc
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/hooks/useFocusTrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ export function useFocusTrap<T extends HTMLElement>(locked = false, options: Use
[getFocusableElements, locked],
);

const getTarget = (e: any) => {
let target = e.target;
if (e.composed) {
target = e.composedPath()[0];
}
return target;
};

// Ensure that user can not focus outside of lock. If an attempt is made
// and focusable elements exist inside, will focus first element inside.
const checkFocus = useCallback(
Expand All @@ -68,10 +76,12 @@ export function useFocusTrap<T extends HTMLElement>(locked = false, options: Use

// Blur focus target if no focusable elements.
const focusableElements = getFocusableElements();
if (!focusableElements.length) return (event.target as HTMLElement | null)?.blur();
const target = getTarget(event);

if (!focusableElements.length) return (target as HTMLElement | null)?.blur();

// Focus initial element if focused outside.
const focusedItemIndex = findFocusableIndex(focusableElements, event.target);
const focusedItemIndex = findFocusableIndex(focusableElements, target);
if (focusedItemIndex === -1) return focusableElements[0].focus();
},
[getFocusableElements, locked],
Expand Down

0 comments on commit 7148bcc

Please sign in to comment.