"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useClickAwayEffect = void 0;
const react_1 = require("react");
const resolveNode = (item) => {
    if (!item) {
        return null;
    }
    return item instanceof Node ? item : item.current;
};
/**
 * хук позволяющий подписаться на клик вне указанного рефа,
 * подойдет для использования в кастомных попперах
 */
const useClickAwayEffect = ({ ref, onClickAway, preventBubbling, isActive, excludeNodes, }) => {
    (0, react_1.useEffect)(() => {
        const node = ref?.current;
        if (!isActive || !node) {
            return;
        }
        const onClick = (event) => {
            const target = event.target;
            const isClickInside = node.contains(target);
            const isClickOnExcluded = excludeNodes?.some((item) => resolveNode(item)?.contains(target));
            const isClickAway = !isClickInside && !isClickOnExcluded;
            if (preventBubbling) {
                event.stopPropagation();
                event.stopImmediatePropagation();
            }
            if (isClickAway) {
                onClickAway(event, 'clickAway');
            }
        };
        window.addEventListener('pointerdown', onClick);
        return () => {
            window.removeEventListener('pointerdown', onClick);
        };
    }, [isActive, ref, excludeNodes, onClickAway, preventBubbling]);
};
exports.useClickAwayEffect = useClickAwayEffect;
