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 { 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, markdownRenderConfig = props.markdownRenderConfig, 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;
    // 兼容旧属性
    var loading = isLoading !== null && isLoading !== void 0 ? isLoading : legacyLoading;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var compact = (useContext(BubbleConfigContext) || {}).compact;
    var prefixClass = getPrefixCls('agentic-bubble-list');
    var _useStyle = useStyle(prefixClass), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var deps = useMemo(function() {
        return [
            props.style
        ];
    }, [
        JSON.stringify(props.style)
    ]);
    // 为 loading 项生成唯一的 key，使用 ref 缓存以确保稳定性
    // 使用 item 的唯一标识（index + createAt）作为缓存 key
    var loadingKeysRef = 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;
        return bubbleList.map(function(item, index) {
            var _props_bubbleRenderConfig;
            var isLast = bubbleList.length - 1 === index;
            var placement = item.role === 'user' ? 'right' : 'left';
            // 保持向后兼容性，设置isLatest
            item.isLatest = isLast;
            item.isLast = isLast;
            // 如果 id 是 LOADING_FLAT，使用 uuid 作为 key
            // 使用 index 和 createAt 的组合作为缓存 key，确保同一项在重新渲染时保持相同的 key
            var itemKey = item.id;
            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);
            }
            var bubbleElement = /*#__PURE__*/ React.createElement(Bubble, {
                key: itemKey,
                "data-id": item.id,
                avatar: _object_spread({}, item.role === 'user' ? userMeta : assistantMeta, item.meta),
                preMessage: bubbleList[index - 1],
                id: item.id,
                style: _object_spread({}, styles === null || styles === void 0 ? void 0 : styles.bubbleListItemStyle),
                originData: item,
                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: _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)
                }),
                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
            });
            // 如果启用了懒加载，用 LazyElement 包裹
            if (isLazyEnabled) {
                var _ref, _ref1, _ref2;
                var _props_lazy_shouldLazyLoad, _props_lazy, _props_lazy1, _props_lazy2, _props_lazy3;
                // 检查是否应该对该消息启用懒加载
                var shouldLazyLoad = (_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;
                // 如果不需要懒加载，直接返回元素
                if (!shouldLazyLoad) {
                    return bubbleElement;
                }
                // 创建适配的 renderPlaceholder，将 role 信息添加到 elementInfo
                var adaptedRenderPlaceholder = ((_props_lazy1 = props.lazy) === null || _props_lazy1 === void 0 ? void 0 : _props_lazy1.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: (_ref1 = (_props_lazy2 = props.lazy) === null || _props_lazy2 === void 0 ? void 0 : _props_lazy2.placeholderHeight) !== null && _ref1 !== void 0 ? _ref1 : 100,
                    rootMargin: (_ref2 = (_props_lazy3 = props.lazy) === null || _props_lazy3 === void 0 ? void 0 : _props_lazy3.rootMargin) !== null && _ref2 !== void 0 ? _ref2 : '200px',
                    renderPlaceholder: adaptedRenderPlaceholder,
                    elementInfo: {
                        type: 'bubble',
                        index: index,
                        total: totalCount
                    }
                }, bubbleElement);
            }
            return bubbleElement;
        });
    }, [
        bubbleList,
        props.style,
        props.lazy
    ]);
    if (loading) return wrapSSR(/*#__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("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;
