import { __assign, __rest } from "tslib";
import React, { useCallback, useContext, useEffect, useRef } from 'react';
import classNames from 'classnames';
import { getRect } from '../_utils/dom';
import { ConfigContext } from '../config-provider/config-context';
import { getPrefixCls } from '../_utils/general';
var Waterfall = function (props) {
    var _a = props.columns, columns = _a === void 0 ? 5 : _a, _b = props.gap, gap = _b === void 0 ? 0 : _b, customisedCls = props.prefixCls, className = props.className, style = props.style, children = props.children, otherProps = __rest(props, ["columns", "gap", "prefixCls", "className", "style", "children"]);
    var configContext = useContext(ConfigContext);
    var prefixCls = getPrefixCls('waterfall', configContext.prefixCls, customisedCls);
    var cls = classNames(prefixCls, className);
    var containerRef = useRef(null);
    var handleLayout = useCallback(function () {
        var width = getRect().width;
        var items = containerRef.current.children;
        var itemWidth = width / columns;
        var arr = [];
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            item.children[0].style.width = itemWidth + "px";
            if (i < columns) {
                item.style.top = '0';
                item.style.left = (itemWidth + gap) * i + 'px';
                arr.push(item.offsetHeight);
            }
            else {
                var minHeight = arr[0];
                var index = 0;
                for (var j = 0; j < arr.length; j++) {
                    if (minHeight > arr[j]) {
                        minHeight = arr[j];
                        index = j;
                    }
                }
                item.style.top = arr[index] + gap + 'px';
                item.style.left = items[index].offsetLeft + 'px';
                arr[index] = arr[index] + item.offsetHeight + gap;
            }
        }
    }, [columns, gap]);
    useEffect(function () {
        window.addEventListener('load', handleLayout);
        window.addEventListener('resize', handleLayout);
        return function () {
            window.removeEventListener('load', handleLayout);
            window.removeEventListener('resize', handleLayout);
        };
    }, [handleLayout]);
    return (React.createElement("div", __assign({}, otherProps, { ref: containerRef, className: cls, style: style }), React.Children.map(children, function (child) {
        return React.createElement('div', { className: prefixCls + "__item" }, child);
    })));
};
export default Waterfall;
//# sourceMappingURL=index.js.map