UNPKG

@modern-kit/react

Version:
36 lines (33 loc) 1.13 kB
import { useRef, useMemo } from 'react'; import { isMobile } from '@modern-kit/utils'; import { useEventListener } from '../useEventListener/index.mjs'; import '../usePreservedCallback/index.mjs'; import '../useIsomorphicLayoutEffect/index.mjs'; function useOutsidePointerDown(callback, options) { const { excludeRefs } = options ?? {}; const targetRef = useRef(null); const eventType = useMemo( () => isMobile() ? "touchstart" : "mousedown", [] ); const handleOutsidePointerDown = ({ target }) => { if (!targetRef.current) return; const targetElement = targetRef.current; const isInExcluded = excludeRefs?.some( (excludeRef) => excludeRef.current?.contains(target) ); const isOutside = !targetElement.contains(target); const shouldTriggerCallback = isOutside && !isInExcluded; if (shouldTriggerCallback) { callback(targetElement); } }; useEventListener( typeof document !== "undefined" ? document : null, eventType, handleOutsidePointerDown ); return { ref: targetRef }; } export { useOutsidePointerDown }; //# sourceMappingURL=index.mjs.map