nice-ui
Version:
React design system, components, and utilities
40 lines (39 loc) • 1.38 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useClickAway = void 0;
const react_1 = require("react");
const context_1 = require("../utils/portal/context");
const defaultEvents = ['mousedown', 'touchstart'];
const useClickAway = (onClickAway, events = defaultEvents) => {
const portal = (0, context_1.usePortal)();
const ref = (0, react_1.useRef)(null);
(0, react_1.useEffect)(() => {
const handler = (event) => {
const { current: el } = ref;
const target = event.target;
if (!el || !target)
return;
if (el.contains(target))
return;
if (!portal) {
onClickAway(event);
return;
}
for (const root of portal.roots)
if (root.contains(target))
return;
onClickAway(event);
};
for (const eventName of events)
document.addEventListener(eventName, handler);
return () => {
for (const eventName of events)
document.removeEventListener(eventName, handler);
};
}, [onClickAway, ...events, ref]);
const refCallback = (0, react_1.useCallback)((el) => {
ref.current = el;
}, []);
return refCallback;
};
exports.useClickAway = useClickAway;
;