/**
 * 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 amisCore = require('amis-core');
var TooltipWrapper = require('./TooltipWrapper.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var AutoFoldedList = function (props) {
    var items = props.items, renderItem = props.renderItem, renderMoreSummary = props.renderMoreSummary, renderTooltipContent = props.renderTooltipContent, _a = props.enabled, enabled = _a === void 0 ? true : _a, cx = props.classnames, popOverContainer = props.popOverContainer, tooltipClassName = props.tooltipClassName, tooltipOptions = props.tooltipOptions, maxVisibleCount = props.maxVisibleCount;
    // State to track number of visible items
    var _b = tslib.__read(React.useState(0), 2), visibleCount = _b[0], setVisibleCount = _b[1];
    // Refs for container and "more" elements
    var moreRef = React.useRef(null);
    var _c = tslib.__read(React__default["default"].useMemo(function () {
        return [
            visibleCount && enabled ? items.slice(0, visibleCount) : items,
            visibleCount && enabled ? items.slice(visibleCount) : []
        ];
    }, [items, visibleCount, enabled]), 2), visibleItems = _c[0], restItems = _c[1];
    /**
     * Renders a single list item with proper key
     */
    var itemRender = React__default["default"].useCallback(function (item, index, folded) {
        var dom = renderItem(item, index, folded);
        if (React__default["default"].isValidElement(dom)) {
            return React__default["default"].cloneElement(dom, {
                key: index
            });
        }
        return _J$X_("div", { key: index }, dom);
    }, [renderItem]);
    /**
     * Effect to calculate and update visible items count based on container width
     */
    React.useEffect(function () {
        if (!enabled) {
            return;
        }
        var more = moreRef.current;
        var container = more.parentElement;
        var moreWidth = Math.max(more.offsetWidth, 30);
        var gap = 10;
        var lastExtendAt = 0;
        var calculateVisibleCount = function () {
            var rect = container.getBoundingClientRect();
            if (!rect.width) {
                return;
            }
            var list = Array.from(container.children).filter(function (item) { return !item.hasAttribute('data-folder-ignore'); });
            var rightElementsWidth = 0;
            var rightElement = more.nextElementSibling;
            while (rightElement) {
                rightElementsWidth += rightElement.offsetWidth;
                rightElement = rightElement.nextElementSibling;
            }
            var last = more.previousElementSibling;
            while (last) {
                if (last.getBoundingClientRect().right +
                    moreWidth +
                    gap +
                    rightElementsWidth <
                    rect.right) {
                    break;
                }
                last = last.previousElementSibling;
            }
            if (last &&
                last === more.previousElementSibling &&
                Date.now() - lastExtendAt > 200 // Prevent flickering
            ) {
                // Expand to show more items
                var width = last.offsetWidth;
                lastExtendAt = Date.now();
                var extend = Math.max(Math.floor((rect.right -
                    last.getBoundingClientRect().right -
                    moreWidth -
                    gap) /
                    width), 0);
                setVisibleCount(Math.min(list.indexOf(last) + 1 + extend, maxVisibleCount !== null && maxVisibleCount !== void 0 ? maxVisibleCount : items.length));
            }
            else if (last) {
                // Collapse to show fewer items
                setVisibleCount(list.indexOf(last) + 1);
            }
        };
        calculateVisibleCount();
        return amisCore.resizeSensor(container, calculateVisibleCount, false, 'both', true);
    }, [items, maxVisibleCount, enabled]);
    React__default["default"].useLayoutEffect(function () {
        var _a;
        if (!enabled) {
            return;
        }
        (_a = moreRef.current.parentElement) === null || _a === void 0 ? void 0 : _a.classList.add(cx('AutoFoldedList'));
        return function () {
            var _a;
            (_a = moreRef.current.parentElement) === null || _a === void 0 ? void 0 : _a.classList.remove(cx('AutoFoldedList'));
        };
    }, [enabled]);
    return (_J$X_(React__default["default"].Fragment, null,
        visibleItems.map(function (item, index) { return itemRender(item, index, false); }),
        _J$X_("div", { className: cx('AutoFoldedList-more'), ref: moreRef }, restItems.length > 0 ? (_J$X_(TooltipWrapper["default"], { container: popOverContainer, tooltip: tslib.__assign(tslib.__assign({ placement: 'auto', trigger: 'hover', showArrow: false }, tooltipOptions), { children: function () { return (_J$X_("div", { className: cx('AutoFoldedList-more-tooltip', tooltipClassName) }, renderTooltipContent
                    ? renderTooltipContent(restItems)
                    : restItems.map(function (item, index) {
                        return itemRender(item, index + visibleCount, true);
                    }))); } }) }, renderMoreSummary ? (renderMoreSummary(restItems)) : (_J$X_("span", null,
            "+ ",
            restItems.length,
            " ...")))) : null)));
};
var AutoFoldedList$1 = amisCore.themeable(AutoFoldedList);

exports.AutoFoldedList = AutoFoldedList;
exports["default"] = AutoFoldedList$1;
