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 { ConfigProvider } from "antd";
import classNames from "classnames";
import React, { useContext } from "react";
import { Editor, Path, Transforms } from "slate";
import { ReactEditor } from "slate-react";
import { I18nContext } from "../../../I18n";
import { debugInfo } from "../../../Utils/debugUtils";
import { useEditorStore } from "../store";
import { EditorUtils } from "../utils/editorUtils";
import { Blockquote } from "./Blockquote";
import { Break } from "./Break";
import { WarpCard } from "./Card";
import { Code } from "./Code";
import { CommentLeaf } from "./CommentLeaf";
import { FncLeaf } from "./FncLeaf";
import { FootnoteDefinition } from "./FootnoteDefinition";
import { FootnoteReference } from "./FootnoteReference";
import { Head } from "./Head";
import { Hr } from "./Hr";
import { EditorImage } from "./Image";
import { InlineKatex } from "./InlineKatex";
import { Katex } from "./Katex";
import { LinkCard } from "./LinkCard";
import { List, ListItem } from "./List";
import { Media } from "./Media";
import { Mermaid } from "./Mermaid";
import { Paragraph } from "./Paragraph";
import { Schema } from "./Schema";
import { tableRenderElement } from "./Table";
import { TagPopup } from "./TagPopup";
/**
 * 性能优化说明：
 *
 * 本文件中的 MElement 和 MLeaf 组件使用了 React.memo 进行性能优化：
 *
 * 1. **避免不必要的重新渲染**：使用自定义比较函数确保只有在 props 真正变化时才重新渲染
 * 2. **快速引用比较**：首先进行引用比较，这是最快的比较方式
 * 4. **批量属性检查**：对 MLeaf 组件使用数组批量检查关键属性
 *
 * 性能测试结果显示约 43% 的渲染性能提升，在相同 props 的情况下避免了重复渲染。
 */ export var dragStart = function(e) {
    e.preventDefault();
    e.stopPropagation();
};
/**
 * 比较两个字符串数组是否相等
 * @param prev - 前一个数组
 * @param next - 下一个数组
 * @returns 是否相等
 */ var areDepsEqual = function(prev, next) {
    if (prev === next) return true;
    if (!prev || !next) return prev === next;
    if (prev.length !== next.length) return false;
    return prev.every(function(val, index) {
        return val === next[index];
    });
};
/**
 * 比较函数，用于优化 MElement 组件的渲染性能
 * 比较 hash 和 deps 来判断是否需要重新渲染
 */ var areElementPropsEqual = function(prevProps, nextProps) {
    var _prevProps_element, _nextProps_element;
    // 比较 deps，如果 deps 发生变化，需要重新渲染
    if (!areDepsEqual(prevProps.deps, nextProps.deps)) {
        return false;
    }
    // 比较 hash
    var prevHash = (_prevProps_element = prevProps.element) === null || _prevProps_element === void 0 ? void 0 : _prevProps_element.hash;
    var nextHash = (_nextProps_element = nextProps.element) === null || _nextProps_element === void 0 ? void 0 : _nextProps_element.hash;
    // 如果都有 hash，只比较 hash
    if (prevHash && nextHash && nextProps.readonly && prevProps.readonly) {
        return prevHash === nextHash;
    }
    // 没有 hash 时，回退到引用比较
    return prevProps.element === nextProps.element;
};
var MElementComponent = function(props) {
    debugInfo('MElementComponent - 渲染元素', {
        elementType: props.element.type,
        readonly: props.readonly,
        hasChildren: !!props.children
    });
    var dom = tableRenderElement(props, {
        readonly: props.readonly
    });
    if (dom) {
        debugInfo('MElementComponent - 使用表格渲染', {
            elementType: props.element.type
        });
        return dom;
    }
    debugInfo('MElementComponent - 选择元素渲染器', {
        elementType: props.element.type
    });
    switch(props.element.type){
        case 'link-card':
            return /*#__PURE__*/ React.createElement(LinkCard, props);
        case 'blockquote':
            return /*#__PURE__*/ React.createElement(Blockquote, props);
        case 'head':
            return /*#__PURE__*/ React.createElement(Head, props);
        case 'hr':
            return /*#__PURE__*/ React.createElement(Hr, props);
        case 'break':
            return /*#__PURE__*/ React.createElement(Break, props);
        case 'katex':
            return /*#__PURE__*/ React.createElement(Katex, props);
        case 'inline-katex':
            return /*#__PURE__*/ React.createElement(InlineKatex, props);
        case 'mermaid':
            return /*#__PURE__*/ React.createElement(Mermaid, props);
        case 'code':
            return /*#__PURE__*/ React.createElement(Code, props);
        case 'list-item':
            return /*#__PURE__*/ React.createElement(ListItem, props);
        case 'list':
            return /*#__PURE__*/ React.createElement(List, props);
        case 'schema':
            return /*#__PURE__*/ React.createElement(Schema, props);
        case 'apassify':
            return /*#__PURE__*/ React.createElement(Schema, props);
        case 'apaasify':
            return /*#__PURE__*/ React.createElement(Schema, props);
        case 'image':
            return /*#__PURE__*/ React.createElement(EditorImage, props);
        case 'media':
            return /*#__PURE__*/ React.createElement(Media, props);
        case 'footnoteDefinition':
            return /*#__PURE__*/ React.createElement(FootnoteDefinition, props);
        case 'footnoteReference':
            return /*#__PURE__*/ React.createElement(FootnoteReference, props);
        case 'card':
            return /*#__PURE__*/ React.createElement(WarpCard, props);
        case 'card-before':
            return /*#__PURE__*/ React.createElement("span", _object_spread({
                style: {
                    minWidth: 4,
                    height: '100%',
                    position: 'relative',
                    lineHeight: 1,
                    zIndex: 99,
                    fontSize: '2em',
                    overflow: 'hidden',
                    display: props.readonly ? 'none' : 'inline-block'
                },
                "data-be": 'card-before'
            }, props.attributes), props.children);
        case 'card-after':
            return /*#__PURE__*/ React.createElement("span", _object_spread({
                style: {
                    minWidth: 4,
                    height: '100%',
                    position: 'relative',
                    lineHeight: 1,
                    zIndex: 99,
                    fontSize: '2em',
                    overflow: 'hidden',
                    display: props.readonly ? 'none' : 'inline-block'
                },
                "data-be": 'card-after'
            }, props.attributes), props.children);
        default:
            debugInfo('MElementComponent - 使用默认段落渲染', {
                elementType: props.element.type
            });
            return /*#__PURE__*/ React.createElement(Paragraph, props);
    }
};
// 使用 React.memo 优化 MElement 组件的性能
export var MElement = /*#__PURE__*/ React.memo(MElementComponent, areElementPropsEqual);
var MLeafComponent = function(props) {
    var _leaf_text;
    var _useEditorStore = useEditorStore(), markdownEditorRef = _useEditorStore.markdownEditorRef, markdownContainerRef = _useEditorStore.markdownContainerRef;
    var context = useContext(ConfigProvider.ConfigContext);
    var locale = useContext(I18nContext).locale;
    var mdEditorBaseClass = context === null || context === void 0 ? void 0 : context.getPrefixCls('agentic-md-editor-content');
    var leaf = props.leaf;
    debugInfo('MLeafComponent - 渲染叶节点', {
        hasCode: !!leaf.code,
        hasTag: !!leaf.tag,
        hasBold: !!leaf.bold,
        hasItalic: !!leaf.italic,
        hasStrikethrough: !!leaf.strikethrough,
        hasUrl: !!leaf.url,
        hasFnc: !!leaf.fnc,
        hasComment: !!leaf.comment,
        text: (_leaf_text = leaf.text) === null || _leaf_text === void 0 ? void 0 : _leaf_text.substring(0, 50)
    });
    var style = {};
    var prefixClassName = classNames(props.hashId);
    var children = /*#__PURE__*/ React.createElement(React.Fragment, null, props.children);
    if (leaf.code || leaf.tag) {
        var _ref = (props === null || props === void 0 ? void 0 : props.leaf) || {}, text = _ref.text, tag = _ref.tag, placeholder = _ref.placeholder, autoOpen = _ref.autoOpen, triggerText = _ref.triggerText;
        var _ref1 = props.tagInputProps || {}, enable = _ref1.enable, tagTextRender = _ref1.tagTextRender;
        debugInfo('MLeafComponent - 处理代码/标签', {
            code: leaf.code,
            tag: tag,
            enable: enable,
            hasTagTextRender: !!tagTextRender
        });
        if (enable && tag) {
            debugInfo('MLeafComponent - 使用 TagPopup', {
                text: text,
                placeholder: placeholder,
                autoOpen: autoOpen,
                triggerText: triggerText
            });
            children = /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(TagPopup, _object_spread_props(_object_spread(_object_spread_props(_object_spread({}, props), {
                autoOpen: autoOpen
            }), props.tagInputProps), {
                text: text,
                onSelect: function(v, path, tagNode) {
                    var _markdownContainerRef_current;
                    debugInfo('MLeafComponent - TagPopup onSelect', {
                        value: v,
                        path: path,
                        hasTagNode: !!tagNode
                    });
                    if (!v) return;
                    if (!(path === null || path === void 0 ? void 0 : path.length)) return;
                    if (!markdownEditorRef.current) return;
                    Editor.withoutNormalizing(markdownEditorRef.current, function() {
                        debugInfo('MLeafComponent - 更新标签节点', {
                            value: v,
                            path: path
                        });
                        var newText = (tagTextRender === null || tagTextRender === void 0 ? void 0 : tagTextRender(_object_spread_props(_object_spread({}, props, props.tagInputProps), {
                            text: v
                        }), "".concat(triggerText !== null && triggerText !== void 0 ? triggerText : '$').concat(v))) || "".concat(triggerText !== null && triggerText !== void 0 ? triggerText : '$').concat(v);
                        Transforms.insertText(markdownEditorRef.current, newText, {
                            at: path
                        });
                        Transforms.setNodes(markdownEditorRef.current, _object_spread({
                            text: newText,
                            tag: true,
                            code: true,
                            placeholder: placeholder
                        }, tagNode), {
                            at: path
                        });
                        Transforms.insertNodes(markdownEditorRef.current, [
                            {
                                text: '\uFEFF'
                            }
                        ], {
                            at: Path.previous(path)
                        });
                    });
                    var focusElement = (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.querySelector('div[data-slate-node="value"]');
                    if (focusElement) {
                        focusElement === null || focusElement === void 0 ? void 0 : focusElement.focus();
                    }
                    setTimeout(function() {
                        if (!markdownEditorRef.current) return;
                        if (!(path === null || path === void 0 ? void 0 : path.length)) return;
                        var nextPath = Path.next(path);
                        if (!Editor.hasPath(markdownEditorRef.current, nextPath)) {
                            Transforms.insertNodes(markdownEditorRef.current, [
                                {
                                    text: ' '
                                }
                            ], {
                                select: true
                            });
                        } else {
                            Transforms.select(markdownEditorRef.current, {
                                anchor: Editor.end(markdownEditorRef.current, path),
                                focus: Editor.end(markdownEditorRef.current, path)
                            });
                        }
                    }, 0);
                },
                placeholder: placeholder || (locale === null || locale === void 0 ? void 0 : locale['input.placeholder']) || '请输入'
            }), children));
        } else {
            debugInfo('MLeafComponent - 使用内联代码样式', {
                code: leaf.code,
                tag: leaf.tag
            });
            children = /*#__PURE__*/ React.createElement("code", {
                className: classNames(mdEditorBaseClass + '-inline-code', props.hashId)
            }, children);
        }
    }
    if (leaf.highColor) {
        style.color = leaf.highColor;
        debugInfo('MLeafComponent - 应用高亮颜色', {
            color: leaf.highColor
        });
    }
    if (leaf.color) {
        style.color = leaf.color;
        debugInfo('MLeafComponent - 应用颜色', {
            color: leaf.color
        });
    }
    if (leaf.bold) {
        style.fontWeight = 'bold';
        children = /*#__PURE__*/ React.createElement("span", {
            "data-testid": "markdown-bold"
        }, children);
        debugInfo('MLeafComponent - 应用粗体');
    }
    if (leaf.strikethrough) {
        children = /*#__PURE__*/ React.createElement("s", null, children);
        debugInfo('MLeafComponent - 应用删除线');
    }
    if (leaf.italic) {
        style.fontStyle = 'italic';
        debugInfo('MLeafComponent - 应用斜体');
    }
    if (leaf.html) {
        prefixClassName = classNames(prefixClassName, mdEditorBaseClass + '-m-html');
        debugInfo('MLeafComponent - 应用 HTML 样式');
    }
    if (leaf.current) {
        style.background = '#f59e0b';
        debugInfo('MLeafComponent - 应用当前高亮');
    }
    var selectFormat = function() {
        try {
            debugInfo('MLeafComponent - selectFormat 调用');
            if (EditorUtils.isDirtLeaf(props.leaf)) {
                var path = ReactEditor.findPath(markdownEditorRef.current, props.text);
                debugInfo('MLeafComponent - 选择格式路径', {
                    path: path
                });
                if (path) {
                    Transforms.select(markdownEditorRef.current, {
                        anchor: Editor.start(markdownEditorRef.current, path),
                        focus: Editor.end(markdownEditorRef.current, path)
                    });
                    debugInfo('MLeafComponent - 格式选择完成');
                }
            }
        } catch (e) {
            debugInfo('MLeafComponent - selectFormat 错误', {
                error: e
            });
        }
    };
    // 如果检测到 fnc、identifier 或 fnd，使用 FncLeaf 组件
    var hasFnc = leaf.fnc || leaf.identifier || leaf.fnd;
    var hasComment = !!leaf.comment;
    if (hasFnc) {
        debugInfo('MLeafComponent - 使用 FncLeaf 组件', {
            hasFnc: !!leaf.fnc,
            hasIdentifier: !!leaf.identifier,
            hasFnd: !!leaf.fnd
        });
        var baseClassName = classNames(prefixClassName === null || prefixClassName === void 0 ? void 0 : prefixClassName.trim(), props.hashId);
        var fncDom = /*#__PURE__*/ React.createElement(FncLeaf, _object_spread_props(_object_spread({}, props), {
            hashId: props.hashId,
            fncProps: props.fncProps,
            linkConfig: props.linkConfig,
            style: style,
            prefixClassName: baseClassName
        }));
        // 如果有评论，使用 CommentLeaf 包裹 fnc DOM
        if (hasComment) {
            return /*#__PURE__*/ React.createElement(CommentLeaf, {
                leaf: props.leaf,
                hashId: props.hashId,
                comment: props.comment
            }, fncDom);
        }
        return fncDom;
    }
    var baseClassName1 = classNames(prefixClassName === null || prefixClassName === void 0 ? void 0 : prefixClassName.trim(), props.hashId);
    var dom = /*#__PURE__*/ React.createElement("span", _object_spread_props(_object_spread({}, props.attributes), {
        "data-be": "text",
        draggable: false,
        onDragStart: dragStart,
        onClick: function(e) {
            var _props_linkConfig, _props_linkConfig1, _props_linkConfig2;
            debugInfo('MLeafComponent - onClick 事件', {
                detail: e.detail,
                hasUrl: !!leaf.url
            });
            if (e.detail === 2) {
                debugInfo('MLeafComponent - 双击选择格式');
                selectFormat();
            }
            if ((_props_linkConfig = props.linkConfig) === null || _props_linkConfig === void 0 ? void 0 : _props_linkConfig.onClick) {
                var _props_linkConfig3;
                var res = (_props_linkConfig3 = props.linkConfig) === null || _props_linkConfig3 === void 0 ? void 0 : _props_linkConfig3.onClick(leaf.url);
                debugInfo('MLeafComponent - 链接点击处理', {
                    result: res
                });
                if (res === false) {
                    return;
                }
            }
            if (leaf.url && ((_props_linkConfig1 = props.linkConfig) === null || _props_linkConfig1 === void 0 ? void 0 : _props_linkConfig1.openInNewTab) !== false) {
                debugInfo('MLeafComponent - 新标签页打开链接', {
                    url: leaf.url
                });
                window.open(leaf.url, '_blank');
            }
            if (leaf.url && ((_props_linkConfig2 = props.linkConfig) === null || _props_linkConfig2 === void 0 ? void 0 : _props_linkConfig2.openInNewTab) === false) {
                debugInfo('MLeafComponent - 当前窗口打开链接', {
                    url: leaf.url
                });
                window.location.href = leaf.url;
            }
        },
        "data-comment": leaf.comment ? 'comment' : undefined,
        "data-url": leaf.url ? 'url' : undefined,
        className: baseClassName1 ? baseClassName1 : undefined,
        style: style
    }), children);
    // 如果有评论，使用 CommentLeaf 包裹普通 DOM
    if (hasComment) {
        return /*#__PURE__*/ React.createElement(CommentLeaf, {
            leaf: props.leaf,
            hashId: props.hashId,
            comment: props.comment
        }, dom);
    }
    return dom;
};
// 使用 React.memo 优化 MLeaf 组件的性能
export var MLeaf = /*#__PURE__*/ React.memo(MLeafComponent);
export { Blockquote, Break, Code, Head, Hr, InlineKatex, Katex, List, ListItem, Media, Mermaid, Paragraph, Schema };
