/* eslint-disable @typescript-eslint/no-this-alias */ /* eslint-disable no-param-reassign */ 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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread 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 _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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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);
}
import isEqual from "lodash-es/isEqual";
import { parse } from "querystring";
import * as React from "react";
import { Editor, Element, Node, Path, Range, Text, Transforms } from "slate";
import { ReactEditor } from "slate-react";
import { parserMdToSchema } from "./parser/parserMdToSchema";
import { parserSlateNodeToMarkdown } from "./utils";
import { getOffsetLeft, getOffsetTop } from "./utils/dom";
import { EditorUtils, findByPathAndText } from "./utils/editorUtils";
import { markdownToHtmlSync } from "./utils/markdownToHtml";
var createContext = React.createContext, useContext = React.useContext;
export var EditorStoreContext = createContext(null);
/**
 * 获取编辑器存储上下文的Hook
 *
 * 提供安全的上下文访问，包含默认值处理
 *
 * @returns 编辑器存储上下文对象
 *
 * @example
 * ```tsx
 * const { store, readonly, typewriter } = useEditorStore();
 * ```
 */ export var useEditorStore = function() {
    return useContext(EditorStoreContext) || {
        store: {},
        readonly: true,
        typewriter: false,
        editorProps: {},
        markdownEditorRef: {}
    };
};
/** 支持键入操作的标签类型列表 */ var SUPPORT_TYPING_TAG = [
    'table-cell',
    'paragraph',
    'head'
];
/**
 * 编辑器核心状态管理类
 *
 * 负责管理编辑器的所有状态、操作和事件处理
 * 包括文档结构、选择状态、高亮、拖拽、历史记录等
 *
 * @class
 */ export var EditorStore = /*#__PURE__*/ function() {
    "use strict";
    function EditorStore(_editor, plugins, markdownToHtmlOptions) {
        var _this = this;
        _class_call_check(this, EditorStore);
        /** 高亮缓存映射表 */ _define_property(this, "highlightCache", new Map());
        /** 允许进入的元素类型集合 */ _define_property(this, "ableToEnter", new Set([
            'paragraph',
            'head',
            'blockquote',
            'code',
            'table',
            'list',
            'media',
            'attach'
        ]));
        /** 当前拖拽的元素 */ _define_property(this, "draggedElement", null);
        _define_property(this, "footnoteDefinitionMap", new Map());
        _define_property(this, "inputComposition", false);
        _define_property(this, "plugins", void 0);
        _define_property(this, "domRect", null);
        _define_property(this, "_editor", void 0);
        /** 当前 setMDContent 操作的 AbortController */ _define_property(this, "_currentAbortController", null);
        _define_property(this, "markdownToHtmlOptions", void 0);
        /**
   * 移除节点
   * @param options
   */ _define_property(this, "removeNodes", function(options) {
            Transforms.removeNodes(_this._editor.current, options);
        });
        this.dragStart = this.dragStart.bind(this);
        this._editor = _editor;
        this.plugins = plugins;
        this.markdownToHtmlOptions = markdownToHtmlOptions;
    }
    _create_class(EditorStore, [
        {
            key: "editor",
            get: /**
   * 获取当前编辑器实例。
   *
   * @returns 当前的 Slate 编辑器实例。
   */ function get() {
                return this._editor.current;
            }
        },
        {
            /**
   * 聚焦到编辑器
   */ key: "focus",
            value: function focus() {
                var editor = this._editor.current;
                try {
                    // 1. 确保编辑器获得焦点
                    setTimeout(function() {
                        return ReactEditor.focus(editor);
                    }, 0);
                    // 2. 处理空文档情况
                    if (editor.children.length === 0) {
                        var defaultNode = {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        };
                        Transforms.insertNodes(editor, defaultNode, {
                            at: [
                                0
                            ]
                        });
                    }
                    // 3. 获取文档末尾位置
                    var end = Editor.end(editor, []);
                    // 4. 设置光标位置
                    Transforms.select(editor, {
                        anchor: end,
                        focus: end
                    });
                } catch (error) {
                    console.error('移动光标失败:', error);
                }
            }
        },
        {
            key: "findLatest",
            value: /**
   * 查找最新的节点索引。
   *
   * @param node - 当前节点。
   * @param index - 当前索引路径。
   * @returns 最新节点的索引路径。
   */ function findLatest(node, index) {
                if (Array.isArray(node.children)) {
                    if (node.children.length === 1 && (SUPPORT_TYPING_TAG.includes(node.type) || !node.children[0].type)) {
                        return index;
                    }
                    return this.findLatest(node.children[node.children.length - 1], _to_consumable_array(index).concat([
                        node.children.length - 1
                    ]));
                }
                return index;
            }
        },
        {
            /**
   * 检查给定节点是否是最新节点。用于展示 闪动光标
   *
   * @param node - 要检查的节点。
   * @returns 如果节点是最新节点，则返回 true；否则返回 false。
   */ key: "isLatestNode",
            value: function isLatestNode(node) {
                try {
                    return this.findLatest(this._editor.current.children.at(-1), [
                        this._editor.current.children.length - 1
                    ]).join('-').startsWith(ReactEditor.findPath(this._editor.current, node).join('-'));
                } catch (error) {
                    return false;
                }
            }
        },
        {
            /**
   * 插入一个链接到编辑器中。
   *
   * @param filePath - 要插入的文件路径。如果路径以 'http' 开头，则链接文本为路径本身，否则为文件名。
   *
   * 该方法首先解析文件路径，并创建一个包含文本和 URL 的节点对象。
   * 然后，它检查当前编辑器的选区是否存在且未折叠。如果选区不存在或已折叠，则方法返回。
   *
   * 接下来，它查找当前选区所在的最低层级的元素节点。如果节点类型是 'table-cell' 或 'paragraph'，
   * 则在当前选区插入链接节点并选中它。
   *
   * 如果当前选区所在的元素节点类型不是 'table-cell' 或 'paragraph'，则查找包含当前选区的父级元素节点，
   * 并在其后插入一个包含链接节点的新段落。
   */ key: "insertLink",
            value: function insertLink(filePath) {
                var p = parse(filePath);
                var insertPath = filePath;
                var node = {
                    text: filePath.startsWith('http') ? filePath : p.name,
                    url: insertPath
                };
                var sel = this._editor.current.selection;
                if (!sel || !Range.isCollapsed(sel)) return;
                // @ts-ignore
                var _Editor_nodes = _sliced_to_array(Editor.nodes(this._editor.current, {
                    match: function(n) {
                        return Element.isElement(n);
                    },
                    mode: 'lowest'
                }), 1), cur = _Editor_nodes[0];
                if (node.text && [
                    'table-cell',
                    'paragraph'
                ].includes(cur[0].type)) {
                    Transforms.insertNodes(this._editor.current, node, {
                        select: true
                    });
                } else {
                    // @ts-ignore
                    var _Editor_nodes1 = _sliced_to_array(Editor.nodes(this._editor.current, {
                        match: function(n) {
                            return Element.isElement(n) && [
                                'table',
                                'code',
                                'head'
                            ].includes(n.type);
                        }
                    }), 1), par = _Editor_nodes1[0];
                    Transforms.insertNodes(this._editor.current, {
                        type: 'paragraph',
                        children: [
                            node
                        ]
                    }, {
                        select: true,
                        at: Path.next(par[1])
                    });
                }
            }
        },
        {
            /**
   * 插入节点到编辑器中。
   *
   * @param nodes - 要插入的节点，可以是单个节点或节点数组。
   * @param options - 可选参数，用于指定插入节点的选项。
   */ key: "insertNodes",
            value: function insertNodes(nodes, options) {
                Transforms.insertNodes(this._editor.current, nodes, options);
            }
        },
        {
            key: "toPath",
            value: /**
   * Converts an HTML element to a Slate path and node.
   *
   * @param el - The HTML element to convert.
   * @returns A tuple containing the path and the corresponding Slate node.
   * @private
   */ function toPath(el) {
                var node = ReactEditor.toSlateNode(this._editor.current, el);
                var path = ReactEditor.findPath(this._editor.current, node);
                return [
                    path,
                    node
                ];
            }
        },
        {
            /**
   * Clears all content from the editor, replacing it with an empty paragraph.
   */ key: "clearContent",
            value: function clearContent() {
                this._editor.current.selection = null;
                this._editor.current.children = [
                    {
                        type: 'paragraph',
                        children: [
                            {
                                text: ''
                            }
                        ]
                    }
                ];
            }
        },
        {
            /**
   * 从 markdown 文本设置编辑器内容
   *
   * @param md - 要设置为编辑器内容的 Markdown 字符串
   *             如果为 undefined，方法将直接返回不做任何更改
   *             如果 markdown 与当前内容相同，则不做任何更改
   * @param plugins - 可选的自定义 markdown 解析插件
   * @param options - 可选的配置参数
   *   - chunkSize: 分块大小阈值，默认 5000 字符。超过此大小会启用分批处理
   *   - separator: 分隔符，默认为双换行符 '\n\n'，用于拆分长文本
   *   - useRAF: 是否使用 requestAnimationFrame 优化，默认 true，避免长文本处理时卡顿
   *   - batchSize: 每帧处理的节点数量，默认 50，仅在 useRAF=true 时生效
   *   - onProgress: 进度回调函数，接收当前进度 (0-1) 作为参数
   * @returns 如果使用 RAF，返回 Promise；否则同步执行
   */ key: "setMDContent",
            value: function setMDContent(md, plugins, options) {
                if (md === undefined) return;
                // 安全地比较当前内容，避免解析异常导致失效
                try {
                    var currentMD = parserSlateNodeToMarkdown(this._editor.current.children);
                    // 使用 trim 和规范化比较，避免空白字符差异
                    if (md.trim() === currentMD.trim()) return;
                } catch (error) {
                    // 如果解析当前内容失败，继续执行设置新内容
                    console.warn('Failed to compare current content, proceeding with setMDContent:', error);
                }
                // 取消之前的操作，避免竞态条件
                this.cancelSetMDContent();
                var _options_chunkSize;
                var chunkSize = (_options_chunkSize = options === null || options === void 0 ? void 0 : options.chunkSize) !== null && _options_chunkSize !== void 0 ? _options_chunkSize : 5000;
                var _options_separator;
                var separator = (_options_separator = options === null || options === void 0 ? void 0 : options.separator) !== null && _options_separator !== void 0 ? _options_separator : /\n\n/;
                var _options_useRAF;
                var useRAF = (_options_useRAF = options === null || options === void 0 ? void 0 : options.useRAF) !== null && _options_useRAF !== void 0 ? _options_useRAF : true;
                var _options_batchSize;
                var batchSize = (_options_batchSize = options === null || options === void 0 ? void 0 : options.batchSize) !== null && _options_batchSize !== void 0 ? _options_batchSize : 50;
                var targetPlugins = plugins || this.plugins;
                // 如果内容较短，直接处理
                if (md.length <= chunkSize) {
                    try {
                        var nodeList = parserMdToSchema(md, targetPlugins).schema;
                        this.setContent(nodeList);
                        this._editor.current.children = nodeList;
                        ReactEditor.deselect(this._editor.current);
                        // 调用进度回调
                        if (options === null || options === void 0 ? void 0 : options.onProgress) {
                            options.onProgress(1);
                        }
                    } catch (error) {
                        console.error('Failed to set MD content:', error);
                        throw error;
                    }
                    return;
                }
                // 内容较长时，按指定分隔符拆分并分批处理
                var chunks = this._splitMarkdown(md, separator);
                // 如果禁用 RAF，使用同步模式处理长内容
                if (!useRAF) {
                    try {
                        var allNodes = [];
                        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                        try {
                            for(var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                                var chunk = _step.value;
                                if (chunk.trim()) {
                                    var _allNodes;
                                    var schema = parserMdToSchema(chunk, targetPlugins).schema;
                                    (_allNodes = allNodes).push.apply(_allNodes, _to_consumable_array(schema));
                                }
                            }
                        } catch (err) {
                            _didIteratorError = true;
                            _iteratorError = err;
                        } finally{
                            try {
                                if (!_iteratorNormalCompletion && _iterator.return != null) {
                                    _iterator.return();
                                }
                            } finally{
                                if (_didIteratorError) {
                                    throw _iteratorError;
                                }
                            }
                        }
                        if (allNodes.length > 0) {
                            this.setContent(allNodes);
                            this._editor.current.children = allNodes;
                            ReactEditor.deselect(this._editor.current);
                        }
                        // 调用进度回调
                        if (options === null || options === void 0 ? void 0 : options.onProgress) {
                            options.onProgress(1);
                        }
                    } catch (error) {
                        console.error('Failed to set MD content synchronously:', error);
                        throw error;
                    }
                    return;
                }
                // 如果使用 RAF 且分块数量较多，异步解析和插入
                if (chunks.length > 10) {
                    // 创建新的 AbortController
                    this._currentAbortController = new AbortController();
                    return this._parseAndSetContentWithRAF(chunks, targetPlugins || [], batchSize, options === null || options === void 0 ? void 0 : options.onProgress, this._currentAbortController.signal);
                }
                // 如果分块数量 <= 10，使用同步模式处理（修复：之前这里直接返回 undefined）
                try {
                    var allNodes1 = [];
                    var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
                    try {
                        for(var _iterator1 = chunks[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
                            var chunk1 = _step1.value;
                            if (chunk1.trim()) {
                                var _allNodes1;
                                var schema1 = parserMdToSchema(chunk1, targetPlugins).schema;
                                (_allNodes1 = allNodes1).push.apply(_allNodes1, _to_consumable_array(schema1));
                            }
                        }
                    } catch (err) {
                        _didIteratorError1 = true;
                        _iteratorError1 = err;
                    } finally{
                        try {
                            if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
                                _iterator1.return();
                            }
                        } finally{
                            if (_didIteratorError1) {
                                throw _iteratorError1;
                            }
                        }
                    }
                    if (allNodes1.length > 0) {
                        this.setContent(allNodes1);
                        this._editor.current.children = allNodes1;
                        ReactEditor.deselect(this._editor.current);
                    }
                    // 调用进度回调
                    if (options === null || options === void 0 ? void 0 : options.onProgress) {
                        options.onProgress(1);
                    }
                } catch (error) {
                    console.error('Failed to set MD content with small chunks:', error);
                    throw error;
                }
            }
        },
        {
            /**
   * 取消当前正在进行的 setMDContent 操作
   */ key: "cancelSetMDContent",
            value: function cancelSetMDContent() {
                if (this._currentAbortController) {
                    this._currentAbortController.abort();
                    this._currentAbortController = null;
                }
            }
        },
        {
            key: "_parseAndSetContentWithRAF",
            value: /**
   * 使用 requestAnimationFrame 分批解析和设置内容
   * 边解析边插入，实时显示内容
   *
   * @param chunks - markdown 分块数组
   * @param plugins - 解析插件
   * @param batchSize - 每帧处理的数量
   * @param onProgress - 进度回调函数
   * @returns Promise，在所有内容处理完成后 resolve
   * @private
   */ function _parseAndSetContentWithRAF(chunks, plugins, batchSize, onProgress, signal) {
                var _this = this;
                return new Promise(function(resolve, reject) {
                    var currentChunkIndex = 0;
                    var totalChunks = chunks.length;
                    var parseChunksPerFrame = Math.max(1, Math.floor(batchSize / 10)); // 每帧解析的 chunk 数
                    var isFirstBatch = true;
                    var rafId = null;
                    // 边解析边插入
                    var parseAndInsertNextBatch = function() {
                        try {
                            // 检查是否被取消
                            if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
                                if (rafId) {
                                    cancelAnimationFrame(rafId);
                                    rafId = null;
                                }
                                _this._currentAbortController = null;
                                reject(new Error('Operation was cancelled'));
                                return;
                            }
                            // 检查编辑器是否仍然有效
                            if (!_this._editor.current) {
                                if (rafId) {
                                    cancelAnimationFrame(rafId);
                                    rafId = null;
                                }
                                _this._currentAbortController = null;
                                reject(new Error('Editor instance is no longer available'));
                                return;
                            }
                            var endIndex = Math.min(currentChunkIndex + parseChunksPerFrame, totalChunks);
                            // 解析当前批次的 chunks 并立即插入
                            for(var i = currentChunkIndex; i < endIndex; i++){
                                var chunk = chunks[i];
                                if (chunk.trim()) {
                                    try {
                                        var schema = parserMdToSchema(chunk, plugins).schema;
                                        if (schema.length > 0) {
                                            if (isFirstBatch) {
                                                // 第一批：清空并插入
                                                _this._editor.current.children = schema;
                                                _this._editor.current.onChange();
                                                isFirstBatch = false;
                                            } else {
                                                // 后续批次：追加节点
                                                Transforms.insertNodes(_this._editor.current, schema, {
                                                    at: [
                                                        _this._editor.current.children.length
                                                    ]
                                                });
                                            }
                                        }
                                    } catch (chunkError) {
                                        // 单个 chunk 解析失败，记录但继续处理其他 chunks
                                        console.warn("Failed to parse chunk ".concat(i, ":"), chunkError);
                                    }
                                }
                            }
                            currentChunkIndex = endIndex;
                            // 更新进度
                            var progress = currentChunkIndex / totalChunks;
                            if (onProgress) {
                                try {
                                    onProgress(progress);
                                } catch (progressError) {
                                    // 进度回调失败不应该中断整个流程
                                    console.warn('Progress callback failed:', progressError);
                                }
                            }
                            if (currentChunkIndex < totalChunks) {
                                // 还有 chunks 未处理，继续下一帧
                                rafId = requestAnimationFrame(parseAndInsertNextBatch);
                            } else {
                                // 所有内容处理完成
                                ReactEditor.deselect(_this._editor.current);
                                rafId = null;
                                _this._currentAbortController = null;
                                resolve();
                            }
                        } catch (error) {
                            // 清理资源并拒绝 Promise
                            if (rafId) {
                                cancelAnimationFrame(rafId);
                                rafId = null;
                            }
                            _this._currentAbortController = null;
                            reject(error);
                        }
                    };
                    // 开始处理
                    rafId = requestAnimationFrame(parseAndInsertNextBatch);
                });
            }
        },
        {
            key: "_setContentWithRAF",
            value: /**
   * 使用 requestAnimationFrame 分批设置内容
   * 每帧插入一批节点，避免长时间阻塞主线程
   *
   * @param allNodes - 所有要插入的节点
   * @param batchSize - 每帧处理的节点数量
   * @param onProgress - 进度回调函数
   * @returns Promise，在所有节点插入完成后 resolve
   * @private
   */ function _setContentWithRAF(allNodes, batchSize, onProgress) {
                var _this = this;
                return new Promise(function(resolve, reject) {
                    var currentIndex = 0;
                    var totalNodes = allNodes.length;
                    var rafId = null;
                    var insertBatch = function() {
                        try {
                            var endIndex = Math.min(currentIndex + batchSize, totalNodes);
                            var batch = allNodes.slice(currentIndex, endIndex);
                            if (currentIndex === 0) {
                                // 第一批：清空并插入
                                _this._editor.current.children = batch;
                                _this._editor.current.onChange();
                            } else {
                                var // 后续批次：追加节点
                                _this__editor_current_children;
                                (_this__editor_current_children = _this._editor.current.children).push.apply(_this__editor_current_children, _to_consumable_array(batch));
                                _this._editor.current.onChange();
                            }
                            currentIndex = endIndex;
                            var progress = currentIndex / totalNodes;
                            // 直接调用进度回调，避免嵌套 requestAnimationFrame
                            onProgress === null || onProgress === void 0 ? void 0 : onProgress(progress);
                            if (currentIndex < totalNodes) {
                                // 还有节点未处理，继续下一帧
                                rafId = requestAnimationFrame(insertBatch);
                            } else {
                                // 所有节点处理完成
                                ReactEditor.deselect(_this._editor.current);
                                rafId = null;
                                resolve();
                            }
                        } catch (error) {
                            // 清理资源并拒绝 Promise
                            if (rafId) {
                                cancelAnimationFrame(rafId);
                                rafId = null;
                            }
                            reject(error);
                        }
                    };
                    // 开始第一帧
                    rafId = requestAnimationFrame(insertBatch);
                });
            }
        },
        {
            key: "_splitMarkdown",
            value: /**
   * 按指定分隔符拆分 markdown 内容
   * 保持内容结构的完整性
   *
   * @param md - 要拆分的 markdown 字符串
   * @param separator - 分隔符，可以是字符串或正则表达式
   * @returns 拆分后的字符串数组
   * @private
   */ function _splitMarkdown(md, separator) {
                if (!md) {
                    return [];
                }
                var separatorMatches = this._collectSeparatorMatches(md, separator);
                if (separatorMatches.length === 0) {
                    return [
                        md
                    ];
                }
                var chunks = [];
                var start = 0;
                var currentMatchIndex = 0;
                var insideFence = false;
                var activeFence = null;
                var index = 0;
                while(index < md.length){
                    if (this._isLineStart(md, index)) {
                        var fence = this._matchFence(md, index);
                        if (fence) {
                            if (!insideFence) {
                                insideFence = true;
                                activeFence = fence.marker;
                            } else if (activeFence === fence.marker) {
                                insideFence = false;
                                activeFence = null;
                            }
                            index = fence.end;
                            continue;
                        }
                    }
                    var match = separatorMatches[currentMatchIndex];
                    if (!insideFence && match && index === match.index) {
                        var chunk = md.slice(start, index);
                        if (chunk.length > 0) {
                            chunks.push(chunk);
                        }
                        start = index + match.length;
                        currentMatchIndex += 1;
                        index = start;
                        continue;
                    }
                    index += 1;
                }
                var tail = md.slice(start);
                if (tail.length > 0) {
                    chunks.push(tail);
                }
                return chunks.length > 0 ? chunks : [
                    md
                ];
            }
        },
        {
            key: "_collectSeparatorMatches",
            value: function _collectSeparatorMatches(md, separator) {
                if (typeof separator === 'string') {
                    var matches = [];
                    var searchIndex = md.indexOf(separator);
                    while(searchIndex !== -1){
                        matches.push({
                            index: searchIndex,
                            length: separator.length
                        });
                        searchIndex = md.indexOf(separator, searchIndex + separator.length);
                    }
                    return matches;
                }
                var flags = separator.flags.includes('g') ? separator.flags : "".concat(separator.flags, "g");
                var globalRegex = new RegExp(separator.source, flags);
                var matches1 = [];
                var match;
                while((match = globalRegex.exec(md)) !== null){
                    var matchedText = match[0];
                    matches1.push({
                        index: match.index,
                        length: matchedText.length
                    });
                    if (matchedText.length === 0) {
                        globalRegex.lastIndex += 1;
                    }
                }
                return matches1;
            }
        },
        {
            key: "_isLineStart",
            value: function _isLineStart(content, position) {
                if (position === 0) {
                    return true;
                }
                return content[position - 1] === '\n';
            }
        },
        {
            key: "_matchFence",
            value: function _matchFence(content, position) {
                var cursor = position;
                var spaces = 0;
                while(cursor < content.length && content[cursor] === ' ' && spaces < 3){
                    cursor += 1;
                    spaces += 1;
                }
                if (cursor >= content.length) {
                    return null;
                }
                var char = content[cursor];
                if (char !== '`' && char !== '~') {
                    return null;
                }
                var fenceLength = 0;
                while(cursor < content.length && content[cursor] === char){
                    cursor += 1;
                    fenceLength += 1;
                }
                if (fenceLength < 3) {
                    return null;
                }
                var lineEnd = this._findLineEnd(content, cursor);
                return {
                    marker: char,
                    end: lineEnd
                };
            }
        },
        {
            key: "_findLineEnd",
            value: function _findLineEnd(content, position) {
                var cursor = position;
                while(cursor < content.length && content[cursor] !== '\n'){
                    cursor += 1;
                }
                if (cursor < content.length && content[cursor] === '\n') {
                    return cursor + 1;
                }
                return cursor;
            }
        },
        {
            /**
   * 获取当前编辑器内容作为节点列表
   *
   * @returns 当前编辑器内容的节点列表
   */ key: "getContent",
            value: function getContent() {
                var nodeList = this._editor.current.children;
                return nodeList;
            }
        },
        {
            /**
   * 获取当前编辑器内容作为 markdown 字符串
   *
   * @param plugins - 可选的自定义 markdown 转换插件
   * @returns 转换为 markdown 的当前编辑器内容
   */ key: "getMDContent",
            value: function getMDContent(plugins) {
                var nodeList = this._editor.current.children;
                var md = parserSlateNodeToMarkdown(nodeList, '', [
                    {
                        root: true
                    }
                ], plugins || this.plugins);
                return md;
            }
        },
        {
            /**
   * 获取当前编辑器内容作为 HTML 字符串
   *
   * @returns 转换为 HTML 的当前编辑器内容
   */ key: "getHtmlContent",
            value: function getHtmlContent(options) {
                var markdown = this.getMDContent();
                var appliedOptions = options !== null && options !== void 0 ? options : this.markdownToHtmlOptions;
                if (options) {
                    this.markdownToHtmlOptions = options;
                }
                return markdownToHtmlSync(markdown, appliedOptions);
            }
        },
        {
            /**
   * 使用节点列表设置编辑器内容
   *
   * @param nodeList - 要设置为编辑器内容的节点列表
   */ key: "setContent",
            value: function setContent(nodeList) {
                this._editor.current.children = nodeList;
                this._editor.current.onChange();
                // 检查最后一个节点是否以换行符结尾
                var lastNode = nodeList[nodeList.length - 1];
                if (lastNode && Text.isText(lastNode)) {
                    var text = Node.string(lastNode);
                    if (!text.endsWith('\n')) {
                        this._editor.current.insertText('\n', {
                            at: [
                                nodeList.length - 1
                            ]
                        });
                    }
                }
            }
        },
        {
            /**
   * 使用差异检测和操作队列优化更新节点列表。
   *
   * @param nodeList - 新的节点列表
   *
   * 优化步骤：
   * 1. 过滤无效节点
   * 2. 生成差异操作
   * 3. 执行优化后的操作
   * 4. 处理可能的错误情况
   *
   * 过滤规则：
   * - 移除空的段落节点
   * - 移除空的列表节点
   * - 移除空的列表项节点
   * - 移除无效的代码块节点
   * - 移除无源的图片节点
   *
   * 错误处理：
   * - 如果优化更新失败，会回退到直接替换整个节点列表
   * - 错误信息会被记录到控制台
   */ key: "updateNodeList",
            value: function updateNodeList(nodeList) {
                if (!nodeList || !Array.isArray(nodeList)) return;
                // 过滤无效节点
                var filteredNodes = nodeList.filter(function(item) {
                    if (!item) return false;
                    if (item.type === 'p' && (!item.children || item.children.length === 0)) return false;
                    if (item.type === 'list' && (!item.children || item.children.length === 0)) return false;
                    if (item.type === 'listItem' && (!item.children || item.children.length === 0)) return false;
                    if (item.type === 'code' && item.language === 'code' && (!item.otherProps || item.otherProps.length === 0)) return false;
                    if (item.type === 'image' && !item.src) return false;
                    return true;
                });
                try {
                    // 生成差异操作
                    var operations = this.generateDiffOperations(filteredNodes, this._editor.current.children);
                    // 执行差异操作
                    if (operations.length > 0) {
                        this.executeOperations(operations);
                    }
                } catch (error) {
                    console.error('Failed to update nodes with optimized method:', error);
                    // 回退：如果优化方法失败，使用直接替换
                    this._editor.current.children = nodeList;
                }
            }
        },
        {
            key: "generateDiffOperations",
            value: /**
   * 生成两个节点列表之间的差异操作队列。
   *
   * @param newNodes - 新的节点列表
   * @param oldNodes - 旧的节点列表
   * @returns 包含所有需要执行的操作的队列
   *
   * 该方法通过以下步骤生成差异：
   * 1. 处理节点数量不同的情况
   * 2. 对共有节点进行深度比较
   * 3. 生成最小化的操作序列
   * 4. 根据优先级排序操作
   */ function generateDiffOperations(newNodes, oldNodes) {
                if (!newNodes || !oldNodes) return [];
                var operations = [];
                // 第一阶段：处理节点数量不同的情况
                var lengthDiff = newNodes.length - oldNodes.length;
                if (lengthDiff > 0) {
                    // 新列表比旧列表长，添加新节点
                    for(var i = oldNodes.length; i < newNodes.length; i++){
                        operations.push({
                            type: 'insert',
                            path: [
                                i
                            ],
                            node: newNodes[i],
                            priority: 10
                        });
                    }
                } else if (lengthDiff < 0) {
                    // 旧列表比新列表长，需要删除节点
                    // 从后往前删除，以避免索引问题
                    for(var i1 = oldNodes.length - 1; i1 >= newNodes.length; i1--){
                        operations.push({
                            type: 'remove',
                            path: [
                                i1
                            ],
                            priority: 0
                        });
                    }
                }
                // 第二阶段：深度比较共有的节点
                var minLength = Math.min(newNodes.length, oldNodes.length);
                for(var i2 = 0; i2 < minLength; i2++){
                    var newNode = newNodes[i2];
                    var oldNode = oldNodes[i2];
                    this.compareNodes(newNode, oldNode, [
                        i2
                    ], operations);
                }
                // 按优先级排序操作队列
                return operations.sort(function(a, b) {
                    return a.priority - b.priority;
                });
            }
        },
        {
            key: "compareNodes",
            value: /**
   * 递归比较两个节点及其子节点的差异。
   *
   * @param newNode - 新节点
   * @param oldNode - 旧节点
   * @param path - 当前节点的路径
   * @param operations - 操作队列，用于存储发现的差异操作
   *
   * 比较过程包括：
   * 1. 检查节点类型是否相同
   * 2. 特殊处理表格节点
   * 3. 比较文本节点内容
   * 4. 比较节点属性
   * 5. 递归比较子节点
   * @private
   */ function compareNodes(newNode, oldNode, path, operations) {
                // 如果节点类型不同，直接替换整个节点
                if (newNode.type !== oldNode.type) {
                    operations.push({
                        type: 'replace',
                        path: path,
                        node: newNode,
                        priority: 5
                    });
                    return;
                }
                // 特殊处理表格节点
                if (newNode.type === 'table') {
                    this.compareTableNodes(newNode, oldNode, path, operations);
                    return;
                }
                // 如果两个节点是文本节点
                if (typeof newNode.text === 'string' && typeof oldNode.text === 'string') {
                    if (newNode.text !== oldNode.text) {
                        operations.push({
                            type: 'text',
                            path: path,
                            text: newNode.text,
                            priority: 8
                        });
                    }
                    // 比较文本节点的其他属性（如加粗、斜体等）
                    var newProps = _object_spread({}, newNode);
                    var oldProps = _object_spread({}, oldNode);
                    delete newProps.text;
                    delete oldProps.text;
                    if (!isEqual(newProps, oldProps)) {
                        operations.push({
                            type: 'update',
                            path: path,
                            properties: newProps,
                            priority: 7
                        });
                    }
                    return;
                }
                // 处理其他类型的节点属性更新
                var newProps1 = _object_spread_props(_object_spread({}, newNode), {
                    children: undefined
                });
                var oldProps1 = _object_spread_props(_object_spread({}, oldNode), {
                    children: undefined
                });
                if (!isEqual(newProps1, oldProps1)) {
                    operations.push({
                        type: 'update',
                        path: path,
                        properties: newProps1,
                        priority: 7
                    });
                }
                // 递归比较子节点
                if (newNode.children && oldNode.children) {
                    // 特殊处理列表、引用等可能有嵌套结构的节点
                    var childrenOps = this.generateDiffOperations(newNode.children, oldNode.children);
                    // 将子节点的操作添加到队列中，调整路径
                    childrenOps.forEach(function(op) {
                        operations.push(_object_spread_props(_object_spread({}, op), {
                            path: _to_consumable_array(path).concat(_to_consumable_array(op.path))
                        }));
                    });
                }
            }
        },
        {
            key: "compareTableNodes",
            value: /**
   * 特殊处理表格节点的比较。
   *
   * @param newTable - 新的表格节点
   * @param oldTable - 旧的表格节点
   * @param path - 表格节点的路径
   * @param operations - 操作队列
   *
   * 处理步骤：
   * 1. 检查表格结构是否相同
   * 2. 比较表格属性
   * 3. 逐行比较和更新
   * 4. 处理行数变化
   * 5. 必要时进行整表替换
   * @private
   */ function compareTableNodes(newTable, oldTable, path, operations) {
                var newRows = newTable.children || [];
                var oldRows = oldTable.children || [];
                // 检查是否是同一个表格的更新（检查表格的关键属性）
                var isSameTableStructure = function() {
                    // 如果有表格ID或其他唯一标识符，优先比较这些
                    if (newTable.id && oldTable.id) {
                        return newTable.id === oldTable.id;
                    }
                    // 表格结构基本一致的情况（行数相同）
                    if (newRows.length === oldRows.length) {
                        // 检查每行的单元格数量
                        for(var i = 0; i < newRows.length; i++){
                            var newRow = newRows[i];
                            var oldRow = oldRows[i];
                            if (!newRow.children || !oldRow.children || newRow.children.length !== oldRow.children.length) {
                                return false;
                            }
                        }
                        return true;
                    }
                    return false;
                };
                // 非结构化属性对比（排除children）
                var tablePropsChanged = function() {
                    var newProps = _object_spread({}, newTable);
                    var oldProps = _object_spread({}, oldTable);
                    delete newProps.children;
                    delete oldProps.children;
                    return !isEqual(newProps, oldProps);
                };
                // 检查表格是否只有内容变化而结构相同
                if (isSameTableStructure()) {
                    // 只更新表格属性（不包括子节点）
                    if (tablePropsChanged()) {
                        var newTableProps = _object_spread_props(_object_spread({}, newTable), {
                            children: undefined
                        });
                        operations.push({
                            type: 'update',
                            path: path,
                            properties: newTableProps,
                            priority: 7
                        });
                    }
                    // 逐行比较和更新
                    for(var rowIdx = 0; rowIdx < newRows.length; rowIdx++){
                        var rowPath = _to_consumable_array(path).concat([
                            rowIdx
                        ]);
                        var newRow = newRows[rowIdx];
                        var oldRow = oldRows[rowIdx];
                        // 更新行属性（不包括子节点）
                        var newRowProps = _object_spread_props(_object_spread({}, newRow), {
                            children: undefined
                        });
                        var oldRowProps = _object_spread_props(_object_spread({}, oldRow), {
                            children: undefined
                        });
                        if (!isEqual(newRowProps, oldRowProps)) {
                            operations.push({
                                type: 'update',
                                path: rowPath,
                                properties: newRowProps,
                                priority: 7
                            });
                        }
                        // 单元格比较和更新
                        var newCells = newRow.children || [];
                        var oldCells = oldRow.children || [];
                        var minCellCount = Math.min(newCells.length, oldCells.length);
                        // 更新共有的单元格
                        for(var cellIdx = 0; cellIdx < minCellCount; cellIdx++){
                            var cellPath = _to_consumable_array(rowPath).concat([
                                cellIdx
                            ]);
                            var newCell = newCells[cellIdx];
                            var oldCell = oldCells[cellIdx];
                            this.compareCells(newCell, oldCell, cellPath, operations);
                        }
                        // 处理单元格数量变化
                        if (newCells.length > oldCells.length) {
                            // 添加新单元格
                            for(var cellIdx1 = oldCells.length; cellIdx1 < newCells.length; cellIdx1++){
                                operations.push({
                                    type: 'insert',
                                    path: _to_consumable_array(rowPath).concat([
                                        cellIdx1
                                    ]),
                                    node: newCells[cellIdx1],
                                    priority: 6
                                });
                            }
                        } else if (newCells.length < oldCells.length) {
                            // 删除多余单元格（从后向前删除）
                            for(var cellIdx2 = oldCells.length - 1; cellIdx2 >= newCells.length; cellIdx2--){
                                operations.push({
                                    type: 'remove',
                                    path: _to_consumable_array(rowPath).concat([
                                        cellIdx2
                                    ]),
                                    priority: 1
                                });
                            }
                        }
                    }
                } else {
                    // 表格结构发生了变化，检查变化情况决定更新策略
                    // 如果是简单的行增减，采用行级更新而非整表替换
                    if (Math.abs(newRows.length - oldRows.length) <= 2) {
                        // 行数量变化较小，尝试行级别更新
                        // 先更新表格属性
                        if (tablePropsChanged()) {
                            operations.push({
                                type: 'update',
                                path: path,
                                properties: _object_spread_props(_object_spread({}, newTable), {
                                    children: undefined
                                }),
                                priority: 7
                            });
                        }
                        // 更新共有的行
                        var minRowCount = Math.min(newRows.length, oldRows.length);
                        for(var rowIdx1 = 0; rowIdx1 < minRowCount; rowIdx1++){
                            var rowPath1 = _to_consumable_array(path).concat([
                                rowIdx1
                            ]);
                            this.compareNodes(newRows[rowIdx1], oldRows[rowIdx1], rowPath1, operations);
                        }
                        // 处理行数变化
                        if (newRows.length > oldRows.length) {
                            // 添加新行
                            for(var rowIdx2 = oldRows.length; rowIdx2 < newRows.length; rowIdx2++){
                                operations.push({
                                    type: 'insert',
                                    path: _to_consumable_array(path).concat([
                                        rowIdx2
                                    ]),
                                    node: newRows[rowIdx2],
                                    priority: 5
                                });
                            }
                        } else if (newRows.length < oldRows.length) {
                            // 从后向前删除多余的行
                            for(var rowIdx3 = oldRows.length - 1; rowIdx3 >= newRows.length; rowIdx3--){
                                operations.push({
                                    type: 'remove',
                                    path: _to_consumable_array(path).concat([
                                        rowIdx3
                                    ]),
                                    priority: 1
                                });
                            }
                        }
                    } else {
                        // 结构变化较大，整表替换可能更高效
                        operations.push({
                            type: 'replace',
                            path: path,
                            node: newTable,
                            priority: 5
                        });
                    }
                }
            }
        },
        {
            key: "compareCells",
            value: /**
   * 比较和更新表格单元格。
   *
   * @param newCell - 新的单元格节点
   * @param oldCell - 旧的单元格节点
   * @param path - 单元格的路径
   * @param operations - 操作队列
   *
   * 处理步骤：
   * 1. 检查单元格属性变化
   * 2. 处理简单文本单元格
   * 3. 处理复杂单元格内容
   * 4. 生成适当的更新操作
   * @private
   */ function compareCells(newCell, oldCell, path, operations) {
                // 检查单元格属性是否变化
                this.compareCellProperties(newCell, oldCell, path, operations);
                // 处理单元格内容
                var newChildren = newCell.children || [];
                var oldChildren = oldCell.children || [];
                this.compareCellChildren(newChildren, oldChildren, path, operations);
            }
        },
        {
            key: "compareCellProperties",
            value: /**
   * 比较单元格属性
   */ function compareCellProperties(newCell, oldCell, path, operations) {
                var newCellProps = _object_spread_props(_object_spread({}, newCell), {
                    children: undefined
                });
                var oldCellProps = _object_spread_props(_object_spread({}, oldCell), {
                    children: undefined
                });
                if (!isEqual(newCellProps, oldCellProps)) {
                    operations.push({
                        type: 'update',
                        path: path,
                        properties: newCellProps,
                        priority: 7
                    });
                }
            }
        },
        {
            key: "compareCellChildren",
            value: /**
   * 比较单元格子节点
   */ function compareCellChildren(newChildren, oldChildren, path, operations) {
                // 简单文本单元格的优化处理
                if (this.isSimpleTextCell(newChildren, oldChildren)) {
                    this.compareSimpleTextCell(newChildren, oldChildren, path, operations);
                    return;
                }
                // 复杂单元格内容
                this.compareComplexCellChildren(newChildren, oldChildren, path, operations);
            }
        },
        {
            key: "isSimpleTextCell",
            value: /**
   * 判断是否是简单文本单元格
   */ function isSimpleTextCell(newChildren, oldChildren) {
                return newChildren.length === 1 && oldChildren.length === 1 && typeof newChildren[0].text === 'string' && typeof oldChildren[0].text === 'string';
            }
        },
        {
            key: "compareSimpleTextCell",
            value: /**
   * 比较简单文本单元格
   */ function compareSimpleTextCell(newChildren, oldChildren, path, operations) {
                // 只有文本内容变化
                if (newChildren[0].text !== oldChildren[0].text) {
                    operations.push({
                        type: 'text',
                        path: _to_consumable_array(path).concat([
                            0
                        ]),
                        text: newChildren[0].text,
                        priority: 8
                    });
                }
                // 检查文本节点的属性变化（加粗、斜体等）
                this.compareTextNodeProperties(newChildren[0], oldChildren[0], path, operations);
            }
        },
        {
            key: "compareTextNodeProperties",
            value: /**
   * 比较文本节点属性
   */ function compareTextNodeProperties(newChild, oldChild, path, operations) {
                var newTextProps = _object_spread({}, newChild);
                var oldTextProps = _object_spread({}, oldChild);
                delete newTextProps.text;
                delete oldTextProps.text;
                if (!isEqual(newTextProps, oldTextProps)) {
                    operations.push({
                        type: 'update',
                        path: _to_consumable_array(path).concat([
                            0
                        ]),
                        properties: newTextProps,
                        priority: 7
                    });
                }
            }
        },
        {
            key: "compareComplexCellChildren",
            value: /**
   * 比较复杂单元格子节点
   */ function compareComplexCellChildren(newChildren, oldChildren, path, operations) {
                // 检查是否结构完全不同
                var structurallyDifferent = this.isStructurallyDifferent(newChildren, oldChildren);
                if (structurallyDifferent) {
                    this.replaceComplexCellChildren(newChildren, oldChildren, path, operations);
                    return;
                }
                // 逐个比较并更新子节点
                this.compareChildrenSequentially(newChildren, oldChildren, path, operations);
            }
        },
        {
            key: "isStructurallyDifferent",
            value: /**
   * 判断结构是否不同
   */ function isStructurallyDifferent(newChildren, oldChildren) {
                if (newChildren.length !== oldChildren.length) return true;
                return newChildren.some(function(n, i) {
                    return oldChildren[i] && n.type !== oldChildren[i].type;
                });
            }
        },
        {
            key: "replaceComplexCellChildren",
            value: /**
   * 替换复杂单元格子节点
   */ function replaceComplexCellChildren(newChildren, oldChildren, path, operations) {
                var childOps = this.generateDiffOperations(newChildren, oldChildren);
                // 调整子操作的路径
                childOps.forEach(function(op) {
                    operations.push(_object_spread_props(_object_spread({}, op), {
                        path: _to_consumable_array(path).concat(_to_consumable_array(op.path))
                    }));
                });
            }
        },
        {
            key: "compareChildrenSequentially",
            value: /**
   * 逐个比较子节点
   */ function compareChildrenSequentially(newChildren, oldChildren, path, operations) {
                var length = Math.min(newChildren.length, oldChildren.length);
                for(var i = 0; i < length; i++){
                    this.compareNodes(newChildren[i], oldChildren[i], _to_consumable_array(path).concat([
                        i
                    ]), operations);
                }
            }
        },
        {
            key: "executeOperations",
            value: /**
   * 执行操作队列中的所有操作。
   *
   * @param operations - 要执行的操作队列
   *
   * 执行过程：
   * 1. 使用批处理模式执行所有操作
   * 2. 按照操作类型分别处理
   * 3. 处理可能的错误情况
   * 4. 保证操作的原子性
   */ function executeOperations(operations) {
                var editor = this._editor.current;
                if (!editor) return;
                // 使用批处理模式执行所有操作
                Editor.withoutNormalizing(editor, function() {
                    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                    try {
                        for(var _iterator = operations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                            var op = _step.value;
                            try {
                                switch(op.type){
                                    case 'insert':
                                        if (op.node && editor.hasPath(Path.parent(op.path))) {
                                            Transforms.insertNodes(editor, op.node, {
                                                at: op.path
                                            });
                                        }
                                        break;
                                    case 'remove':
                                        if (editor.hasPath(op.path)) {
                                            Transforms.removeNodes(editor, {
                                                at: op.path
                                            });
                                        }
                                        break;
                                    case 'update':
                                        if (op.properties && editor.hasPath(op.path)) {
                                            Transforms.setNodes(editor, op.properties, {
                                                at: op.path
                                            });
                                        }
                                        break;
                                    case 'replace':
                                        if (op.node && editor.hasPath(op.path)) {
                                            Transforms.removeNodes(editor, {
                                                at: op.path
                                            });
                                            Transforms.insertNodes(editor, op.node, {
                                                at: op.path
                                            });
                                        }
                                        break;
                                    case 'text':
                                        if (op.text !== undefined && editor.hasPath(op.path)) {
                                            Transforms.insertText(editor, op.text, {
                                                at: op.path,
                                                voids: true
                                            });
                                        }
                                        break;
                                }
                            } catch (err) {
                                console.error("Error executing operation ".concat(op.type, " at path ").concat(op.path, ":"), err);
                            }
                        }
                    } catch (err) {
                        _didIteratorError = true;
                        _iteratorError = err;
                    } finally{
                        try {
                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                _iterator.return();
                            }
                        } finally{
                            if (_didIteratorError) {
                                throw _iteratorError;
                            }
                        }
                    }
                });
            }
        },
        {
            /**
   * 处理拖拽开始事件。
   *
   * @param e - React 拖拽事件对象
   * @param container - 容器 div 元素
   *
   * 此方法会在拖拽开始时调用，主要功能包括：
   * 1. 阻止事件传播
   * 2. 设置拖拽图像
   * 3. 初始化拖拽相关的元素和位置数据
   * 4. 添加拖拽过程中和拖拽结束时的事件监听器
   * 5. 计算可拖拽目标的位置
   * 6. 处理拖拽过程中的视觉反馈
   * 7. 在拖拽结束时更新编辑器内容
   */ key: "dragStart",
            value: function dragStart(e, container) {
                var _this = this;
                var _this_draggedElement_dataset, _this_draggedElement;
                e.stopPropagation();
                var img = document.createElement('img');
                img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
                e.dataTransfer.setDragImage(img, 1, 1);
                var ableToEnter = ((_this_draggedElement = this.draggedElement) === null || _this_draggedElement === void 0 ? void 0 : (_this_draggedElement_dataset = _this_draggedElement.dataset) === null || _this_draggedElement_dataset === void 0 ? void 0 : _this_draggedElement_dataset.be) === 'list-item' ? new Set([
                    'paragraph',
                    'head',
                    'blockquote',
                    'code',
                    'table',
                    'list',
                    'list-item',
                    'media',
                    'attach'
                ]) : this.ableToEnter;
                var mark = null;
                var els = document.querySelectorAll('[data-be]');
                var points = [];
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    // @ts-ignore
                    for(var _iterator = els[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var el = _step.value;
                        var _this_draggedElement1;
                        if (!ableToEnter.has(el.dataset.be)) continue;
                        if (el.hasAttribute('data-frontmatter')) continue;
                        var pre = el.previousSibling;
                        if (el.dataset.be === 'paragraph' && ((_this_draggedElement1 = this.draggedElement) === null || _this_draggedElement1 === void 0 ? void 0 : _this_draggedElement1.dataset.be) === 'list-item' && (!pre || pre.hasAttribute('data-check-item'))) {
                            continue;
                        }
                        if (el === this.draggedElement) continue;
                        var top = getOffsetTop(el, container);
                        var left = getOffsetLeft(el, container);
                        points.push({
                            el: el,
                            direction: 'top',
                            left: left,
                            top: top
                        });
                        points.push({
                            el: el,
                            left: left,
                            direction: 'bottom',
                            top: top + el.clientHeight + 2
                        });
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                var last = null;
                var dragover = function(e) {
                    e.preventDefault();
                    var top = e.clientY - 40 + container.scrollTop;
                    var distance = 1000000;
                    var cur = null;
                    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                    try {
                        for(var _iterator = points[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                            var p = _step.value;
                            var curDistance = Math.abs(p.top - top);
                            if (curDistance < distance) {
                                cur = p;
                                distance = curDistance;
                            }
                        }
                    } catch (err) {
                        _didIteratorError = true;
                        _iteratorError = err;
                    } finally{
                        try {
                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                _iterator.return();
                            }
                        } finally{
                            if (_didIteratorError) {
                                throw _iteratorError;
                            }
                        }
                    }
                    if (cur) {
                        var rect = container.getBoundingClientRect();
                        var scrollTop = container.scrollTop;
                        var scrollLeft = container.scrollLeft;
                        last = cur;
                        var width = last.el.dataset.be === 'list-item' ? last.el.clientWidth + 20 + 'px' : last.el.clientWidth + 'px';
                        if (!mark) {
                            mark = document.createElement('div');
                            mark.setAttribute('data-move-mark', '');
                            mark.style.width = width;
                            mark.style.height = '2px';
                            mark.style.transform = "translate(".concat(last.left - rect.left - scrollLeft, "px, ").concat(last.top - rect.top - scrollTop, "px)");
                            container === null || container === void 0 ? void 0 : container.parentElement.append(mark);
                        } else {
                            mark.style.width = width;
                            mark.style.transform = "translate(".concat(last.left - rect.left - scrollLeft, "px, ").concat(last.top - rect.top - scrollTop, "px)");
                        }
                    }
                };
                window.addEventListener('dragover', dragover);
                window.addEventListener('dragend', function() {
                    try {
                        window.removeEventListener('dragover', dragover);
                        if (mark) container === null || container === void 0 ? void 0 : container.parentElement.removeChild(mark);
                        if (last && _this.draggedElement) {
                            var _this_toPath = _sliced_to_array(_this.toPath(_this.draggedElement), 2), dragPath = _this_toPath[0], dragNode = _this_toPath[1];
                            var _this_toPath1 = _sliced_to_array(_this.toPath(last.el), 1), targetPath = _this_toPath1[0];
                            var toPath = last.direction === 'top' ? targetPath : Path.next(targetPath);
                            if (!Path.equals(targetPath, dragPath)) {
                                var _parent_children;
                                var parent = Node.parent(_this._editor.current, dragPath);
                                if (Path.equals(Path.parent(targetPath), Path.parent(dragPath)) && Path.compare(dragPath, targetPath) === -1) {
                                    toPath = Path.previous(toPath);
                                }
                                var delPath = Path.parent(dragPath);
                                var targetNode = Node.get(_this._editor.current, targetPath);
                                if (dragNode.type === 'list-item') {
                                    if (targetNode.type !== 'list-item') {
                                        var _parent_children1;
                                        Transforms.delete(_this._editor.current, {
                                            at: dragPath
                                        });
                                        Transforms.insertNodes(_this._editor.current, _object_spread_props(_object_spread({}, parent), {
                                            children: [
                                                EditorUtils.copy(dragNode)
                                            ]
                                        }), {
                                            at: toPath,
                                            select: true
                                        });
                                        if (((_parent_children1 = parent.children) === null || _parent_children1 === void 0 ? void 0 : _parent_children1.length) === 1) {
                                            if (EditorUtils.isNextPath(Path.parent(dragPath), targetPath)) {
                                                delPath = Path.next(Path.parent(dragPath));
                                            } else {
                                                delPath = Path.parent(dragPath);
                                            }
                                        }
                                    } else {
                                        Transforms.moveNodes(_this._editor.current, {
                                            at: dragPath,
                                            to: toPath
                                        });
                                    }
                                } else {
                                    Transforms.moveNodes(_this._editor.current, {
                                        at: dragPath,
                                        to: toPath
                                    });
                                }
                                if (((_parent_children = parent.children) === null || _parent_children === void 0 ? void 0 : _parent_children.length) === 1) {
                                    if (Path.equals(Path.parent(toPath), Path.parent(delPath)) && Path.compare(toPath, delPath) !== 1) {
                                        delPath = Path.next(delPath);
                                    }
                                    Transforms.delete(_this._editor.current, {
                                        at: delPath
                                    });
                                }
                            }
                            if ((dragNode === null || dragNode === void 0 ? void 0 : dragNode.type) !== 'media') _this.draggedElement.draggable = false;
                        }
                        _this.draggedElement = null;
                    } catch (error) {
                        console.error(error);
                    }
                }, {
                    once: true
                });
            }
        },
        {
            /**
   * 替换编辑器中的文本内容
   *
   * @param searchText - 要查找和替换的原始文本
   * @param replaceText - 替换后的新文本
   * @param options - 可选参数
   * @param options.caseSensitive - 是否区分大小写，默认为 false
   * @param options.wholeWord - 是否只匹配完整单词，默认为 false
   * @param options.replaceAll - 是否替换所有匹配项，默认为 true
   *
   * @returns 替换操作的数量
   *
   * @example
   * ```ts
   * // 替换所有 "old" 为 "new"
   * const count = store.replaceText("old", "new");
   *
   * // 只替换第一个匹配项，区分大小写
   * const count = store.replaceText("Old", "New", {
   *   caseSensitive: true,
   *   replaceAll: false
   * });
   * ```
   */ key: "replaceText",
            value: function replaceText(searchText, replaceText) {
                var _this = this;
                var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
                var _options_caseSensitive = options.caseSensitive, caseSensitive = _options_caseSensitive === void 0 ? false : _options_caseSensitive, _options_wholeWord = options.wholeWord, wholeWord = _options_wholeWord === void 0 ? false : _options_wholeWord, _options_replaceAll = options.replaceAll, replaceAll = _options_replaceAll === void 0 ? true : _options_replaceAll;
                if (!searchText) return 0;
                var editor = this._editor.current;
                var replaceCount = 0;
                // 遍历所有文本节点进行替换
                var textNodes = Array.from(Editor.nodes(editor, {
                    at: [],
                    match: function(n) {
                        return Text.isText(n) && typeof n.text === 'string';
                    }
                }));
                Editor.withoutNormalizing(editor, function() {
                    if (replaceAll) {
                        var _loop = function(i) {
                            var _textNodes_i = _sliced_to_array(textNodes[i], 2), node = _textNodes_i[0], path = _textNodes_i[1];
                            var originalText = node.text;
                            var newText = originalText;
                            var nodeReplaceCount = 0;
                            if (caseSensitive) {
                                if (wholeWord) {
                                    // 匹配完整单词
                                    var regex = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), 'g');
                                    newText = originalText.replace(regex, function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                } else {
                                    // 普通字符串替换
                                    newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), 'g'), function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                }
                            } else {
                                if (wholeWord) {
                                    // 匹配完整单词，不区分大小写
                                    var regex1 = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), 'gi');
                                    newText = originalText.replace(regex1, function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                } else {
                                    // 普通字符串替换，不区分大小写
                                    newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), 'gi'), function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                }
                            }
                            // 如果文本发生了变化，更新节点
                            if (newText !== originalText) {
                                Transforms.insertText(editor, newText, {
                                    at: path,
                                    voids: true
                                });
                                replaceCount += nodeReplaceCount;
                            }
                        };
                        // 替换所有：从后往前处理，避免路径变化影响前面的操作
                        for(var i = textNodes.length - 1; i >= 0; i--)_loop(i);
                    } else {
                        var _loop1 = function(i1) {
                            var _textNodes_i = _sliced_to_array(textNodes[i1], 2), node = _textNodes_i[0], path = _textNodes_i[1];
                            var originalText = node.text;
                            var newText = originalText;
                            var nodeReplaceCount = 0;
                            if (caseSensitive) {
                                if (wholeWord) {
                                    // 匹配完整单词
                                    var regex = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), '');
                                    newText = originalText.replace(regex, function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                } else {
                                    // 普通字符串替换
                                    newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), ''), function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                }
                            } else {
                                if (wholeWord) {
                                    // 匹配完整单词，不区分大小写
                                    var regex1 = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), 'i');
                                    newText = originalText.replace(regex1, function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                } else {
                                    // 普通字符串替换，不区分大小写
                                    newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), 'i'), function() {
                                        nodeReplaceCount++;
                                        return replaceText;
                                    });
                                }
                            }
                            // 如果文本发生了变化，更新节点并停止
                            if (newText !== originalText) {
                                Transforms.insertText(editor, newText, {
                                    at: path,
                                    voids: true
                                });
                                replaceCount += nodeReplaceCount;
                                return "break" // 只替换第一个匹配项
                                ;
                            }
                        };
                        // 只替换第一个：从前往后处理，找到第一个匹配就停止
                        for(var i1 = 0; i1 < textNodes.length; i1++){
                            var _ret = _loop1(i1);
                            if (_ret === "break") break;
                        }
                    }
                });
                return replaceCount;
            }
        },
        {
            /**
   * 在选中的区域内替换文本
   *
   * @param searchText - 要查找和替换的原始文本
   * @param replaceText - 替换后的新文本
   * @param options - 可选参数
   * @param options.caseSensitive - 是否区分大小写，默认为 false
   * @param options.wholeWord - 是否只匹配完整单词，默认为 false
   * @param options.replaceAll - 是否替换所有匹配项，默认为 true
   *
   * @returns 替换操作的数量，如果没有选中区域则返回 0
   *
   * @example
   * ```ts
   * // 在选中区域内替换文本
   * const count = store.replaceTextInSelection("old", "new");
   * ```
   */ key: "replaceTextInSelection",
            value: function replaceTextInSelection(searchText, replaceText) {
                var _this = this;
                var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
                var editor = this._editor.current;
                var selection = editor.selection;
                if (!selection || Range.isCollapsed(selection)) {
                    return 0;
                }
                var _options_caseSensitive = options.caseSensitive, caseSensitive = _options_caseSensitive === void 0 ? false : _options_caseSensitive, _options_wholeWord = options.wholeWord, wholeWord = _options_wholeWord === void 0 ? false : _options_wholeWord, _options_replaceAll = options.replaceAll, replaceAll = _options_replaceAll === void 0 ? true : _options_replaceAll;
                if (!searchText) return 0;
                var replaceCount = 0;
                // 获取选中区域的文本节点
                var textNodes = Array.from(Editor.nodes(editor, {
                    at: selection,
                    match: function(n) {
                        return Text.isText(n) && typeof n.text === 'string';
                    }
                }));
                Editor.withoutNormalizing(editor, function() {
                    var _loop = function(i) {
                        var _textNodes_i = _sliced_to_array(textNodes[i], 2), node = _textNodes_i[0], path = _textNodes_i[1];
                        var originalText = node.text;
                        var newText = originalText;
                        var nodeReplaceCount = 0;
                        if (caseSensitive) {
                            if (wholeWord) {
                                var regex = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), 'g');
                                newText = originalText.replace(regex, function() {
                                    nodeReplaceCount++;
                                    return replaceText;
                                });
                            } else {
                                newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), 'g'), function() {
                                    nodeReplaceCount++;
                                    return replaceText;
                                });
                            }
                        } else {
                            if (wholeWord) {
                                var regex1 = new RegExp("\\b".concat(_this.escapeRegExp(searchText), "\\b"), 'gi');
                                newText = originalText.replace(regex1, function() {
                                    nodeReplaceCount++;
                                    return replaceText;
                                });
                            } else {
                                newText = originalText.replace(new RegExp(_this.escapeRegExp(searchText), 'gi'), function() {
                                    nodeReplaceCount++;
                                    return replaceText;
                                });
                            }
                        }
                        if (newText !== originalText) {
                            Transforms.insertText(editor, newText, {
                                at: path,
                                voids: true
                            });
                            replaceCount += nodeReplaceCount;
                            if (!replaceAll && nodeReplaceCount > 0) {
                                return "break";
                            }
                        }
                    };
                    // 从后往前处理，避免路径变化影响前面的操作
                    for(var i = textNodes.length - 1; i >= 0; i--){
                        var _ret = _loop(i);
                        if (_ret === "break") break;
                    }
                });
                return replaceCount;
            }
        },
        {
            /**
   * 替换所有匹配的文本（replaceText 的简化版本）
   *
   * @param searchText - 要查找和替换的原始文本
   * @param replaceText - 替换后的新文本
   * @param caseSensitive - 是否区分大小写，默认为 false
   *
   * @returns 替换操作的数量
   *
   * @example
   * ```ts
   * // 替换所有 "old" 为 "new"
   * const count = store.replaceAll("old", "new");
   *
   * // 区分大小写替换
   * const count = store.replaceAll("Old", "New", true);
   * ```
   */ key: "replaceAll",
            value: function replaceAll(searchText, replaceText) {
                var caseSensitive = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
                return this.replaceText(searchText, replaceText, {
                    caseSensitive: caseSensitive,
                    replaceAll: true
                });
            }
        },
        {
            key: "escapeRegExp",
            value: /**
   * 转义正则表达式特殊字符
   *
   * @param string - 需要转义的字符串
   * @returns 转义后的字符串
   * @private
   */ function escapeRegExp(string) {
                return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            }
        },
        {
            /**
   * 在编辑器中根据路径描述和文本内容查找并选择匹配位置
   *
   * @param pathDescription - 路径描述，用于限制搜索范围。可以是：
   *                         - 节点类型（如 "paragraph", "table", "list"）
   *                         - 包含特定文本的节点区域
   *                         - 空字符串表示在整个编辑器中搜索
   * @param searchText - 要查找的文本内容
   * @param options - 查找选项
   * @returns 匹配结果数组
   *
   * @example
   * ```ts
   * // 查找所有包含 "focus" 的位置
   * const results = store.findByPathAndText("", "focus");
   */ key: "findByPathAndText",
            value: function findByPathAndText1(pathDescription, searchText) {
                var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
                var _options_caseSensitive = options.caseSensitive, caseSensitive = _options_caseSensitive === void 0 ? false : _options_caseSensitive, _options_wholeWord = options.wholeWord, wholeWord = _options_wholeWord === void 0 ? false : _options_wholeWord, _options_maxResults = options.maxResults, maxResults = _options_maxResults === void 0 ? 50 : _options_maxResults;
                if (!searchText.trim()) return [];
                var editor = this._editor.current;
                return findByPathAndText(editor, pathDescription, searchText, {
                    caseSensitive: caseSensitive,
                    wholeWord: wholeWord,
                    maxResults: maxResults
                });
            }
        },
        {
            /**
   * 更新编辑器的状态数据
   *
   * @param value - 状态更新器，可以是函数或对象
   *
   * 该方法提供两种更新状态的方式：
   * 1. 函数式更新：传入一个函数，可以直接修改状态
   * 2. 对象式更新：传入一个对象，直接覆盖对应的状态值
   *
   * @example
   * ```ts
   * // 函数式更新 - 可以访问当前状态
   * setState((state) => {
   *   state.focus = true;
   *   state.manual = false;
   * });
   *
   * // 对象式更新 - 直接设置新值
   * setState({
   *   focus: true,
   *   manual: false
   * });
   * ```
   */ key: "setState",
            value: function setState(value) {
                if (value instanceof Function) {
                    value(this);
                } else {
                    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                    try {
                        for(var _iterator = Object.keys(value)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                            var key = _step.value;
                            // @ts-ignore
                            this[key] = value[key];
                        }
                    } catch (err) {
                        _didIteratorError = true;
                        _iteratorError = err;
                    } finally{
                        try {
                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                _iterator.return();
                            }
                        } finally{
                            if (_didIteratorError) {
                                throw _iteratorError;
                            }
                        }
                    }
                }
            }
        }
    ]);
    return EditorStore;
}();
