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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(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);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
/* eslint-disable @typescript-eslint/no-use-before-define */ /* eslint-disable no-param-reassign */ import { Editor, Element, Node, Path, Range, Transforms } from "slate";
import { jsx } from "slate-hyperscript";
import { debugInfo } from "../../../Utils/debugUtils";
import { EditorUtils } from "../utils";
import { docxDeserializer } from "../utils/docx/docxDeserializer";
import { BackspaceKey } from "./hotKeyCommands/backspace";
// 性能优化常量
var BATCH_SIZE = 10; // 每批处理的节点数量
var BATCH_DELAY = 16; // 每批之间的延迟时间(ms)，约60fps
var MAX_SYNC_SIZE = 1000; // 同步处理的最大字符数
/** 文件上传时排除的片段类型 */ var UPLOAD_EXCLUDED_FRAGMENT_TYPES = [
    'media',
    'image'
];
/** card 的第二个子节点为 media/image 时排除上传 */ var CARD_CONTENT_EXCLUDED_TYPES = [
    'media',
    'image'
];
var shouldExcludeFromUpload = function shouldExcludeFromUpload(fragment) {
    if (UPLOAD_EXCLUDED_FRAGMENT_TYPES.includes(fragment === null || fragment === void 0 ? void 0 : fragment.type)) {
        return true;
    }
    if ((fragment === null || fragment === void 0 ? void 0 : fragment.type) === 'card') {
        var _fragment_children;
        var secondNode = fragment === null || fragment === void 0 ? void 0 : (_fragment_children = fragment.children) === null || _fragment_children === void 0 ? void 0 : _fragment_children[1];
        return CARD_CONTENT_EXCLUDED_TYPES.includes(secondNode === null || secondNode === void 0 ? void 0 : secondNode.type);
    }
    return false;
};
var findElementByNode = function findElementByNode(node) {
    var index = Array.prototype.indexOf.call(node.parentNode.childNodes, node);
    return node.parentElement.children[index];
};
var fragment = new Set([
    'body',
    'figure',
    'div'
]);
export var ELEMENT_TAGS = {
    BLOCKQUOTE: function BLOCKQUOTE() {
        return {
            type: 'blockquote'
        };
    },
    H1: function H1(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'head',
            level: 1
        }, align ? {
            align: align
        } : {});
    },
    H2: function H2(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'head',
            level: 2
        }, align ? {
            align: align
        } : {});
    },
    H3: function H3(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'head',
            level: 3
        }, align ? {
            align: align
        } : {});
    },
    H4: function H4(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'head',
            level: 4
        }, align ? {
            align: align
        } : {});
    },
    H5: function H5(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'head',
            level: 5
        }, align ? {
            align: align
        } : {});
    },
    TABLE: function TABLE() {
        return {
            type: 'table'
        };
    },
    IMG: function IMG(el) {
        // 添加更严格的图片URL验证，避免将普通URL误识别为图片
        var src = el === null || el === void 0 ? void 0 : el.src;
        var alt = el === null || el === void 0 ? void 0 : el.alt;
        // 检查是否为有效的图片URL
        var isValidImageUrl = function isValidImageUrl(url) {
            if (!url) return false;
            // 检查是否为blob URL或data URL
            if (url.startsWith('blob:') || url.startsWith('data:')) {
                return true;
            }
            // 检查是否为有效的HTTP/HTTPS URL
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                return false;
            }
            // 检查URL是否包含图片文件扩展名
            var imageExtensions = [
                '.jpg',
                '.jpeg',
                '.png',
                '.gif',
                '.svg',
                '.webp',
                '.bmp',
                '.ico'
            ];
            var hasImageExtension = imageExtensions.some(function(ext) {
                return url.toLowerCase().includes(ext);
            });
            // 检查URL是否包含图片相关的路径
            var imagePaths = [
                '/image',
                '/img',
                '/photo',
                '/picture',
                '/avatar',
                '/icon'
            ];
            var hasImagePath = imagePaths.some(function(path) {
                return url.toLowerCase().includes(path);
            });
            // 检查Content-Type（如果可能的话）
            var hasImageContentType = url.includes('image/') || url.includes('img/');
            // 如果URL看起来像图片，或者是明确的图片URL，则认为是有效的
            return hasImageExtension || hasImagePath || hasImageContentType;
        };
        // 如果URL不是有效的图片URL，则作为普通文本处理
        if (!isValidImageUrl(src)) {
            return {
                type: 'paragraph',
                children: [
                    {
                        text: src || alt || '图片链接'
                    }
                ]
            };
        }
        return EditorUtils.createMediaNode(src, 'image', {
            alt: alt,
            downloadUrl: src && /^https?:/.test(src) ? src : undefined
        });
    },
    TR: function TR() {
        return {
            type: 'table-row'
        };
    },
    TH: function TH() {
        return {
            type: 'table-cell',
            title: true
        };
    },
    TD: function TD() {
        return {
            type: 'table-cell'
        };
    },
    LI: function LI() {
        return {
            type: 'list-item'
        };
    },
    OL: function OL() {
        return {
            type: 'list',
            order: true
        };
    },
    P: function P(el) {
        var _el_style;
        var align = (el && typeof el.getAttribute === 'function' ? el.getAttribute('align') : null) || (el === null || el === void 0 ? void 0 : (_el_style = el.style) === null || _el_style === void 0 ? void 0 : _el_style.textAlign) || (el && typeof el.getAttribute === 'function' ? el.getAttribute('data-align') : null);
        return _object_spread({
            type: 'paragraph'
        }, align ? {
            align: align
        } : {});
    },
    PRE: function PRE() {
        return {
            type: 'code'
        };
    },
    UL: function UL() {
        return {
            type: 'bulleted-list'
        };
    }
};
export var TEXT_TAGS = {
    A: function A(el) {
        return {
            url: el && typeof el.getAttribute === 'function' ? el.getAttribute('href') : null
        };
    },
    CODE: function CODE() {
        return {
            code: true
        };
    },
    KBD: function KBD() {
        return {
            code: true
        };
    },
    SPAN: function SPAN(el) {
        return {
            text: el === null || el === void 0 ? void 0 : el.textContent
        };
    },
    DEL: function DEL() {
        return {
            strikethrough: true
        };
    },
    EM: function EM() {
        return {
            italic: true
        };
    },
    I: function I() {
        return {
            italic: true
        };
    },
    S: function S() {
        return {
            strikethrough: true
        };
    },
    STRONG: function STRONG() {
        return {
            bold: true
        };
    },
    B: function B() {
        return {
            bold: true
        };
    }
};
export var deserialize = function deserialize1(el) {
    var parentTag = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : '';
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'script') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'style') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'meta') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'link') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'head') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'colgroup') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase()) === 'noscript') return [];
    if ((el === null || el === void 0 ? void 0 : el.nodeType) === 3) {
        return el === null || el === void 0 ? void 0 : el.textContent;
    } else if ((el === null || el === void 0 ? void 0 : el.nodeType) !== 1) {
        return null;
    } else if ((el === null || el === void 0 ? void 0 : el.nodeName) === 'BR') {
        return '\n';
    }
    var nodeName = el.nodeName;
    var target = el;
    if (nodeName === 'PRE' && (el === null || el === void 0 ? void 0 : el.childNodes[0]) && (el === null || el === void 0 ? void 0 : el.childNodes[0].nodeName) === 'CODE') {
        target = el === null || el === void 0 ? void 0 : el.childNodes[0];
    }
    var children = Array.from(target.childNodes).map(function(n) {
        return deserialize(n, target.nodeName.toLowerCase().toLowerCase());
    }).flat();
    if (children.length === 0) {
        children = [
            {
                text: (el === null || el === void 0 ? void 0 : el.textContent) || ''
            }
        ];
    }
    if (fragment.has(el === null || el === void 0 ? void 0 : el.nodeName.toLowerCase())) {
        return jsx('fragment', {}, children);
    }
    if (TEXT_TAGS[nodeName] && Array.from(el === null || el === void 0 ? void 0 : el.childNodes).some(function(e) {
        return e.nodeType !== 3 && !TEXT_TAGS[e.nodeName];
    })) {
        return jsx('fragment', {}, children);
    }
    if (ELEMENT_TAGS[nodeName]) {
        if (!parentTag || ![
            'h1',
            'h2',
            'code',
            'h3',
            'h4',
            'h5',
            'th',
            'td'
        ].includes(parentTag)) {
            if (nodeName === 'PRE') {
                var dom = findElementByNode(el);
                var dataset = dom.dataset;
                var inner = (dataset === null || dataset === void 0 ? void 0 : dataset.blType) === 'code';
                if (inner) {
                    var value = Array.from(target.childNodes.values()).map(function(n) {
                        var _n_textContent_replace, _n_textContent;
                        return (_n_textContent = n.textContent) === null || _n_textContent === void 0 ? void 0 : (_n_textContent_replace = _n_textContent.replace(/\n/g, '')) === null || _n_textContent_replace === void 0 ? void 0 : _n_textContent_replace.replace(/\t/g, '  ');
                    });
                    return {
                        type: 'code',
                        language: dataset === null || dataset === void 0 ? void 0 : dataset.blLang,
                        value: value,
                        children: [
                            {
                                text: value
                            }
                        ]
                    };
                } else {
                    var text = parserCodeText(findElementByNode(target));
                    if (text) {
                        return {
                            type: 'code',
                            value: text,
                            children: [
                                {
                                    text: text
                                }
                            ]
                        };
                    }
                }
                return null;
            }
            // @ts-ignore
            var attrs = ELEMENT_TAGS[nodeName](el);
            return jsx('element', attrs, children);
        }
    }
    if (TEXT_TAGS[nodeName]) {
        // @ts-ignore
        var attrs1 = TEXT_TAGS[nodeName](el);
        return children.map(function(child) {
            return jsx('text', attrs1, child);
        }).filter(function(c) {
            return !!c.text;
        });
    }
    return children;
};
var parserCodeText = function parserCodeText(el) {
    if (!el) return '';
    el.innerHTML = el === null || el === void 0 ? void 0 : el.innerHTML.replace(/<br\/?>|<\/div>(?=\S)/g, '\n');
    return el === null || el === void 0 ? void 0 : el.innerText;
};
var getTextsNode = function getTextsNode1(nodes) {
    var text = [];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var n = _step.value;
            if (n.text) {
                text.push(n);
            }
            if (n === null || n === void 0 ? void 0 : n.children) {
                var _text;
                (_text = text).push.apply(_text, _to_consumable_array(getTextsNode(n.children)));
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return text;
};
var blobToFile = function blobToFile(blobUrl, fileName) {
    return _async_to_generator(function() {
        var blob, file;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    return [
                        4,
                        fetch(blobUrl).then(function(r) {
                            return r.blob();
                        })
                    ];
                case 1:
                    blob = _state.sent();
                    file = new File([
                        blob
                    ], fileName);
                    return [
                        2,
                        file
                    ];
            }
        });
    })();
};
/**
 * 从片段列表中递归移除所有媒体类型的片段（图片、视频、音频等）
 */ var removeMediaFragments = function removeMediaFragments1(fragments) {
    for(var i = fragments.length - 1; i >= 0; i--){
        var fragment = fragments[i];
        if (fragment.type === 'media') {
            fragments.splice(i, 1);
            continue;
        }
        if (fragment === null || fragment === void 0 ? void 0 : fragment.children) {
            removeMediaFragments(fragment.children);
        }
    }
};
/**
 * 分段处理文件上传，避免阻塞主线程
 */ var upLoadFileBatch = function upLoadFileBatch(fragmentList, editorProps) {
    return _async_to_generator(function() {
        var _editorProps_image, mediaFragments, collectMediaFragments, hideLoading, i, batch, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    // 如果没有配置 upload，过滤掉所有媒体类型的片段
                    if (!((_editorProps_image = editorProps.image) === null || _editorProps_image === void 0 ? void 0 : _editorProps_image.upload)) {
                        removeMediaFragments(fragmentList);
                        return [
                            2
                        ];
                    }
                    mediaFragments = [];
                    // 收集所有需要上传的媒体文件
                    collectMediaFragments = function collectMediaFragments1(fragments) {
                        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                        try {
                            for(var _iterator = fragments[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                                var fragment = _step.value;
                                if (fragment.type === 'media') {
                                    mediaFragments.push(fragment);
                                }
                                if (fragment === null || fragment === void 0 ? void 0 : fragment.children) {
                                    collectMediaFragments(fragment.children);
                                }
                            }
                        } catch (err) {
                            _didIteratorError = true;
                            _iteratorError = err;
                        } finally{
                            try {
                                if (!_iteratorNormalCompletion && _iterator.return != null) {
                                    _iterator.return();
                                }
                            } finally{
                                if (_didIteratorError) {
                                    throw _iteratorError;
                                }
                            }
                        }
                    };
                    collectMediaFragments(fragmentList);
                    if (mediaFragments.length === 0) {
                        return [
                            2
                        ];
                    }
                    hideLoading = function hideLoading() {};
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        7,
                        8,
                        9
                    ]);
                    i = 0;
                    _state.label = 2;
                case 2:
                    if (!(i < mediaFragments.length)) return [
                        3,
                        6
                    ];
                    batch = mediaFragments.slice(i, i + BATCH_SIZE);
                    return [
                        4,
                        Promise.all(batch.map(function(fragment) {
                            return _async_to_generator(function() {
                                var url, _editorProps_image, file, serverUrl, _editorProps_image1, serverUrl1;
                                return _ts_generator(this, function(_state) {
                                    switch(_state.label){
                                        case 0:
                                            url = fragment.url;
                                            if (!(url === null || url === void 0 ? void 0 : url.startsWith('blob:'))) return [
                                                3,
                                                4
                                            ];
                                            return [
                                                4,
                                                blobToFile(fragment === null || fragment === void 0 ? void 0 : fragment.url, 'image.png')
                                            ];
                                        case 1:
                                            file = _state.sent();
                                            if (!((_editorProps_image = editorProps.image) === null || _editorProps_image === void 0 ? void 0 : _editorProps_image.upload)) return [
                                                3,
                                                3
                                            ];
                                            return [
                                                4,
                                                editorProps.image.upload([
                                                    file
                                                ])
                                            ];
                                        case 2:
                                            serverUrl = [
                                                _state.sent()
                                            ].flat(1);
                                            fragment.url = serverUrl === null || serverUrl === void 0 ? void 0 : serverUrl[0];
                                            fragment.downloadUrl = serverUrl === null || serverUrl === void 0 ? void 0 : serverUrl[0];
                                            _state.label = 3;
                                        case 3:
                                            return [
                                                3,
                                                6
                                            ];
                                        case 4:
                                            if (!((_editorProps_image1 = editorProps.image) === null || _editorProps_image1 === void 0 ? void 0 : _editorProps_image1.upload)) return [
                                                3,
                                                6
                                            ];
                                            return [
                                                4,
                                                editorProps.image.upload([
                                                    fragment === null || fragment === void 0 ? void 0 : fragment.url
                                                ])
                                            ];
                                        case 5:
                                            serverUrl1 = [
                                                _state.sent()
                                            ].flat(1);
                                            fragment.url = serverUrl1 === null || serverUrl1 === void 0 ? void 0 : serverUrl1[0];
                                            fragment.downloadUrl = serverUrl1 === null || serverUrl1 === void 0 ? void 0 : serverUrl1[0];
                                            _state.label = 6;
                                        case 6:
                                            return [
                                                2
                                            ];
                                    }
                                });
                            })();
                        }))
                    ];
                case 3:
                    _state.sent();
                    if (!(i + BATCH_SIZE < mediaFragments.length)) return [
                        3,
                        5
                    ];
                    return [
                        4,
                        new Promise(function(resolve) {
                            return setTimeout(resolve, BATCH_DELAY);
                        })
                    ];
                case 4:
                    _state.sent();
                    _state.label = 5;
                case 5:
                    i += BATCH_SIZE;
                    return [
                        3,
                        2
                    ];
                case 6:
                    return [
                        3,
                        9
                    ];
                case 7:
                    error = _state.sent();
                    console.error('文件上传失败:', error);
                    return [
                        3,
                        9
                    ];
                case 8:
                    hideLoading();
                    return [
                        7
                    ];
                case 9:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 分段插入节点，避免一次性插入大量内容导致卡顿
 */ var insertNodesBatch = function insertNodesBatch(editor, nodes, at, options) {
    return _async_to_generator(function() {
        var i, batch, insertAt;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (nodes.length <= BATCH_SIZE) {
                        // 小批量直接插入
                        Transforms.insertNodes(editor, nodes, _object_spread({
                            at: at
                        }, options));
                        return [
                            2
                        ];
                    }
                    i = 0;
                    _state.label = 1;
                case 1:
                    if (!(i < nodes.length)) return [
                        3,
                        4
                    ];
                    batch = nodes.slice(i, i + BATCH_SIZE);
                    // 计算插入位置
                    insertAt = at ? _to_consumable_array(at.slice(0, -1)).concat([
                        at[at.length - 1] + i
                    ]) : undefined;
                    Transforms.insertNodes(editor, batch, {
                        at: insertAt,
                        select: (options === null || options === void 0 ? void 0 : options.select) && i + BATCH_SIZE >= nodes.length
                    });
                    if (!(i + BATCH_SIZE < nodes.length)) return [
                        3,
                        3
                    ];
                    return [
                        4,
                        new Promise(function(resolve) {
                            return setTimeout(resolve, BATCH_DELAY);
                        })
                    ];
                case 2:
                    _state.sent();
                    _state.label = 3;
                case 3:
                    i += BATCH_SIZE;
                    return [
                        3,
                        1
                    ];
                case 4:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 优化的HTML解析函数，支持分段处理
 */ var parseHtmlOptimized = function parseHtmlOptimized(html, rtf) {
    return _async_to_generator(function() {
        var result;
        return _ts_generator(this, function(_state) {
            debugInfo('parseHtmlOptimized - 开始解析', {
                htmlLength: html.length,
                rtfLength: rtf.length,
                useSync: html.length < MAX_SYNC_SIZE
            });
            // 对于小内容，使用同步处理
            if (html.length < MAX_SYNC_SIZE) {
                result = docxDeserializer(rtf, html.trim());
                debugInfo('parseHtmlOptimized - 同步解析完成', {
                    resultLength: result === null || result === void 0 ? void 0 : result.length,
                    resultTypes: result === null || result === void 0 ? void 0 : result.map(function(r) {
                        return r === null || r === void 0 ? void 0 : r.type;
                    })
                });
                return [
                    2,
                    result
                ];
            }
            // 对于大内容，使用异步处理
            return [
                2,
                new Promise(function(resolve) {
                    // 使用 requestIdleCallback 在空闲时间处理
                    var processInIdle = function processInIdle() {
                        try {
                            debugInfo('parseHtmlOptimized - 异步解析开始');
                            var result = docxDeserializer(rtf, html.trim());
                            debugInfo('parseHtmlOptimized - 异步解析完成', {
                                resultLength: result === null || result === void 0 ? void 0 : result.length,
                                resultTypes: result === null || result === void 0 ? void 0 : result.map(function(r) {
                                    return r === null || r === void 0 ? void 0 : r.type;
                                })
                            });
                            resolve(result);
                        } catch (error) {
                            console.error('HTML解析失败:', error);
                            debugInfo('parseHtmlOptimized - 解析失败', {
                                error: error
                            });
                            resolve([]);
                        }
                    };
                    if ('requestIdleCallback' in window) {
                        requestIdleCallback(processInIdle, {
                            timeout: 1000
                        });
                    } else {
                        // 降级到 setTimeout
                        setTimeout(processInIdle, 0);
                    }
                })
            ];
        });
    })();
};
/**
 * 转化 html 到 slate - 性能优化版本
 * @param editor
 * @param html
 * @returns
 */ export var htmlToFragmentList = function htmlToFragmentList(html, rtl) {
    debugInfo('htmlToFragmentList - 开始转换', {
        htmlLength: html.length,
        rtlLength: rtl.length
    });
    var fragmentList = docxDeserializer(rtl, html.trim());
    debugInfo('htmlToFragmentList - 反序列化完成', {
        fragmentListLength: fragmentList === null || fragmentList === void 0 ? void 0 : fragmentList.length,
        fragmentTypes: fragmentList === null || fragmentList === void 0 ? void 0 : fragmentList.map(function(f) {
            return f === null || f === void 0 ? void 0 : f.type;
        })
    });
    var result = fragmentList.map(function(fragment) {
        if (fragment.type === 'table') {
            return EditorUtils.wrapperCardNode(fragment);
        }
        if (fragment.type === '"paragraph"' && fragment.children.length === 1) {
            return {
                type: 'paragraph',
                children: fragment.children
            };
        }
        return fragment;
    });
    debugInfo('htmlToFragmentList - 转换完成', {
        resultLength: result.length,
        resultTypes: result.map(function(r) {
            return r === null || r === void 0 ? void 0 : r.type;
        })
    });
    return result;
};
export var insertParsedHtmlNodes = function insertParsedHtmlNodes(editor, html, editorProps, rtl) {
    return _async_to_generator(function() {
        var fragmentList, fragmentsToUpload, _Editor_nodes, node, selection, processedNodes, back, _Editor_nodes1, specialNode, parsed, inner, hasCodeTags, textContent, children, _Editor_nodes2, p, parent, nextPath, texts, text, processedNodes1, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    debugInfo('insertParsedHtmlNodes - 开始插入 HTML 节点', {
                        htmlLength: html === null || html === void 0 ? void 0 : html.length,
                        htmlPreview: html === null || html === void 0 ? void 0 : html.substring(0, 200),
                        rtlLength: rtl === null || rtl === void 0 ? void 0 : rtl.length,
                        hasEditorProps: !!editorProps
                    });
                    // 1. 基础检查
                    if (html.startsWith('<html>\r\n<body>\r\n\x3C!--StartFragment--><img src="')) {
                        debugInfo('insertParsedHtmlNodes - 跳过特殊格式的 HTML');
                        return [
                            2,
                            false
                        ];
                    }
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        17,
                        ,
                        18
                    ]);
                    return [
                        4,
                        parseHtmlOptimized(html, rtl)
                    ];
                case 2:
                    fragmentList = _state.sent();
                    if (!(fragmentList === null || fragmentList === void 0 ? void 0 : fragmentList.length)) {
                        return [
                            2,
                            false
                        ];
                    }
                    // 4. 异步处理文件上传（排除 media、image；card 需判断第二个节点类型）
                    fragmentsToUpload = fragmentList.filter(function(f) {
                        return !shouldExcludeFromUpload(f);
                    });
                    return [
                        4,
                        upLoadFileBatch(fragmentsToUpload, editorProps)
                    ];
                case 3:
                    _state.sent();
                    // 5. 获取当前节点
                    _Editor_nodes = _sliced_to_array(Editor.nodes(editor, {
                        match: function match(n) {
                            return Element.isElement(n);
                        }
                    }), 1), node = _Editor_nodes[0];
                    selection = editor.selection;
                    if (!(!selection || !Editor.hasPath(editor, selection.anchor.path))) return [
                        3,
                        5
                    ];
                    debugInfo('insertParsedHtmlNodes - 无有效选区，直接插入');
                    processedNodes = fragmentsToUpload === null || fragmentsToUpload === void 0 ? void 0 : fragmentsToUpload.map(function(item) {
                        if (!item.type) {
                            return {
                                type: 'paragraph',
                                children: [
                                    item
                                ]
                            };
                        }
                        return item;
                    });
                    debugInfo('insertParsedHtmlNodes - 处理后的节点', {
                        processedNodesLength: processedNodes === null || processedNodes === void 0 ? void 0 : processedNodes.length,
                        processedTypes: processedNodes === null || processedNodes === void 0 ? void 0 : processedNodes.map(function(n) {
                            return n === null || n === void 0 ? void 0 : n.type;
                        })
                    });
                    return [
                        4,
                        insertNodesBatch(editor, processedNodes)
                    ];
                case 4:
                    _state.sent();
                    debugInfo('insertParsedHtmlNodes - 节点插入完成');
                    return [
                        2,
                        true
                    ];
                case 5:
                    // 7. 处理非折叠选区
                    if (!Range.isCollapsed(selection)) {
                        debugInfo('insertParsedHtmlNodes - 处理非折叠选区', {
                            selectionRange: {
                                anchor: selection.anchor,
                                focus: selection.focus
                            }
                        });
                        back = new BackspaceKey(editor);
                        back.range();
                        Transforms.select(editor, Range.start(selection));
                        setTimeout(function() {
                            var _node_;
                            var node = Editor === null || Editor === void 0 ? void 0 : Editor.node(editor, [
                                0
                            ]);
                            if (editor.children.length > 1 && (node === null || node === void 0 ? void 0 : (_node_ = node[0]) === null || _node_ === void 0 ? void 0 : _node_.type) === 'paragraph' && !Node.string(node[0])) {
                                Transforms.delete(editor, {
                                    at: [
                                        0
                                    ]
                                });
                            }
                        });
                    }
                    // 8. 获取特殊节点类型
                    _Editor_nodes1 = _sliced_to_array(Editor.nodes(editor, {
                        match: function match(n) {
                            return Element.isElement(n) && [
                                'code',
                                'table-cell',
                                'head',
                                'list-item'
                            ].includes(n.type);
                        },
                        at: Range.isCollapsed(selection) ? selection.anchor.path : Range.start(selection).path
                    }), 1), specialNode = _Editor_nodes1[0];
                    if (specialNode) {
                        node = specialNode;
                    }
                    // 9. 处理代码块和表格单元格
                    parsed = new DOMParser().parseFromString(html, 'text/html').body;
                    inner = !!parsed.querySelector('[data-be]');
                    debugInfo('insertParsedHtmlNodes - DOM 解析完成', {
                        hasDataBe: inner,
                        parsedBodyChildren: parsed.children.length
                    });
                    // 对于代码块，检查是否包含代码相关的标签
                    if ((node === null || node === void 0 ? void 0 : node[0].type) === 'code') {
                        debugInfo('insertParsedHtmlNodes - 当前节点是代码块', {
                            nodeType: node[0].type
                        });
                        hasCodeTags = html.includes('<pre>') || html.includes('<code>') || inner;
                        debugInfo('insertParsedHtmlNodes - 代码块检查', {
                            hasPreTag: html.includes('<pre>'),
                            hasCodeTag: html.includes('<code>'),
                            hasDataBe: inner,
                            hasCodeTags: hasCodeTags
                        });
                        if (hasCodeTags) {
                            // 从 HTML 中提取纯文本内容
                            textContent = parsed.textContent || '';
                            debugInfo('insertParsedHtmlNodes - 提取文本内容', {
                                textContentLength: textContent.length,
                                textContentPreview: textContent.substring(0, 100)
                            });
                            if (textContent.trim()) {
                                Transforms.insertText(editor, textContent.trim(), {
                                    at: selection
                                });
                                debugInfo('insertParsedHtmlNodes - 代码块文本插入完成');
                                return [
                                    2,
                                    true
                                ];
                            }
                        }
                    }
                    // 处理表格单元格
                    if (inner && (node === null || node === void 0 ? void 0 : node[0].type) === 'table-cell') {
                        return [
                            2,
                            true
                        ];
                    }
                    if (!((node === null || node === void 0 ? void 0 : node[0].type) === 'list-item' && (fragmentsToUpload[0].type === 'list' || fragmentsToUpload[0].type === 'bulleted-list' || fragmentsToUpload[0].type === 'numbered-list'))) return [
                        3,
                        12
                    ];
                    debugInfo('insertParsedHtmlNodes - 处理列表项', {
                        currentNodeType: node[0].type,
                        fragmentListType: fragmentsToUpload[0].type
                    });
                    children = fragmentsToUpload[0].children || [];
                    debugInfo('insertParsedHtmlNodes - 列表项子节点', {
                        childrenCount: children.length
                    });
                    if (!children.length) {
                        debugInfo('insertParsedHtmlNodes - 列表项无子节点');
                        return [
                            2,
                            false
                        ];
                    }
                    _Editor_nodes2 = _sliced_to_array(Editor.nodes(editor, {
                        match: function match(n) {
                            return Element.isElement(n) && n.type === 'paragraph';
                        },
                        at: Range.isCollapsed(selection) ? selection.anchor.path : Range.start(selection).path
                    }), 1), p = _Editor_nodes2[0];
                    if (!(specialNode && !Path.hasPrevious(p[1]))) return [
                        3,
                        12
                    ];
                    if (!!Node.string(p[0])) return [
                        3,
                        7
                    ];
                    return [
                        4,
                        insertNodesBatch(editor, children, Path.next(specialNode[1]))
                    ];
                case 6:
                    _state.sent();
                    parent = Node.parent(editor, p[1]);
                    nextPath = _to_consumable_array(specialNode[1].slice(0, -1)).concat([
                        specialNode[1][specialNode[1].length - 1] + children.length
                    ]);
                    if (parent.children.length > 1) {
                        Transforms.moveNodes(editor, {
                            at: {
                                anchor: {
                                    path: Path.next(p[1]),
                                    offset: 0
                                },
                                focus: {
                                    path: _to_consumable_array(p[1].slice(0, -1)).concat([
                                        parent.children.length - 1
                                    ]),
                                    offset: 0
                                }
                            },
                            to: _to_consumable_array(nextPath).concat([
                                1
                            ])
                        });
                    }
                    Transforms.delete(editor, {
                        at: selection
                    });
                    return [
                        3,
                        9
                    ];
                case 7:
                    return [
                        4,
                        insertNodesBatch(editor, children, selection.anchor.path, {
                            select: true
                        })
                    ];
                case 8:
                    _state.sent();
                    _state.label = 9;
                case 9:
                    if (!(fragmentsToUpload.length > 1)) return [
                        3,
                        11
                    ];
                    return [
                        4,
                        insertNodesBatch(editor, fragmentsToUpload.slice(1), selection.anchor.path, {
                            select: true
                        })
                    ];
                case 10:
                    _state.sent();
                    _state.label = 11;
                case 11:
                    return [
                        2,
                        true
                    ];
                case 12:
                    // 11. 处理表格单元格
                    if ((node === null || node === void 0 ? void 0 : node[0].type) === 'table-cell') {
                        Transforms.insertFragment(editor, getTextsNode(fragmentsToUpload), {
                            at: selection
                        });
                        return [
                            2,
                            true
                        ];
                    }
                    if (!((node === null || node === void 0 ? void 0 : node[0].type) === 'head')) return [
                        3,
                        15
                    ];
                    if (fragmentsToUpload[0].type) {
                        if (fragmentsToUpload[0].type !== 'paragraph') {
                            Transforms.insertNodes(editor, {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            }, {
                                at: selection,
                                select: true
                            });
                            return [
                                2,
                                true
                            ];
                        }
                        return [
                            2,
                            false
                        ];
                    }
                    texts = fragmentsToUpload.filter(function(c) {
                        return c.text;
                    });
                    if (!texts.length) return [
                        3,
                        14
                    ];
                    return [
                        4,
                        insertNodesBatch(editor, texts, selection.anchor.path)
                    ];
                case 13:
                    _state.sent();
                    return [
                        2,
                        true
                    ];
                case 14:
                    return [
                        2,
                        false
                    ];
                case 15:
                    // 13. 处理单个段落的特殊情况
                    if (fragmentsToUpload.length === 1 && (fragmentsToUpload[0].type === 'paragraph' || !fragmentsToUpload[0].type) && node) {
                        text = Node.string(fragmentsToUpload[0]);
                        if (text) {
                            Transforms.insertText(editor, text, {
                                at: selection
                            });
                            return [
                                2,
                                true
                            ];
                        }
                    }
                    // 14. 默认情况：替换选中节点
                    debugInfo('insertParsedHtmlNodes - 使用默认处理方式');
                    processedNodes1 = fragmentsToUpload === null || fragmentsToUpload === void 0 ? void 0 : fragmentsToUpload.map(function(item) {
                        if (!item.type) {
                            return {
                                type: 'paragraph',
                                children: [
                                    item
                                ]
                            };
                        }
                        if (item.type === 'code') {
                            return _object_spread_props(_object_spread({}, item), {
                                type: 'code',
                                value: Node.string(item),
                                language: item.language || 'txt'
                            });
                        }
                        return item;
                    });
                    debugInfo('insertParsedHtmlNodes - 默认处理节点准备完成', {
                        processedNodesLength: processedNodes1 === null || processedNodes1 === void 0 ? void 0 : processedNodes1.length,
                        processedTypes: processedNodes1 === null || processedNodes1 === void 0 ? void 0 : processedNodes1.map(function(n) {
                            return n === null || n === void 0 ? void 0 : n.type;
                        })
                    });
                    return [
                        4,
                        insertNodesBatch(editor, processedNodes1)
                    ];
                case 16:
                    _state.sent();
                    debugInfo('insertParsedHtmlNodes - 默认处理完成');
                    return [
                        2,
                        true
                    ];
                case 17:
                    error = _state.sent();
                    console.error('插入HTML节点失败:', error);
                    return [
                        2,
                        false
                    ];
                case 18:
                    return [
                        2
                    ];
            }
        });
    })();
};
