UNPKG

@renderlesskit/react

Version:

Collection of headless components/hooks that are accessible, composable, customizable from low level to build your own UI & Design System powered by Reakit

47 lines (40 loc) 2.13 kB
import * as React from "react"; import { getDocument } from "reakit-utils/getDocument"; import { useEventListenerOutside } from "./useEventListenerOutside"; function useMouseDownRef(dialogRef, options) { var mouseDownRef = React.useRef(); React.useEffect(() => { if (!options.visible) return undefined; if (!options.hideOnClickOutside) return undefined; var document = getDocument(dialogRef.current); var onMouseDown = event => { mouseDownRef.current = event.target; }; document.addEventListener("mousedown", onMouseDown); return () => document.removeEventListener("mousedown", onMouseDown); }, [options.visible, options.hideOnClickOutside, dialogRef]); return mouseDownRef; } export function useHideOnClickOutside(dialogRef, disclosureRef, nestedDialogs, options) { var mouseDownRef = useMouseDownRef(dialogRef, options); useEventListenerOutside(dialogRef, disclosureRef, nestedDialogs, "click", event => { // Make sure the element that has been clicked is the same that last // triggered the mousedown event. This prevents the dialog from closing // by dragging the cursor (for example, selecting some text inside the // dialog and releasing the mouse outside of it). if (mouseDownRef.current === event.target) { var _options$hide; (_options$hide = options.hide) === null || _options$hide === void 0 ? void 0 : _options$hide.call(options); } }, options.visible && options.hideOnClickOutside); useEventListenerOutside(dialogRef, disclosureRef, nestedDialogs, "focusin", event => { var document = getDocument(dialogRef.current); // Fix for https://github.com/reakit/reakit/issues/619 // On IE11, calling element.blur() triggers the focus event on // document.body, so we make sure to ignore it as well. if (event.target !== document && event.target !== document.body) { var _options$hide2; (_options$hide2 = options.hide) === null || _options$hide2 === void 0 ? void 0 : _options$hide2.call(options); } }, options.visible && options.hideOnClickOutside); } //# sourceMappingURL=useHideOnClickOutside.js.map