"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useObserveIntersection = useObserveIntersection;
const react_1 = require("react");
const react_use_1 = require("react-use");
const useRAF_1 = require("../../../../react-utils/hooks/useRAF.js");
const dom_1 = require("../../../../utils/dom.js");
function useObserveIntersection({ floatingRef, container, selector, observerOptions, }) {
    const [intersection, setIntersection] = (0, react_1.useState)(false);
    const intersectionRef = (0, react_use_1.useLatest)(intersection);
    const updateFunction = (0, react_1.useCallback)(() => {
        const floating = floatingRef.current;
        const element = container.querySelector(selector);
        if (!element || !floating) {
            if (intersectionRef.current)
                setIntersection(false);
            return;
        }
        const isIntersecting = (0, dom_1.areElementsIntersecting)(element, floating);
        if (isIntersecting !== intersectionRef.current)
            setIntersection(isIntersecting);
    }, [container, floatingRef, intersectionRef, selector]);
    const observer = (0, useRAF_1.useRAF)(updateFunction);
    (0, react_1.useEffect)(() => {
        observer();
        const containerObserver = new MutationObserver(observer);
        containerObserver.observe(container, observerOptions ?? {
            childList: true,
            subtree: true,
            attributes: true,
        });
        for (const event of dom_1.REFLOW_EVENTS) {
            window.addEventListener(event, observer);
        }
        return () => {
            containerObserver.disconnect();
            for (const event of dom_1.REFLOW_EVENTS) {
                window.removeEventListener(event, observer);
            }
        };
    }, [container, observer, observerOptions]);
    return { intersection };
}
//# sourceMappingURL=useObserveIntersection.js.map
