@yamada-ui/react
Version:
React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion
84 lines (80 loc) • 2.48 kB
JavaScript
"use client";
import { useCallbackRef } from "../../utils/ref.js";
import { utils_exports } from "../../utils/index.js";
import { useCallback, useEffect, useRef } from "react";
//#region src/hooks/use-outside-click/index.ts
/**
* `useOutsideClick` is a custom hook that detects click events outside of an element.
*
* @see https://yamada-ui.com/docs/hooks/use-outside-click
*/
const useOutsideClick = ({ ref, enabled = true, handler }) => {
const handlerRef = useCallbackRef(handler);
const state = useRef({
ignoreEmulatedMouseEvents: false,
isPointerDown: false
});
const onPointerDown = useCallback((ev) => {
if (isValidEvent(ev, ref)) state.current.isPointerDown = true;
}, [ref]);
const onMouseUp = useCallback((ev) => {
if (state.current.ignoreEmulatedMouseEvents) {
state.current.ignoreEmulatedMouseEvents = false;
return;
}
if (state.current.isPointerDown && handler && isValidEvent(ev, ref)) {
state.current.isPointerDown = false;
handlerRef(ev);
}
}, [
handler,
handlerRef,
ref
]);
const onTouchEnd = useCallback((ev) => {
state.current.ignoreEmulatedMouseEvents = true;
if (state.current.isPointerDown && handler && isValidEvent(ev, ref)) {
state.current.isPointerDown = false;
handlerRef(ev);
}
}, [
handler,
handlerRef,
ref
]);
useEffect(() => {
if (!enabled) return;
const doc = (0, utils_exports.getDocument)((0, utils_exports.isArray)(ref) ? ref[0]?.current : ref.current);
doc.addEventListener("mousedown", onPointerDown, true);
doc.addEventListener("mouseup", onMouseUp, true);
doc.addEventListener("touchstart", onPointerDown, true);
doc.addEventListener("touchend", onTouchEnd, true);
return () => {
doc.removeEventListener("mousedown", onPointerDown, true);
doc.removeEventListener("mouseup", onMouseUp, true);
doc.removeEventListener("touchstart", onPointerDown, true);
doc.removeEventListener("touchend", onTouchEnd, true);
};
}, [
handler,
ref,
handlerRef,
state,
enabled,
onPointerDown,
onMouseUp,
onTouchEnd
]);
};
const isValidEvent = (ev, ref) => {
const target = ev.target;
if ("button" in ev && ev.button > 0) return false;
if (target) {
if (!(0, utils_exports.getDocument)(target).contains(target)) return false;
}
if ((0, utils_exports.isArray)(ref)) return !ref.some((ref$1) => ref$1.current?.contains(target));
else return !ref.current?.contains(target);
};
//#endregion
export { useOutsideClick };
//# sourceMappingURL=index.js.map