function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
import SkeletonList from "./SkeletonList";
export { PureBubbleList } from "./PureBubbleList";
import { useContext, useMemo, useRef } from "react";
import { ConfigProvider } from "antd";
import clsx from "clsx";
import { nanoid } from "nanoid";
import React from "react";
import { LazyElement } from "../../MarkdownEditor/editor/components/LazyElement";
import { Bubble } from "../Bubble";
import { BubbleConfigContext } from "../BubbleConfigProvide";
import { shallowEqualRecord, shallowEqualStyles } from "../bubblePropsAreEqual";
import { LOADING_FLAT } from "../MessagesContent";
import { useStyle } from "./style";
/**
 * BubbleList 组件 - 聊天气泡列表组件
 *
 * 该组件用于渲染聊天气泡列表，支持用户和助手的消息显示、加载状态、滚动事件等。
 * 提供完整的聊天界面功能，包括消息渲染、交互操作、样式自定义等。
 *
 * @component
 * @description 聊天气泡列表组件，渲染聊天消息列表
 * @param {BubbleListProps} props - 组件属性
 * @param {BubbleProps[]} [props.bubbleList=[]] - 气泡列表数据
 * @param {React.RefObject} [props.bubbleListRef] - 气泡列表引用
 * @param {boolean} [props.loading] - 是否显示加载状态
 * @param {string} [props.className] - 自定义CSS类名
 * @param {React.CSSProperties} [props.style] - 自定义样式
 * @param {BubbleRenderConfig} [props.bubbleRenderConfig] - 气泡渲染配置
 * @param {MarkdownRenderConfig} [props.markdownRenderConfig] - Markdown渲染配置
 * @param {BubbleMetaData} [props.userMeta] - 用户头像元数据
 * @param {BubbleMetaData} [props.assistantMeta] - 助手头像元数据
 * @param {BubbleStyles} [props.styles] - 自定义样式配置
 * @param {BubbleClassNames} [props.classNames] - 自定义类名配置
 * @param {boolean} [props.readonly] - 是否只读模式
 * @param {Function} [props.onScroll] - 滚动事件回调
 * @param {Function} [props.onWheel] - 滚轮事件回调
 * @param {Function} [props.onTouchMove] - 触摸移动事件回调
 * @param {Function} [props.onLike] - 点赞事件回调
 * @param {Function} [props.onDislike] - 点踩事件回调（符合命名规范）
 * @param {Function} [props.onDisLike] - 点踩事件回调（已废弃，请使用 onDislike）
 * @param {Function} [props.onReply] - 回复事件回调
 * @param {Function} [props.onLikeCancel] - 取消点赞事件回调（符合命名规范）
 * @param {Function} [props.onCancelLike] - 取消点赞事件回调（已废弃，请使用 onLikeCancel）
 * @param {Function} [props.onAvatarClick] - 头像点击事件回调
 * @param {Function} [props.onDoubleClick] - 双击事件回调
 * @param {boolean|Function} [props.shouldShowCopy] - 是否显示复制按钮
 *
 * @example
 * ```tsx
 * <BubbleList
 *   bubbleList={chatMessages}
 *   loading={false}
 *   userMeta={{ avatar: "user.jpg", title: "用户" }}
 *   assistantMeta={{ avatar: "assistant.jpg", title: "助手" }}
 *   onLike={(message) => console.log('点赞:', message)}
 *   onReply={(message) => console.log('回复:', message)}
 *   onAvatarClick={() => console.log('点击了头像')}
 *   onDoubleClick={() => console.log('双击了消息')}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的聊天气泡列表组件
 *
 * @remarks
 * - 支持用户和助手消息的不同布局
 * - 提供加载状态和骨架屏
 * - 支持消息交互操作（点赞、点踩、回复等）
 * - 支持自定义样式和类名
 * - 支持Markdown内容渲染
 * - 支持滚动和触摸事件
 * - 提供消息复制功能
 */ export var BubbleList = function BubbleList(props) {
    var bubbleListRef = props.bubbleListRef, bubbleRenderConfig = props.bubbleRenderConfig, className = props.className, legacyLoading = props.loading, isLoading = props.isLoading, styles = props.styles, classNames = props.classNames, markdownRenderConfigProp = props.markdownRenderConfig, renderMode = props.renderMode, renderType = props.renderType, userMeta = props.userMeta, assistantMeta = props.assistantMeta, _props_bubbleList = props.bubbleList, bubbleList = _props_bubbleList === void 0 ? [] : _props_bubbleList, style = props.style, onScroll = props.onScroll, onWheel = props.onWheel, onTouchMove = props.onTouchMove;
    // 合并 renderMode / renderType 快捷属性到 markdownRenderConfig
    var markdownRenderConfig = useMemo(function() {
        var _ref, _ref1;
        var mode = (_ref = (_ref1 = renderMode !== null && renderMode !== void 0 ? renderMode : renderType) !== null && _ref1 !== void 0 ? _ref1 : markdownRenderConfigProp === null || markdownRenderConfigProp === void 0 ? void 0 : markdownRenderConfigProp.renderMode) !== null && _ref !== void 0 ? _ref : markdownRenderConfigProp === null || markdownRenderConfigProp === void 0 ? void 0 : markdownRenderConfigProp.renderType;
        return mode ? _object_spread_props(_object_spread({}, markdownRenderConfigProp), {
            renderMode: mode
        }) : markdownRenderConfigProp;
    }, [
        markdownRenderConfigProp,
        renderMode,
        renderType
    ]);
    // 兼容旧属性
    var loading = isLoading !== null && isLoading !== void 0 ? isLoading : legacyLoading;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var parentContext = useContext(BubbleConfigContext);
    var compact = (parentContext || {}).compact;
    var mergedContext = useMemo(function() {
        var _props_extraShowOnHover;
        return parentContext ? _object_spread_props(_object_spread({}, parentContext), {
            extraShowOnHover: (_props_extraShowOnHover = props.extraShowOnHover) !== null && _props_extraShowOnHover !== void 0 ? _props_extraShowOnHover : parentContext.extraShowOnHover
        }) : {
            standalone: false,
            extraShowOnHover: props.extraShowOnHover
        };
    }, [
        parentContext,
        props.extraShowOnHover
    ]);
    var prefixClass = getPrefixCls('agentic-bubble-list');
    var _useStyle = useStyle(prefixClass), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var prevStyleRef = useRef(props.style);
    if (props.style !== prevStyleRef.current && !shallowEqualRecord(props.style || {}, prevStyleRef.current || {})) {
        prevStyleRef.current = props.style;
    }
    var deps = useMemo(function() {
        return [
            prevStyleRef.current
        ];
    }, [
        prevStyleRef.current
    ]);
    // 为 loading 项生成唯一的 key，使用 ref 缓存以确保稳定性
    var loadingKeysRef = useRef(new Map());
    // 记录每个 index 在上一轮是否是 loading，用于 loading→real 过渡时保持 key 稳定，避免闪动
    var loadingKeyByIndexRef = useRef(new Map());
    // 真实 id 映射到稳定 key（过渡后沿用），避免同一条消息因 id 变化导致 remount
    var realIdToStableKeyRef = useRef(new Map());
    /** 按列表行稳定 key 缓存合并后的 Bubble styles，避免每条消息每次父级渲染都换引用 */ var bubbleMergedStylesRef = useRef(new Map());
    var bubbleMergedAvatarRef = useRef(new Map());
    var bubbleListDom = useMemo(function() {
        var _props_lazy;
        var isLazyEnabled = (_props_lazy = props.lazy) === null || _props_lazy === void 0 ? void 0 : _props_lazy.enable;
        var totalCount = bubbleList.length;
        var activeRowKeys = new Set();
        var rows = bubbleList.map(function(item, index) {
            var _ref;
            var _props_lazy_shouldLazyLoad, _props_lazy, _props_bubbleRenderConfig;
            var isLast = bubbleList.length - 1 === index;
            var placement = item.role === 'user' ? 'right' : 'left';
            var originDataWithFlags = _object_spread_props(_object_spread({}, item), {
                isLatest: isLast,
                isLast: isLast
            });
            var itemKey;
            if (item.id === LOADING_FLAT) {
                var cacheKey = "".concat(index, "-").concat(item.createAt || Date.now());
                if (!loadingKeysRef.current.has(cacheKey)) {
                    loadingKeysRef.current.set(cacheKey, nanoid());
                }
                itemKey = loadingKeysRef.current.get(cacheKey);
                loadingKeyByIndexRef.current.set(index, itemKey);
            } else {
                var realId = item.id;
                var prevLoadingKey = loadingKeyByIndexRef.current.get(index);
                if (prevLoadingKey) {
                    itemKey = prevLoadingKey;
                    realIdToStableKeyRef.current.set(realId, prevLoadingKey);
                    loadingKeyByIndexRef.current.delete(index);
                } else if (realIdToStableKeyRef.current.has(realId)) {
                    itemKey = realIdToStableKeyRef.current.get(realId);
                } else {
                    itemKey = realId;
                }
            }
            activeRowKeys.add(itemKey);
            var candidateAvatar = _object_spread({}, item.role === 'user' ? userMeta : assistantMeta, item.meta);
            var prevAvatar = bubbleMergedAvatarRef.current.get(itemKey);
            if (!prevAvatar || !shallowEqualRecord(prevAvatar, candidateAvatar)) {
                bubbleMergedAvatarRef.current.set(itemKey, candidateAvatar);
            }
            var mergedAvatar = bubbleMergedAvatarRef.current.get(itemKey);
            var candidateStyles = _object_spread_props(_object_spread({}, styles), {
                bubbleListItemContentStyle: _object_spread({}, styles === null || styles === void 0 ? void 0 : styles.bubbleListItemContentStyle, placement === 'right' ? styles === null || styles === void 0 ? void 0 : styles.bubbleListRightItemContentStyle : styles === null || styles === void 0 ? void 0 : styles.bubbleListLeftItemContentStyle)
            });
            var prevMergedStyles = bubbleMergedStylesRef.current.get(itemKey);
            if (!prevMergedStyles || !shallowEqualStyles(prevMergedStyles, candidateStyles)) {
                bubbleMergedStylesRef.current.set(itemKey, candidateStyles);
            }
            var mergedStyles = bubbleMergedStylesRef.current.get(itemKey);
            // LazyElement 依赖被观察元素的几何尺寸；display:contents 不产生盒子，会导致
            // IntersectionObserver 在部分环境下永不触发，气泡永远不渲染。
            var useLazyWrapper = !!isLazyEnabled && ((_ref = (_props_lazy = props.lazy) === null || _props_lazy === void 0 ? void 0 : (_props_lazy_shouldLazyLoad = _props_lazy.shouldLazyLoad) === null || _props_lazy_shouldLazyLoad === void 0 ? void 0 : _props_lazy_shouldLazyLoad.call(_props_lazy, index, totalCount)) !== null && _ref !== void 0 ? _ref : true);
            var bubbleElement = /*#__PURE__*/ React.createElement("div", {
                key: itemKey,
                style: {
                    minWidth: 0,
                    width: '100%'
                },
                "data-bubble-list-item": true,
                "data-is-last": isLast ? 'true' : 'false'
            }, /*#__PURE__*/ React.createElement(Bubble, {
                "data-id": item.id,
                avatar: mergedAvatar,
                preMessage: bubbleList[index - 1],
                id: item.id,
                style: _object_spread({}, styles === null || styles === void 0 ? void 0 : styles.bubbleListItemStyle),
                originData: originDataWithFlags,
                placement: placement,
                time: item.updateAt || item.createAt,
                deps: deps,
                pure: props.pure,
                bubbleListRef: bubbleListRef,
                bubbleRenderConfig: bubbleRenderConfig,
                classNames: classNames,
                bubbleRef: props.bubbleRef,
                markdownRenderConfig: markdownRenderConfig,
                docListProps: props.docListProps,
                styles: mergedStyles,
                readonly: props.readonly,
                onReply: props.onReply,
                onDisLike: props.onDisLike,
                onDislike: props.onDislike,
                onLike: props.onLike,
                onCancelLike: props.onCancelLike,
                onLikeCancel: props.onLikeCancel,
                onAvatarClick: props.onAvatarClick,
                onDoubleClick: props.onDoubleClick,
                customConfig: props === null || props === void 0 ? void 0 : (_props_bubbleRenderConfig = props.bubbleRenderConfig) === null || _props_bubbleRenderConfig === void 0 ? void 0 : _props_bubbleRenderConfig.customConfig,
                shouldShowCopy: props.shouldShowCopy,
                shouldShowVoice: props.shouldShowVoice
            }));
            return {
                itemKey: itemKey,
                bubbleElement: bubbleElement,
                isLazyEnabled: isLazyEnabled,
                index: index,
                item: item,
                totalCount: totalCount,
                useLazyWrapper: useLazyWrapper
            };
        });
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            for(var _iterator = bubbleMergedStylesRef.current.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var k = _step.value;
                if (!activeRowKeys.has(k)) {
                    bubbleMergedStylesRef.current.delete(k);
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
        try {
            for(var _iterator1 = bubbleMergedAvatarRef.current.keys()[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
                var k1 = _step1.value;
                if (!activeRowKeys.has(k1)) {
                    bubbleMergedAvatarRef.current.delete(k1);
                }
            }
        } catch (err) {
            _didIteratorError1 = true;
            _iteratorError1 = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
                    _iterator1.return();
                }
            } finally{
                if (_didIteratorError1) {
                    throw _iteratorError1;
                }
            }
        }
        return rows.map(function(param) {
            var itemKey = param.itemKey, bubbleElement = param.bubbleElement, lazyOn = param.isLazyEnabled, index = param.index, item = param.item, count = param.totalCount, useLazyWrapper = param.useLazyWrapper;
            // 如果启用了懒加载，用 LazyElement 包裹
            if (lazyOn) {
                var _ref, _ref1;
                var _props_lazy, _props_lazy1, _props_lazy2;
                // 如果不需要懒加载，直接返回元素
                if (!useLazyWrapper) {
                    return bubbleElement;
                }
                // 创建适配的 renderPlaceholder，将 role 信息添加到 elementInfo
                var adaptedRenderPlaceholder = ((_props_lazy = props.lazy) === null || _props_lazy === void 0 ? void 0 : _props_lazy.renderPlaceholder) ? function(lazyProps) {
                    return props.lazy.renderPlaceholder(_object_spread_props(_object_spread({}, lazyProps), {
                        elementInfo: lazyProps.elementInfo ? _object_spread_props(_object_spread({}, lazyProps.elementInfo), {
                            role: item.role
                        }) : undefined
                    }));
                } : undefined;
                return /*#__PURE__*/ React.createElement(LazyElement, {
                    key: itemKey,
                    placeholderHeight: (_ref = (_props_lazy1 = props.lazy) === null || _props_lazy1 === void 0 ? void 0 : _props_lazy1.placeholderHeight) !== null && _ref !== void 0 ? _ref : 100,
                    rootMargin: (_ref1 = (_props_lazy2 = props.lazy) === null || _props_lazy2 === void 0 ? void 0 : _props_lazy2.rootMargin) !== null && _ref1 !== void 0 ? _ref1 : '200px',
                    renderPlaceholder: adaptedRenderPlaceholder,
                    elementInfo: {
                        type: 'bubble',
                        index: index,
                        total: count
                    }
                }, bubbleElement);
            }
            return bubbleElement;
        });
    }, [
        bubbleList,
        bubbleListRef,
        bubbleRenderConfig,
        classNames,
        deps,
        markdownRenderConfig,
        props.bubbleRef,
        props.docListProps,
        props.lazy,
        props.onAvatarClick,
        props.onCancelLike,
        props.onDisLike,
        props.onDislike,
        props.onDoubleClick,
        props.onLike,
        props.onLikeCancel,
        props.onReply,
        props.pure,
        props.readonly,
        props.shouldShowCopy,
        props.shouldShowVoice,
        props.style,
        styles,
        userMeta,
        assistantMeta
    ]);
    if (loading) return wrapSSR(/*#__PURE__*/ React.createElement(BubbleConfigContext.Provider, {
        value: mergedContext
    }, /*#__PURE__*/ React.createElement("div", {
        className: clsx(prefixClass, "".concat(prefixClass, "-loading"), className, hashId),
        ref: bubbleListRef,
        style: {
            padding: 24
        }
    }, /*#__PURE__*/ React.createElement(SkeletonList, null))));
    var _obj;
    return wrapSSR(/*#__PURE__*/ React.createElement(BubbleConfigContext.Provider, {
        value: mergedContext
    }, /*#__PURE__*/ React.createElement("div", {
        className: clsx("".concat(prefixClass), className, hashId, (_obj = {}, _define_property(_obj, "".concat(prefixClass, "-readonly"), props.readonly), _define_property(_obj, "".concat(prefixClass, "-compact"), compact), _obj)),
        "data-chat-list": bubbleList.length,
        style: style,
        ref: bubbleListRef,
        onScroll: onScroll,
        onWheel: function onWheel1(e) {
            return onWheel === null || onWheel === void 0 ? void 0 : onWheel(e, (bubbleListRef === null || bubbleListRef === void 0 ? void 0 : bubbleListRef.current) || null);
        },
        onTouchMove: function onTouchMove1(e) {
            return onTouchMove === null || onTouchMove === void 0 ? void 0 : onTouchMove(e, (bubbleListRef === null || bubbleListRef === void 0 ? void 0 : bubbleListRef.current) || null);
        }
    }, bubbleListDom)));
};
export default BubbleList;
