Skip to content

Commit

Permalink
Add back previous checks
Browse files Browse the repository at this point in the history
  • Loading branch information
BenLorantfy committed Sep 11, 2024
1 parent 3e2d97d commit a3c1e51
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions packages/react/focus-scope/src/FocusScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,27 @@ const FocusScope = React.forwardRef<FocusScopeElement, FocusScopeProps>((props,
// When the focused element gets removed from the DOM, browsers move focus
// back to the document.body. In this case, we move focus to the container
// to keep focus trapped correctly.
function handleMutations() {
function handleMutations(mutations: MutationRecord[]) {
// If the activeElement is not the document body, then the focus was not
// lost, so we don't need to rescue the focus. Please note that this is
// not perfectly robust, because the active element can still be
// document.body even in some cases where the focus was not lost. For
// example, during a blur event, browsers set the activeElement to
// document.body just before activeElement may be set to the next
// element
if (document.activeElement !== document.body) return;

// If no elements were removed, then we don't need to rescue focus
if (noElementsRemoved(mutations)) return;

// If the last focused element is still in the container, then it wasn't
// removed and we don't need to rescue focus
const lastFocusedElementStillInContainer = container?.contains(
lastFocusedElementRef.current
);
if (!lastFocusedElementStillInContainer) {
focus(container);
}
if (lastFocusedElementStillInContainer) return;

focus(container);
}

document.addEventListener('focusin', handleFocusIn);
Expand Down Expand Up @@ -343,6 +357,15 @@ function removeLinks(items: HTMLElement[]) {
return items.filter((item) => item.tagName !== 'A');
}

function noElementsRemoved(mutations: MutationRecord[]) {
for (const mutation of mutations) {
if (mutation.removedNodes.length > 0) {
return false;
}
}
return true;
}

const Root = FocusScope;

export {
Expand Down

0 comments on commit a3c1e51

Please sign in to comment.