/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

'use strict';

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

var tslib = require('tslib');
var React = require('react');
var PropTypes = require('prop-types');
var SizeAndPositionManager = require('./SizeAndPositionManager.js');
var constants = require('./constants.js');
var AutoSizer = require('./AutoSizer.js');

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var React__namespace = /*#__PURE__*/_interopNamespace(React);
var PropTypes__namespace = /*#__PURE__*/_interopNamespace(PropTypes);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var STYLE_WRAPPER = {
    overflow: 'auto',
    willChange: 'transform',
    WebkitOverflowScrolling: 'touch'
};
var STYLE_INNER = {
    position: 'relative',
    width: 'auto',
    whiteSpace: 'nowrap',
    minHeight: '100%'
};
var STYLE_ITEM = {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%'
};
var STYLE_STICKY_ITEM = tslib.__assign(tslib.__assign({}, STYLE_ITEM), { position: 'sticky' });
var VirtualList = /** @class */ (function (_super) {
    tslib.__extends(VirtualList, _super);
    function VirtualList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.itemSizeGetter = function (itemSize) {
            return function (index) { return _this.getSize(index, itemSize); };
        };
        _this.sizeAndPositionManager = new SizeAndPositionManager["default"]({
            itemCount: _this.props.itemCount,
            itemSizeGetter: _this.itemSizeGetter(_this.props.itemSize),
            estimatedItemSize: _this.getEstimatedItemSize()
        });
        _this.state = {
            offset: _this.props.scrollOffset ||
                (_this.props.scrollToIndex != null &&
                    _this.getOffsetForIndex(_this.props.scrollToIndex)) ||
                0,
            scrollChangeReason: constants.SCROLL_CHANGE_REASON.REQUESTED
        };
        _this.styleCache = {};
        _this.getRef = function (node) {
            node && (_this.rootNode = node);
        };
        _this.handleScroll = function (event) {
            var onScroll = _this.props.onScroll;
            var offset = _this.getNodeOffset();
            if (offset < 0 ||
                _this.state.offset === offset ||
                event.target !== _this.rootNode) {
                return;
            }
            _this.setState({
                offset: offset,
                scrollChangeReason: constants.SCROLL_CHANGE_REASON.OBSERVED
            });
            if (typeof onScroll === 'function') {
                onScroll(offset, event);
            }
        };
        return _this;
    }
    VirtualList.prototype.componentDidMount = function () {
        var _a = this.props, scrollOffset = _a.scrollOffset, scrollToIndex = _a.scrollToIndex;
        this.rootNode.addEventListener('scroll', this.handleScroll, {
            passive: true
        });
        this.updateRootWidth();
        if (scrollOffset != null) {
            this.scrollTo(scrollOffset);
        }
        else if (scrollToIndex != null) {
            this.scrollTo(this.getOffsetForIndex(scrollToIndex));
        }
    };
    // 自适应宽度
    VirtualList.prototype.updateRootWidth = function () {
        var itemsDom = this.rootNode.children[0].children;
        var scrollbarWidth = window.innerWidth - document.documentElement.clientWidth || 15;
        var containerWidth = this.rootNode.parentElement.getBoundingClientRect().width;
        var maxItemWidth = 0;
        for (var i = 0; i < itemsDom.length; i++) {
            var itemWidth = itemsDom[i].getBoundingClientRect().width;
            if (itemWidth > maxItemWidth) {
                maxItemWidth = itemWidth;
            }
        }
        if (maxItemWidth > containerWidth) {
            this.rootNode.style.width = maxItemWidth + scrollbarWidth + 'px';
        }
    };
    VirtualList.prototype.componentDidUpdate = function (prevProps, prevState) {
        var props = this.props;
        var estimatedItemSize = prevProps.estimatedItemSize, itemCount = prevProps.itemCount, itemSize = prevProps.itemSize, scrollOffset = prevProps.scrollOffset, scrollToAlignment = prevProps.scrollToAlignment, scrollToIndex = prevProps.scrollToIndex;
        var scrollPropsHaveChanged = props.scrollToIndex !== scrollToIndex ||
            props.scrollToAlignment !== scrollToAlignment;
        var itemPropsHaveChanged = props.itemCount !== itemCount ||
            props.itemSize !== itemSize ||
            props.estimatedItemSize !== estimatedItemSize;
        if (props.itemSize !== itemSize) {
            this.sizeAndPositionManager.updateConfig({
                itemSizeGetter: this.itemSizeGetter(props.itemSize)
            });
        }
        if (props.itemCount !== itemCount ||
            props.estimatedItemSize !== estimatedItemSize) {
            this.sizeAndPositionManager.updateConfig({
                itemCount: props.itemCount,
                estimatedItemSize: this.getEstimatedItemSize(props)
            });
        }
        if (itemPropsHaveChanged) {
            this.recomputeSizes();
        }
        if (props.scrollOffset !== scrollOffset) {
            this.setState({
                offset: props.scrollOffset || 0,
                scrollChangeReason: constants.SCROLL_CHANGE_REASON.REQUESTED
            });
        }
        else if (typeof props.scrollToIndex === 'number' &&
            (scrollPropsHaveChanged || itemPropsHaveChanged)) {
            this.setState({
                offset: this.getOffsetForIndex(props.scrollToIndex, props.scrollToAlignment, props.itemCount),
                scrollChangeReason: constants.SCROLL_CHANGE_REASON.REQUESTED
            });
        }
        var _a = this.state, offset = _a.offset, scrollChangeReason = _a.scrollChangeReason;
        if (prevState.offset !== offset &&
            scrollChangeReason === constants.SCROLL_CHANGE_REASON.REQUESTED) {
            this.scrollTo(offset);
        }
        if (props.itemCount !== itemCount) {
            // 长度发生变化时重新渲染
            this.forceUpdate();
        }
    };
    VirtualList.prototype.componentWillUnmount = function () {
        this.rootNode.removeEventListener('scroll', this.handleScroll);
    };
    VirtualList.prototype.scrollTo = function (value) {
        var _a = this.props.scrollDirection, scrollDirection = _a === void 0 ? constants.DIRECTION.VERTICAL : _a;
        this.rootNode[constants.scrollProp[scrollDirection]] = value;
    };
    VirtualList.prototype.getOffsetForIndex = function (index, scrollToAlignment, itemCount) {
        if (scrollToAlignment === void 0) { scrollToAlignment = this.props.scrollToAlignment; }
        if (itemCount === void 0) { itemCount = this.props.itemCount; }
        var _a = this.props.scrollDirection, scrollDirection = _a === void 0 ? constants.DIRECTION.VERTICAL : _a;
        if (index < 0 || index >= itemCount) {
            index = 0;
        }
        return this.sizeAndPositionManager.getUpdatedOffsetForIndex({
            align: scrollToAlignment,
            containerSize: this.props[constants.sizeProp[scrollDirection]],
            currentOffset: (this.state && this.state.offset) || 0,
            targetIndex: index
        });
    };
    VirtualList.prototype.recomputeSizes = function (startIndex) {
        if (startIndex === void 0) { startIndex = 0; }
        this.styleCache = {};
        this.sizeAndPositionManager.resetItem(startIndex);
    };
    VirtualList.prototype.render = function () {
        var _a;
        var _this = this;
        var _b = this.props; _b.estimatedItemSize; var height = _b.height, _c = _b.overscanCount, overscanCount = _c === void 0 ? 3 : _c, renderItem = _b.renderItem; _b.itemCount; _b.itemSize; var onItemsRendered = _b.onItemsRendered; _b.onScroll; var _d = _b.scrollDirection, scrollDirection = _d === void 0 ? constants.DIRECTION.VERTICAL : _d; _b.scrollOffset; _b.scrollToIndex; _b.scrollToAlignment; var stickyIndices = _b.stickyIndices, style = _b.style, width = _b.width, WrapperComponent = _b.WrapperComponent, InnerComponent = _b.InnerComponent, prefix = _b.prefix, innerStyleFilter = _b.innerStyleFilter, props = tslib.__rest(_b, ["estimatedItemSize", "height", "overscanCount", "renderItem", "itemCount", "itemSize", "onItemsRendered", "onScroll", "scrollDirection", "scrollOffset", "scrollToIndex", "scrollToAlignment", "stickyIndices", "style", "width", "WrapperComponent", "InnerComponent", "prefix", "innerStyleFilter"]);
        var offset = this.state.offset;
        var _e = this.sizeAndPositionManager.getVisibleRange({
            containerSize: this.props[constants.sizeProp[scrollDirection]] || 0,
            offset: offset,
            overscanCount: overscanCount
        }), start = _e.start, stop = _e.stop;
        var items = [];
        var wrapperStyle = tslib.__assign(tslib.__assign(tslib.__assign({}, STYLE_WRAPPER), style), { height: height, width: width });
        var innerStyle = tslib.__assign(tslib.__assign({}, STYLE_INNER), (_a = {}, _a[constants.sizeProp[scrollDirection]] = this.sizeAndPositionManager.getTotalSize(), _a));
        if (stickyIndices != null && stickyIndices.length !== 0) {
            stickyIndices.forEach(function (index) {
                return items.push(renderItem({
                    index: index,
                    style: _this.getStyle(index, true)
                }));
            });
            if (scrollDirection === constants.DIRECTION.HORIZONTAL) {
                innerStyle.display = 'flex';
            }
        }
        if (typeof start !== 'undefined' && typeof stop !== 'undefined') {
            for (var index = start; index <= stop; index++) {
                if (stickyIndices != null && ~stickyIndices.indexOf(index)) {
                    continue;
                }
                items.push(renderItem({
                    index: index,
                    style: this.getStyle(index, false)
                }));
            }
            if (typeof onItemsRendered === 'function') {
                onItemsRendered({
                    startIndex: start,
                    stopIndex: stop
                });
            }
        }
        var WrapperCmpt = WrapperComponent || 'div';
        var InnerCmpt = InnerComponent || 'div';
        return (_J$X_(WrapperCmpt, tslib.__assign({ ref: this.getRef }, props, { style: wrapperStyle }), prefix !== null && prefix !== void 0 ? prefix : null,
            _J$X_(InnerCmpt, { style: innerStyleFilter ? innerStyleFilter(innerStyle) : innerStyle }, items)));
    };
    VirtualList.prototype.getNodeOffset = function () {
        var _a = this.props.scrollDirection, scrollDirection = _a === void 0 ? constants.DIRECTION.VERTICAL : _a;
        return this.rootNode[constants.scrollProp[scrollDirection]];
    };
    VirtualList.prototype.getEstimatedItemSize = function (props) {
        if (props === void 0) { props = this.props; }
        return (props.estimatedItemSize ||
            (typeof props.itemSize === 'number' && props.itemSize) ||
            50);
    };
    VirtualList.prototype.getSize = function (index, itemSize) {
        if (typeof itemSize === 'function') {
            return itemSize(index);
        }
        return Array.isArray(itemSize) ? itemSize[index] : itemSize;
    };
    VirtualList.prototype.getStyle = function (index, sticky) {
        var _a, _b;
        var style = this.styleCache[index];
        if (style) {
            return style;
        }
        var _c = this.props.scrollDirection, scrollDirection = _c === void 0 ? constants.DIRECTION.VERTICAL : _c;
        var _d = this.sizeAndPositionManager.getSizeAndPositionForIndex(index), size = _d.size, offset = _d.offset;
        return (this.styleCache[index] = sticky
            ? tslib.__assign(tslib.__assign({}, STYLE_STICKY_ITEM), (_a = {}, _a[constants.sizeProp[scrollDirection]] = size, _a[constants.marginProp[scrollDirection]] = offset, _a[constants.oppositeMarginProp[scrollDirection]] = -(offset + size), _a.zIndex = 1, _a)) : tslib.__assign(tslib.__assign({}, STYLE_ITEM), (_b = {}, _b[constants.sizeProp[scrollDirection]] = size, _b[constants.positionProp[scrollDirection]] = offset, _b)));
    };
    VirtualList.defaultProps = {
        overscanCount: 3,
        scrollDirection: constants.DIRECTION.VERTICAL,
        width: '100%'
    };
    VirtualList.propTypes = {
        estimatedItemSize: PropTypes__namespace.number,
        height: PropTypes__namespace.oneOfType([PropTypes__namespace.number, PropTypes__namespace.string])
            .isRequired,
        itemCount: PropTypes__namespace.number.isRequired,
        itemSize: PropTypes__namespace.oneOfType([
            PropTypes__namespace.number,
            PropTypes__namespace.array,
            PropTypes__namespace.func
        ]).isRequired,
        onScroll: PropTypes__namespace.func,
        onItemsRendered: PropTypes__namespace.func,
        overscanCount: PropTypes__namespace.number,
        renderItem: PropTypes__namespace.func.isRequired,
        scrollOffset: PropTypes__namespace.number,
        scrollToIndex: PropTypes__namespace.number,
        scrollToAlignment: PropTypes__namespace.oneOf([
            constants.ALIGNMENT.AUTO,
            constants.ALIGNMENT.START,
            constants.ALIGNMENT.CENTER,
            constants.ALIGNMENT.END
        ]),
        scrollDirection: PropTypes__namespace.oneOf([
            constants.DIRECTION.HORIZONTAL,
            constants.DIRECTION.VERTICAL
        ]),
        stickyIndices: PropTypes__namespace.arrayOf(PropTypes__namespace.number),
        style: PropTypes__namespace.object,
        width: PropTypes__namespace.oneOfType([PropTypes__namespace.number, PropTypes__namespace.string])
    };
    return VirtualList;
}(React__namespace.PureComponent));

Object.defineProperty(exports, 'ScrollDirection', {
    enumerable: true,
    get: function () { return constants.DIRECTION; }
});
exports.AutoSizer = AutoSizer["default"];
exports["default"] = VirtualList;
