import { isWithinRect } from "@reins/utils"; import { useWindowEvent, UseOutsideClickType } from "hooks"; /** * * @kind 08-Mouse */ export const useOutsideClick: UseOutsideClickType = (refs, onOutsideClick, options) => { const { disabled, checkOption = "contains" } = options || {}; useWindowEvent("click", (event) => { if (!refs || disabled) return; const target = event.target as Node; if (Array.isArray(refs)) { const elements = refs.filter((el) => (el && "current" in el && el?.current) || el); const hasClickedOutsideAll = elements.every((el) => { const element = el && "current" in el ? el.current : el; if (checkOption === "rect") { return !isWithinRect(element as HTMLElement, event); } return element && !element.contains(target); }); return hasClickedOutsideAll && onOutsideClick(); } if (checkOption === "rect") { return !isWithinRect(refs as HTMLElement, event) && onOutsideClick(); } if ( Array.isArray(refs) && !refs.some((el) => (el && "current" in el ? el.current.contains(target) : el.contains(target))) ) { onOutsideClick(); } }); };