Skip to content

Commit

Permalink
Do not restore focus when user clicks outside a trap area
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Jul 22, 2024
1 parent 4b5a754 commit 922183b
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .changeset/shiny-ears-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@chialab/loock': minor
---

Do not restore focus when user clicks outside a trap area.
18 changes: 0 additions & 18 deletions src/focusTrapBehavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ export function focusTrapBehavior(node: HTMLElement, options: FocusTrapOptions =
}

// MUST use the `focusin` event because it fires after the bound `focus` on trap helpers
node.ownerDocument.addEventListener('focus', handleFocusOut, true);
node.addEventListener('focusin', handleFocusIn, true);
node.addEventListener('keydown', handleKeyDown, true);
if (trapStart) {
Expand Down Expand Up @@ -223,7 +222,6 @@ export function focusTrapBehavior(node: HTMLElement, options: FocusTrapOptions =
connected = false;

restoreAttribute(node, 'tabindex', tabIndex);
node.ownerDocument.removeEventListener('focus', handleFocusOut, true);
node.removeEventListener('focusin', handleFocusIn, true);
node.removeEventListener('keydown', handleKeyDown, true);

Expand Down Expand Up @@ -256,22 +254,6 @@ export function focusTrapBehavior(node: HTMLElement, options: FocusTrapOptions =
currentNode = event.target as HTMLElement;
};

/**
* Handle focus events on document in order to prevent focus exits the active context.
* @param event The focusin event.
*/
const handleFocusOut = (event: FocusEvent) => {
const element = event.target as HTMLElement;
if (!node.contains(element)) {
const { focusContainer = false } = options;
if (focusContainer) {
node.focus();
} else {
manager.focusFirst();
}
}
};

/**
* Handle keydown events.
* @param event The keydown event.
Expand Down

0 comments on commit 922183b

Please sign in to comment.