import { useEffect } from 'react';
import { isInstance } from '../utils';
/**
 * @example useItemIntersection(listRef,offset,() => { do_some_thing; });
 * @param containerRef The ref of the List.
 * @param offset  Index of the list item which needs to be observed.
 * @param cb Callback that needs to be fired on intersect
 * @param itemSelector Selector used to get the node list of items
 * @param boundingRef Ref to use as the bounding root for querying items, needed if component may be rendered in ShadowDOM.
 * @returns void.
 */
const useItemIntersection = (containerRef, offset, cb, itemSelector, boundingRef) => {
    useEffect(() => {
        let item = null;
        if (offset > 0) {
            const elementToQuery = containerRef?.current ?? boundingRef?.current?.getRootNode() ?? document;
            if (!isInstance(elementToQuery, HTMLElement, SVGElement, Document, ShadowRoot)) {
                return;
            }
            const items = elementToQuery.querySelectorAll(itemSelector);
            if (items.length > offset) {
                item = items[offset];
            }
        }
        if (item) {
            const intersectionObserver = new IntersectionObserver((entries) => {
                if (entries[0].isIntersecting) {
                    cb();
                }
            }, {
                root: containerRef.current ?? null
            });
            intersectionObserver.observe(item);
            return () => {
                intersectionObserver.disconnect();
            };
        }
    }, [cb, offset]);
};
export default useItemIntersection;
//# sourceMappingURL=useItemIntersection.js.map