function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
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 _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = _object_without_properties_loose(source, excluded);
    var key, i;
    if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceSymbolKeys.length; i++){
            key = sourceSymbolKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, g, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    };
    return g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(_)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { ConfigProvider } from "antd";
import classNames from "classnames";
import { useMergedState } from "rc-util";
import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useRefFunction } from "../Hooks/useRefFunction";
import { BaseMarkdownEditor } from "../MarkdownEditor";
import { upLoadFileToServer } from "./AttachmentButton";
import { isMobileDevice } from "./AttachmentButton/utils";
import { AttachmentFileList } from "./AttachmentButton/AttachmentFileList";
import { getFileListFromDataTransferItems } from "./FilePaste";
import { useFileUploadManager } from "./FileUploadManager";
import { QuickActions } from "./QuickActions";
import { SendActions } from "./SendActions";
import { SkillModeBar } from "./SkillModeBar";
import { useStyle } from "./style";
import { Suggestion } from "./Suggestion";
import TopOperatingArea from "./TopOperatingArea";
import { useVoiceInputManager } from "./VoiceInputManager";
/**
 * MarkdownInputField 组件 - Markdown输入字段组件
 *
 * 该组件提供一个功能完整的Markdown输入框，支持实时预览、文件附件、
 * 快捷键发送、自动完成等功能。是聊天应用中的核心输入组件。
 *
 * @component
 * @description Markdown输入字段组件，支持实时预览和文件附件
 * @param {MarkdownInputFieldProps} props - 组件属性
 * @param {string} [props.value] - 输入框的值
 * @param {(value: string) => void} [props.onChange] - 值变化时的回调
 * @param {(value: string) => Promise<void>} [props.onSend] - 发送消息的回调
 * @param {string} [props.placeholder] - 占位符文本
 * @param {string} [props.triggerSendKey='Enter'] - 触发发送的快捷键（Enter 发送，Shift+Enter 换行）
 * @param {boolean} [props.disabled] - 是否禁用
 * @param {boolean} [props.typing] - 是否正在输入
 * @param {AttachmentProps} [props.attachment] - 附件配置
 * @param {string[]} [props.bgColorList] - 背景颜色列表，推荐使用3-4种颜色
 * @param {React.RefObject} [props.inputRef] - 输入框引用
 * @param {MarkdownRenderConfig} [props.markdownRenderConfig] - Markdown渲染配置
 * @param {SuggestionProps} [props.suggestion] - 自动完成配置
 *
 * @example
 * ```tsx
 * <MarkdownInputField
 *   value="# 标题"
 *   onChange={(value) => console.log(value)}
 *   onSend={(value) => Promise.resolve()}
 *   placeholder="请输入Markdown文本..."
 *   triggerSendKey="Enter"
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的Markdown输入字段组件
 *
 * @remarks
 * - 支持实时Markdown预览
 * - 支持文件附件上传
 * - 支持快捷键发送消息
 * - 支持自动完成功能
 * - 支持自定义渲染配置
 */ export var MarkdownInputField = function(_param) {
    var tagInputProps = _param.tagInputProps, markdownProps = _param.markdownProps, _param_borderRadius = _param.borderRadius, borderRadius = _param_borderRadius === void 0 ? 16 : _param_borderRadius, onBlur = _param.onBlur, onFocus = _param.onFocus, _param_isShowTopOperatingArea = _param.isShowTopOperatingArea, isShowTopOperatingArea = _param_isShowTopOperatingArea === void 0 ? false : _param_isShowTopOperatingArea, props = _object_without_properties(_param, [
        "tagInputProps",
        "markdownProps",
        "borderRadius",
        "onBlur",
        "onFocus",
        "isShowTopOperatingArea"
    ]);
    var _props_style, _props_attachment, _props_attachment1, _props_attachment2, _props_attachment3, _props_enlargeable, _props_refinePrompt, _props_style1, _props_attachment4, _props_attachment5, _props_enlargeable1, _props_refinePrompt1, _props_enlargeable2, _props_enlargeable3;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var baseCls = getPrefixCls('agentic-md-input-field');
    var _useStyle = useStyle(baseCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _React_useState = _sliced_to_array(React.useState(false), 2), isHover = _React_useState[0], setHover = _React_useState[1];
    var _React_useState1 = _sliced_to_array(React.useState(false), 2), isLoading = _React_useState1[0], setIsLoading = _React_useState1[1];
    var _React_useState2 = _sliced_to_array(React.useState(false), 2), isEnlarged = _React_useState2[0], setIsEnlarged = _React_useState2[1];
    var markdownEditorRef = React.useRef();
    var quickActionsRef = React.useRef(null);
    var actionsRef = React.useRef(null);
    var isSendingRef = React.useRef(false); // 防重复触发标记
    var _useState = _sliced_to_array(useState(function() {
        if (typeof window === 'undefined') return false;
        if (window.innerWidth < 460) return true;
        return false;
    }), 2), collapseSendActions = _useState[0], setCollapseSendActions = _useState[1];
    var _useMergedState = _sliced_to_array(useMergedState('', {
        value: props.value,
        onChange: props.onChange
    }), 2), value = _useMergedState[0], setValue = _useMergedState[1];
    var _useState1 = _sliced_to_array(useState(64), 2), rightPadding = _useState1[0], setRightPadding = _useState1[1];
    var _useState2 = _sliced_to_array(useState(0), 2), topRightPadding = _useState2[0], setTopRightPadding = _useState2[1];
    var _useState3 = _sliced_to_array(useState(0), 2), quickRightOffset = _useState3[0], setQuickRightOffset = _useState3[1];
    var computedRightPadding = useMemo(function() {
        var bottomOverlayPadding = props.toolsRender ? 0 : rightPadding || 52;
        var topOverlayPadding = (topRightPadding || 0) + (quickRightOffset || 0);
        return Math.max(bottomOverlayPadding, topOverlayPadding);
    }, [
        props.toolsRender,
        rightPadding,
        topRightPadding,
        quickRightOffset
    ]);
    var collapsedHeight = useMemo(function() {
        var _props_style;
        var _props_maxHeight;
        // 优先使用 maxHeight prop，其次使用 style.maxHeight，最后使用默认值
        var maxHeightValue = (_props_maxHeight = props.maxHeight) !== null && _props_maxHeight !== void 0 ? _props_maxHeight : (_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.maxHeight;
        var base = typeof maxHeightValue === 'number' ? maxHeightValue : maxHeightValue ? parseFloat(String(maxHeightValue)) || 114 : 114;
        return base;
    }, [
        props.maxHeight,
        (_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.maxHeight,
        (_props_attachment = props.attachment) === null || _props_attachment === void 0 ? void 0 : _props_attachment.enable
    ]);
    var collapsedHeightPx = useMemo(function() {
        var _props_attachment;
        var extra = ((_props_attachment = props.attachment) === null || _props_attachment === void 0 ? void 0 : _props_attachment.enable) ? 90 : 0;
        return collapsedHeight + extra;
    }, [
        collapsedHeight,
        (_props_attachment1 = props.attachment) === null || _props_attachment1 === void 0 ? void 0 : _props_attachment1.enable
    ]);
    var _useMergedState1 = _sliced_to_array(useMergedState(undefined, {
        value: (_props_attachment2 = props.attachment) === null || _props_attachment2 === void 0 ? void 0 : _props_attachment2.fileMap,
        onChange: (_props_attachment3 = props.attachment) === null || _props_attachment3 === void 0 ? void 0 : _props_attachment3.onFileMapChange
    }), 2), fileMap = _useMergedState1[0], setFileMap = _useMergedState1[1];
    var hasEnlargeAction = !!(props === null || props === void 0 ? void 0 : (_props_enlargeable = props.enlargeable) === null || _props_enlargeable === void 0 ? void 0 : _props_enlargeable.enable);
    var hasRefineAction = !!(props === null || props === void 0 ? void 0 : (_props_refinePrompt = props.refinePrompt) === null || _props_refinePrompt === void 0 ? void 0 : _props_refinePrompt.enable);
    var hasCustomQuickAction = !!(props === null || props === void 0 ? void 0 : props.quickActionRender);
    var hasActionsRender = !!(props === null || props === void 0 ? void 0 : props.actionsRender);
    var hasToolsRender = !!(props === null || props === void 0 ? void 0 : props.toolsRender);
    var quickActionCount = Number(hasEnlargeAction) + Number(hasRefineAction) + Number(hasCustomQuickAction);
    var auxiliaryActionCount = Number(hasActionsRender) + Number(hasToolsRender);
    var totalActionCount = quickActionCount + auxiliaryActionCount;
    // 是否需要多行布局
    var isMultiRowLayout = totalActionCount > 0;
    // 计算最小高度
    var computedMinHeight = useMemo(function() {
        var _props_style, _props_style1;
        if (isEnlarged) return 'auto';
        if (((_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.minHeight) !== undefined) return props.style.minHeight;
        // 如果同时有放大按钮和提示词优化按钮，最小高度为 140px
        if (hasEnlargeAction && hasRefineAction) return 140;
        if (totalActionCount === 1) return 90;
        // 其他多行布局情况，最小高度为 106px
        if (isMultiRowLayout) return 106;
        // 默认使用传入的 minHeight 或 0
        return ((_props_style1 = props.style) === null || _props_style1 === void 0 ? void 0 : _props_style1.minHeight) || 0;
    }, [
        isEnlarged,
        hasEnlargeAction,
        hasRefineAction,
        isMultiRowLayout,
        totalActionCount,
        (_props_style1 = props.style) === null || _props_style1 === void 0 ? void 0 : _props_style1.minHeight
    ]);
    // 文件上传管理
    var _useFileUploadManager = useFileUploadManager({
        attachment: props.attachment,
        fileMap: fileMap,
        onFileMapChange: setFileMap
    }), fileUploadDone = _useFileUploadManager.fileUploadDone, supportedFormat = _useFileUploadManager.supportedFormat, uploadImage = _useFileUploadManager.uploadImage, updateAttachmentFiles = _useFileUploadManager.updateAttachmentFiles, handleFileRemoval = _useFileUploadManager.handleFileRemoval, handleFileRetry = _useFileUploadManager.handleFileRetry;
    // 语音输入管理
    var _useVoiceInputManager = useVoiceInputManager({
        voiceRecognizer: props.voiceRecognizer,
        editorRef: markdownEditorRef,
        onValueChange: setValue
    }), recording = _useVoiceInputManager.recording, startRecording = _useVoiceInputManager.startRecording, stopRecording = _useVoiceInputManager.stopRecording;
    useEffect(function() {
        var _markdownEditorRef_current_store, _markdownEditorRef_current;
        if (!markdownEditorRef.current) return;
        (_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : (_markdownEditorRef_current_store = _markdownEditorRef_current.store) === null || _markdownEditorRef_current_store === void 0 ? void 0 : _markdownEditorRef_current_store.setMDContent(value);
    }, [
        props.value
    ]);
    useImperativeHandle(props.inputRef, function() {
        return markdownEditorRef.current;
    });
    // 已移除 enlargeTargetRef，不需要校验容器定位
    /**
   * 处理放大缩小按钮点击
   * @description 切换编辑器的放大/缩小状态
   */ var handleEnlargeClick = useRefFunction(function() {
        setIsEnlarged(!isEnlarged);
    });
    /**
   * 发送消息的函数
   * @description 该函数用于处理发送消息的逻辑，包括调用回调函数和清空输入框。
   * @returns {Promise<void>} 发送操作的Promise
   * @example
   * ```tsx
   * <MarkdownInputField
   *   value="# 示例"
   *   onChange={(value) => console.log(value)}
   *   onSend={(value) => Promise.resolve()}
   * />
   * ```
   */ var sendMessage = useRefFunction(/*#__PURE__*/ _async_to_generator(function() {
        var _markdownEditorRef_current_store, _markdownEditorRef_current, mdValue, _props_onChange, _markdownEditorRef_current_store1, _markdownEditorRef_current1, _props_onChange1, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (props.disabled) return [
                        2
                    ];
                    if (props.typing) return [
                        2
                    ];
                    // 防止重复触发：如果正在加载中，直接返回
                    if (isLoading) return [
                        2
                    ];
                    // 使用 ref 防止快速连续触发
                    if (isSendingRef.current) return [
                        2
                    ];
                    if (!recording) return [
                        3,
                        2
                    ];
                    return [
                        4,
                        stopRecording()
                    ];
                case 1:
                    _state.sent();
                    _state.label = 2;
                case 2:
                    mdValue = markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : (_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : (_markdownEditorRef_current_store = _markdownEditorRef_current.store) === null || _markdownEditorRef_current_store === void 0 ? void 0 : _markdownEditorRef_current_store.getMDContent();
                    // 如果mdValue和value不一致，并且mdValue不为空，则调用onChange
                    if (mdValue !== value && mdValue) {
                        ;
                        (_props_onChange = props.onChange) === null || _props_onChange === void 0 ? void 0 : _props_onChange.call(props, mdValue);
                    }
                    if (!(props.onSend && (props.allowEmptySubmit || mdValue))) return [
                        3,
                        7
                    ];
                    // 设置发送标记
                    isSendingRef.current = true;
                    setIsLoading(true);
                    _state.label = 3;
                case 3:
                    _state.trys.push([
                        3,
                        5,
                        6,
                        7
                    ]);
                    return [
                        4,
                        props.onSend(mdValue || '')
                    ];
                case 4:
                    _state.sent();
                    markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : (_markdownEditorRef_current1 = markdownEditorRef.current) === null || _markdownEditorRef_current1 === void 0 ? void 0 : (_markdownEditorRef_current_store1 = _markdownEditorRef_current1.store) === null || _markdownEditorRef_current_store1 === void 0 ? void 0 : _markdownEditorRef_current_store1.clearContent();
                    (_props_onChange1 = props.onChange) === null || _props_onChange1 === void 0 ? void 0 : _props_onChange1.call(props, '');
                    setValue('');
                    setFileMap === null || setFileMap === void 0 ? void 0 : setFileMap(new Map());
                    return [
                        3,
                        7
                    ];
                case 5:
                    error = _state.sent();
                    console.error('Send message failed:', error);
                    throw error;
                case 6:
                    setIsLoading(false);
                    // 重置发送标记
                    isSendingRef.current = false;
                    return [
                        7
                    ];
                case 7:
                    return [
                        2
                    ];
            }
        });
    }));
    /**
   * 放大状态样式计算
   */ var enlargedStyle = useMemo(function() {
        if (!isEnlarged) return {};
        return {
            maxHeight: '980px',
            minHeight: '280px'
        };
    }, [
        isEnlarged
    ]);
    var beforeTools = useMemo(function() {
        if (props.beforeToolsRender) {
            return props.beforeToolsRender(_object_spread_props(_object_spread({}, props), {
                isHover: isHover,
                isLoading: isLoading
            }));
        }
        return null;
    }, [
        props,
        isHover,
        isLoading
    ]);
    var inputRef = useRef(null);
    var activeInput = useRefFunction(function(active) {
        if (inputRef.current) {
            if (active) {
                var _inputRef_current;
                inputRef.current.tabIndex = 1;
                (_inputRef_current = inputRef.current) === null || _inputRef_current === void 0 ? void 0 : _inputRef_current.classList.add('active');
            } else {
                var _inputRef_current1;
                inputRef.current.tabIndex = -1;
                (_inputRef_current1 = inputRef.current) === null || _inputRef_current1 === void 0 ? void 0 : _inputRef_current1.classList.remove('active');
            }
        }
    });
    useEffect(function() {
        if (!inputRef.current) return;
        if (process.env.NODE_ENV === 'test') return;
        var handleResize = function() {
            var _inputRef_current;
            if (!inputRef.current) return;
            if (process.env.NODE_ENV === 'test') return;
            if (((_inputRef_current = inputRef.current) === null || _inputRef_current === void 0 ? void 0 : _inputRef_current.clientWidth) < 481) {
                setCollapseSendActions(true);
            } else {
                setCollapseSendActions(false);
            }
        };
        handleResize();
        var resizeObserver = new ResizeObserver(handleResize);
        resizeObserver.observe(inputRef.current);
        return function() {
            resizeObserver.disconnect();
        };
    }, []);
    // 图片粘贴上传
    var handlePaste = useCallback(/*#__PURE__*/ function() {
        var _ref = _async_to_generator(function(e) {
            var imageFiles;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        return [
                            4,
                            getFileListFromDataTransferItems(e)
                        ];
                    case 1:
                        imageFiles = _state.sent().filter(function(file) {
                            return file.type.startsWith('image/');
                        });
                        upLoadFileToServer(imageFiles, _object_spread_props(_object_spread({}, markdownProps === null || markdownProps === void 0 ? void 0 : markdownProps.attachment), {
                            fileMap: fileMap,
                            onFileMapChange: setFileMap
                        }));
                        return [
                            2
                        ];
                }
            });
        });
        return function(e) {
            return _ref.apply(this, arguments);
        };
    }(), [
        fileMap,
        markdownProps === null || markdownProps === void 0 ? void 0 : markdownProps.attachment
    ]);
    // 预计算：附件列表节点，减少 JSX 嵌套
    var attachmentList = useMemo(function() {
        var _props_attachment;
        if (!((_props_attachment = props.attachment) === null || _props_attachment === void 0 ? void 0 : _props_attachment.enable)) return null;
        return /*#__PURE__*/ React.createElement(AttachmentFileList, {
            fileMap: fileMap,
            onDelete: handleFileRemoval,
            onRetry: handleFileRetry,
            onClearFileMap: function() {
                updateAttachmentFiles(new Map());
            }
        });
    }, [
        fileMap,
        (_props_attachment4 = props.attachment) === null || _props_attachment4 === void 0 ? void 0 : _props_attachment4.enable,
        handleFileRemoval,
        handleFileRetry,
        updateAttachmentFiles
    ]);
    // 键盘事件：早返回减少嵌套
    var handleKeyDown = useRefFunction(function(e) {
        var _markdownEditorRef_current;
        if (markdownEditorRef === null || markdownEditorRef === void 0 ? void 0 : (_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : _markdownEditorRef_current.store.inputComposition) return;
        var isEnter = e.key === 'Enter';
        var isMod = e.ctrlKey || e.metaKey;
        var isShift = e.shiftKey;
        // 手机端禁用 Enter 键发送
        if (isEnter && !isMod && !isShift && isMobileDevice()) {
            return; // 让编辑器正常处理换行
        }
        // Enter 发送，Shift+Enter 换行
        if (!isEnter || isMod) return;
        if (isShift) return; // Shift+Enter 时让编辑器处理换行
        e.stopPropagation();
        e.preventDefault();
        if (props.onSend) sendMessage();
    });
    // 预计算：SendActions 节点，统一渲染，避免重复 JSX
    var sendActionsNode = /*#__PURE__*/ React.createElement(SendActions, {
        attachment: _object_spread_props(_object_spread({}, props.attachment), {
            supportedFormat: supportedFormat,
            fileMap: fileMap,
            onFileMapChange: setFileMap,
            upload: ((_props_attachment5 = props.attachment) === null || _props_attachment5 === void 0 ? void 0 : _props_attachment5.upload) ? function(file) {
                return props.attachment.upload(file, 0);
            } : undefined
        }),
        voiceRecognizer: props.voiceRecognizer,
        value: value,
        disabled: props.disabled,
        typing: props.typing,
        isLoading: isLoading,
        fileUploadDone: fileUploadDone,
        recording: recording,
        collapseSendActions: collapseSendActions,
        allowEmptySubmit: props.allowEmptySubmit,
        uploadImage: uploadImage,
        onStartRecording: startRecording,
        onStopRecording: stopRecording,
        onSend: sendMessage,
        onStop: function() {
            var _props_onStop;
            setIsLoading(false);
            (_props_onStop = props.onStop) === null || _props_onStop === void 0 ? void 0 : _props_onStop.call(props);
        },
        actionsRender: props.actionsRender,
        prefixCls: baseCls,
        hashId: hashId,
        hasTools: !!props.toolsRender,
        onResize: setRightPadding
    });
    var _props_enlargeable_height;
    var _obj, _obj1;
    return wrapSSR(/*#__PURE__*/ React.createElement(React.Fragment, null, isShowTopOperatingArea && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-top-area"), hashId)
    }, /*#__PURE__*/ React.createElement(TopOperatingArea, {
        targetRef: props.targetRef,
        operationBtnRender: props.operationBtnRender,
        isShowBackTo: props.isShowBackTo
    })), beforeTools ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-before-tools"), hashId)
    }, beforeTools) : null, /*#__PURE__*/ React.createElement(Suggestion, {
        tagInputProps: _object_spread({
            enable: true,
            type: 'dropdown'
        }, tagInputProps)
    }, /*#__PURE__*/ React.createElement("div", {
        ref: inputRef,
        className: classNames(baseCls, hashId, props.className, (_obj = {}, _define_property(_obj, "".concat(baseCls, "-disabled"), props.disabled), _define_property(_obj, "".concat(baseCls, "-typing"), false), _define_property(_obj, "".concat(baseCls, "-loading"), isLoading), _define_property(_obj, "".concat(baseCls, "-is-multi-row"), isMultiRowLayout), _define_property(_obj, "".concat(baseCls, "-enlarged"), isEnlarged), _obj)),
        style: _object_spread_props(_object_spread({}, props.style, enlargedStyle), {
            height: isEnlarged ? "".concat((_props_enlargeable_height = (_props_enlargeable1 = props.enlargeable) === null || _props_enlargeable1 === void 0 ? void 0 : _props_enlargeable1.height) !== null && _props_enlargeable_height !== void 0 ? _props_enlargeable_height : 980, "px") : "min(".concat(collapsedHeightPx, "px,100%)"),
            borderRadius: borderRadius || 16,
            minHeight: computedMinHeight,
            cursor: isLoading || props.disabled ? 'not-allowed' : 'auto',
            opacity: props.disabled ? 0.5 : 1,
            maxHeight: isEnlarged ? 'none' : props.maxHeight !== undefined ? typeof props.maxHeight === 'number' ? "".concat(props.maxHeight, "px") : props.maxHeight : "min(".concat(collapsedHeightPx, "px,100%)"),
            transition: 'height, max-height 0.3s,border-radius 0.3s,box-shadow 0.3s,transform 0.3s,opacity 0.3s,background 0.3s'
        }),
        tabIndex: 1,
        onMouseEnter: function() {
            return setHover(true);
        },
        onMouseLeave: function() {
            return setHover(false);
        },
        onKeyDown: handleKeyDown
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            flexDirection: 'column',
            borderTopLeftRadius: 'inherit',
            borderTopRightRadius: 'inherit',
            maxHeight: isEnlarged ? 'none' : function() {
                var _props_style, _props_attachment;
                var _props_maxHeight;
                // 优先使用 maxHeight prop，其次使用 style.maxHeight，最后使用默认值
                var maxHeightValue = (_props_maxHeight = props.maxHeight) !== null && _props_maxHeight !== void 0 ? _props_maxHeight : (_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.maxHeight;
                var base = typeof maxHeightValue === 'number' ? maxHeightValue : maxHeightValue ? parseFloat(String(maxHeightValue)) || 400 : 400;
                var extra = ((_props_attachment = props.attachment) === null || _props_attachment === void 0 ? void 0 : _props_attachment.enable) ? 90 : 0;
                return "min(".concat(base + extra, "px)");
            }(),
            height: isEnlarged ? '100%' : 'auto',
            flex: 1
        },
        className: classNames("".concat(baseCls, "-editor"), hashId, (_obj1 = {}, _define_property(_obj1, "".concat(baseCls, "-editor-hover"), isHover), _define_property(_obj1, "".concat(baseCls, "-editor-disabled"), props.disabled), _obj1))
    }, /*#__PURE__*/ React.createElement(SkillModeBar, {
        skillMode: props.skillMode,
        onSkillModeOpenChange: props.onSkillModeOpenChange
    }), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-editor-content"), hashId)
    }, attachmentList, /*#__PURE__*/ React.createElement(BaseMarkdownEditor, _object_spread({
        editorRef: markdownEditorRef,
        leafRender: props.leafRender,
        style: {
            width: '100%',
            flex: 1,
            padding: 0,
            paddingRight: computedRightPadding
        },
        toolBar: {
            enable: false
        },
        floatBar: {
            enable: false
        },
        readonly: isLoading,
        contentStyle: {
            padding: 'var(--padding-3x)'
        },
        textAreaProps: {
            enable: true,
            placeholder: props.placeholder
        },
        tagInputProps: _object_spread({
            enable: true,
            type: 'dropdown'
        }, tagInputProps),
        initValue: props.value,
        onChange: function(value) {
            var _props_onChange;
            // 检查并限制字符数
            if (props.maxLength !== undefined) {
                if (value.length > props.maxLength) {
                    var _props_onChange1, _props_onMaxLengthExceeded, // 更新编辑器内容以反映截断后的值
                    _markdownEditorRef_current_store, _markdownEditorRef_current;
                    var truncatedValue = value.slice(0, props.maxLength);
                    setValue(truncatedValue);
                    (_props_onChange1 = props.onChange) === null || _props_onChange1 === void 0 ? void 0 : _props_onChange1.call(props, truncatedValue);
                    (_props_onMaxLengthExceeded = props.onMaxLengthExceeded) === null || _props_onMaxLengthExceeded === void 0 ? void 0 : _props_onMaxLengthExceeded.call(props, value);
                    (_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : (_markdownEditorRef_current_store = _markdownEditorRef_current.store) === null || _markdownEditorRef_current_store === void 0 ? void 0 : _markdownEditorRef_current_store.setMDContent(truncatedValue);
                    return;
                }
            }
            setValue(value);
            (_props_onChange = props.onChange) === null || _props_onChange === void 0 ? void 0 : _props_onChange.call(props, value);
        },
        onFocus: function(value, schema, e) {
            onFocus === null || onFocus === void 0 ? void 0 : onFocus(value, schema, e);
            activeInput(true);
        },
        onBlur: function(value, schema, e) {
            onBlur === null || onBlur === void 0 ? void 0 : onBlur(value, schema, e);
            activeInput(false);
        },
        onPaste: function(e) {
            handlePaste(e);
        },
        titlePlaceholderContent: props.placeholder,
        toc: false,
        pasteConfig: props.pasteConfig
    }, markdownProps)))), props.toolsRender ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-tools-wrapper"), hashId)
    }, /*#__PURE__*/ React.createElement("div", {
        ref: actionsRef,
        contentEditable: false,
        className: classNames("".concat(baseCls, "-send-tools"), hashId)
    }, props.toolsRender(_object_spread_props(_object_spread({
        value: value,
        fileMap: fileMap,
        onFileMapChange: setFileMap
    }, props), {
        isHover: isHover,
        isLoading: isLoading,
        fileUploadStatus: fileUploadDone ? 'done' : 'uploading'
    }))), sendActionsNode) : sendActionsNode, (props === null || props === void 0 ? void 0 : props.quickActionRender) || ((_props_refinePrompt1 = props.refinePrompt) === null || _props_refinePrompt1 === void 0 ? void 0 : _props_refinePrompt1.enable) || ((_props_enlargeable2 = props.enlargeable) === null || _props_enlargeable2 === void 0 ? void 0 : _props_enlargeable2.enable) ? /*#__PURE__*/ React.createElement(QuickActions, {
        ref: quickActionsRef,
        value: value,
        fileMap: fileMap,
        onFileMapChange: setFileMap,
        isHover: isHover,
        isLoading: isLoading,
        disabled: props.disabled,
        fileUploadStatus: fileUploadDone ? 'done' : 'uploading',
        refinePrompt: props.refinePrompt,
        editorRef: markdownEditorRef,
        onValueChange: function(text) {
            var _props_onChange;
            setValue(text);
            (_props_onChange = props.onChange) === null || _props_onChange === void 0 ? void 0 : _props_onChange.call(props, text);
        },
        quickActionRender: props.quickActionRender,
        prefixCls: baseCls,
        hashId: hashId,
        enlargeable: !!((_props_enlargeable3 = props.enlargeable) === null || _props_enlargeable3 === void 0 ? void 0 : _props_enlargeable3.enable),
        isEnlarged: isEnlarged,
        onEnlargeClick: handleEnlargeClick,
        onResize: function(width, rightOffset) {
            setTopRightPadding(width);
            setQuickRightOffset(rightOffset);
        }
    }) : null))));
};
