Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useClickOutside): fix handling in shadow dom #91

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/useClickOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ function useClickOutside(
) {
const preventMouseClickOutsideRef = useRef(false);
const waitingForTrigger = useRef(false);
const initialSetHandlers = useRef(false);

const handleMouseCapture = useCallback(
(e) => {
Expand Down Expand Up @@ -102,6 +103,11 @@ function useClickOutside(
// so we should fall back to that global event if the local one doesn't exist
// https://github.com/facebook/react/issues/20074
let currentEvent = ownerWindow.event ?? ownerWindow.parent?.event;
if (!currentEvent) {
// Current event would be undefined when in the shadow DOM, so use a ref
// to track the initial event.
initialSetHandlers.current = true;
}

let removeInitialTriggerListener: (() => void) | null = null;
if (InitialTriggerEvents[clickTrigger]) {
Expand All @@ -125,8 +131,9 @@ function useClickOutside(

const removeMouseListener = listen(doc as any, clickTrigger, (e) => {
// skip if this event is the same as the one running when we added the handlers
if (e === currentEvent) {
if (e === currentEvent || initialSetHandlers.current) {
currentEvent = undefined;
initialSetHandlers.current = false;
return;
}
handleMouse(e);
Expand Down