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(useClickAway): Fix click on self in shadowDOM will also trigger a callback #2528

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 21 additions & 4 deletions src/useClickAway.ts
@@ -1,28 +1,45 @@
import { RefObject, useEffect, useRef } from 'react';
import { off, on } from './misc/util';

const defaultEvents = ['mousedown', 'touchstart'];
export type Events = (keyof GlobalEventHandlersEventMap)[];

const useClickAway = <E extends Event = Event>(
ref: RefObject<HTMLElement | null>,
onClickAway: (event: E) => void,
events: string[] = defaultEvents
events: Events = ['mousedown', 'touchstart']
) => {
const savedCallback = useRef(onClickAway);
useEffect(() => {
savedCallback.current = onClickAway;
}, [onClickAway]);
useEffect(() => {
const { current: el } = ref;
if (!el) return;

const rootNode = el.getRootNode();
const isInShadow = rootNode instanceof ShadowRoot;

/**
* When events are captured outside the component, events that occur in shadow DOM will target the host element
* so additional event listeners need to be added for shadowDom
*
* document shadowDom target
* | | |
* |- on(document) -|- on(shadowRoot) -|
*/
const handler = (event) => {
const { current: el } = ref;
el && !el.contains(event.target) && savedCallback.current(event);
!el.contains(event.target) &&
event.target.shadowRoot !== rootNode &&
savedCallback.current(event);
};
for (const eventName of events) {
on(document, eventName, handler);
isInShadow && on(rootNode, eventName, handler);
}
return () => {
for (const eventName of events) {
off(document, eventName, handler);
isInShadow && off(rootNode, eventName, handler);
}
};
}, [events, ref]);
Expand Down