'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../_virtual/_tslib.js');
var React = require('react');
var useDebounce = require('../../hooks/useDebounce.js');

/**
 * Component to handle infinite scrolling of paginated data sets. This component is built to work
 * with both x (horizontal) and y (vertical) directions.
 *
 * If migrating from using `react-infinite-scroller`, all shared props should hold the same value.
 */
function InfiniteScroll(_a) {
    var { element, loadMore, children, hasMore, threshold, axis, loader } = _a, defaultProps = _tslib.__rest(_a, ["element", "loadMore", "children", "hasMore", "threshold", "axis", "loader"]);
    const mainWrapperRef = React.useRef(null);
    const dispatchLoadMore = useDebounce.useDebouncedFn(loadMore, 300);
    const offset = React.useMemo(() => (typeof threshold === 'number' ? threshold : threshold[axis]), [threshold, axis]);
    const hasReachedThreshold = React.useCallback((target) => {
        const value = axis === 'x'
            ? (target.scrollLeft + offset) /
                (target.scrollWidth - target.clientWidth)
            : (target.scrollTop + offset) /
                (target.scrollHeight - target.clientHeight);
        return value >= 1;
    }, [axis, offset]);
    function onScroll(e) {
        if (hasMore && hasReachedThreshold(e.target)) {
            dispatchLoadMore();
        }
    }
    // Handle vertical scroll
    React.useEffect(() => {
        var _a;
        const parent = (_a = mainWrapperRef.current) === null || _a === void 0 ? void 0 : _a.parentNode;
        parent === null || parent === void 0 ? void 0 : parent.addEventListener('scroll', onScroll);
        return () => {
            parent === null || parent === void 0 ? void 0 : parent.removeEventListener('scroll', onScroll);
        };
    }, [mainWrapperRef.current]);
    if (!['x', 'y'].includes(axis)) {
        throw new Error('Invalid axis provided.');
    }
    if (offset < 0) {
        throw new RangeError('Threshold is outside of the expected range');
    }
    return React.createElement(element, Object.assign(Object.assign({}, defaultProps), { ref: mainWrapperRef, onScroll }), [children, hasMore && loader]);
}

exports.InfiniteScroll = InfiniteScroll;
