"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSticky = useSticky;
const react_1 = require("react");
const react_use_1 = require("react-use");
const dom_1 = require("../utils/dom.js");
function useSticky(elemRef) {
    const [sticky, setSticky] = (0, react_1.useState)(false);
    const stickyRef = (0, react_use_1.useLatest)(sticky);
    (0, react_use_1.useEffectOnce)(() => {
        let rafId = null;
        observe();
        for (const eventName of dom_1.REFLOW_EVENTS) {
            window.addEventListener(eventName, scheduleObserve, true);
        }
        return () => {
            if (rafId !== null) {
                cancelAnimationFrame(rafId);
            }
            for (const eventName of dom_1.REFLOW_EVENTS) {
                window.removeEventListener(eventName, scheduleObserve, true);
            }
        };
        function scheduleObserve() {
            if (rafId !== null) {
                cancelAnimationFrame(rafId);
            }
            rafId = requestAnimationFrame(observe);
        }
        function observe() {
            rafId = null;
            if (!elemRef.current)
                return;
            const refPageOffset = elemRef.current.getBoundingClientRect().top;
            const stickyOffset = parseInt(getComputedStyle(elemRef.current).top, 10);
            const stickyActive = refPageOffset <= stickyOffset;
            if (stickyActive && !stickyRef.current)
                setSticky(true);
            else if (!stickyActive && stickyRef.current)
                setSticky(false);
        }
    });
    return sticky;
}
//# sourceMappingURL=useSticky.js.map
