/* eslint-disable @typescript-eslint/no-use-before-define */ /* 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 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, g, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    };
    return g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(_)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { message } from "antd";
import { Editor, Element, Node, Path, Range, Transforms } from "slate";
import { jsx } from "slate-hyperscript";
import { debugLog, 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 findElementByNode = function(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() {
        return {
            type: 'blockquote'
        };
    },
    H1: function() {
        return {
            type: 'head',
            level: 1
        };
    },
    H2: function() {
        return {
            type: 'head',
            level: 2
        };
    },
    H3: function() {
        return {
            type: 'head',
            level: 3
        };
    },
    H4: function() {
        return {
            type: 'head',
            level: 4
        };
    },
    H5: function() {
        return {
            type: 'head',
            level: 5
        };
    },
    TABLE: function() {
        return {
            type: 'table'
        };
    },
    IMG: function(el) {
        // 添加更严格的图片URL验证，避免将普通URL误识别为图片
        var src = el.src;
        var alt = el.alt;
        // 检查是否为有效的图片URL
        var isValidImageUrl = function(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() {
        return {
            type: 'table-row'
        };
    },
    TH: function() {
        return {
            type: 'table-cell',
            title: true
        };
    },
    TD: function() {
        return {
            type: 'table-cell'
        };
    },
    LI: function() {
        return {
            type: 'list-item'
        };
    },
    OL: function() {
        return {
            type: 'list',
            order: true
        };
    },
    P: function() {
        return {
            type: 'paragraph'
        };
    },
    PRE: function() {
        return {
            type: 'code'
        };
    },
    UL: function() {
        return {
            type: 'list'
        };
    }
};
export var TEXT_TAGS = {
    A: function(el) {
        return {
            url: el.getAttribute('href')
        };
    },
    CODE: function() {
        return {
            code: true
        };
    },
    KBD: function() {
        return {
            code: true
        };
    },
    SPAN: function(el) {
        return {
            text: el.textContent
        };
    },
    DEL: function() {
        return {
            strikethrough: true
        };
    },
    EM: function() {
        return {
            italic: true
        };
    },
    I: function() {
        return {
            italic: true
        };
    },
    S: function() {
        return {
            strikethrough: true
        };
    },
    STRONG: function() {
        return {
            bold: true
        };
    },
    B: function() {
        return {
            bold: true
        };
    }
};
export var deserialize = function(el) {
    var parentTag = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : '';
    if (el.nodeName.toLowerCase() === 'script') return [];
    if (el.nodeName.toLowerCase() === 'style') return [];
    if (el.nodeName.toLowerCase() === 'meta') return [];
    if (el.nodeName.toLowerCase() === 'link') return [];
    if (el.nodeName.toLowerCase() === 'head') return [];
    if (el.nodeName.toLowerCase() === 'colgroup') return [];
    if (el.nodeName.toLowerCase() === 'noscript') return [];
    if (el.nodeType === 3) {
        return el.textContent;
    } else if (el.nodeType !== 1) {
        return null;
    } else if (el.nodeName === 'BR') {
        return '\n';
    }
    var nodeName = el.nodeName;
    var target = el;
    if (nodeName === 'PRE' && el.childNodes[0] && el.childNodes[0].nodeName === 'CODE') {
        target = 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.textContent || ''
            }
        ];
    }
    if (fragment.has(el.nodeName.toLowerCase())) {
        return jsx('fragment', {}, children);
    }
    if (TEXT_TAGS[nodeName] && Array.from(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(el) {
    el.innerHTML = el.innerHTML.replace(/<br\/?>|<\/div>(?=\S)/g, '\n');
    return el.innerText;
};
var getTextsNode = function(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 = /*#__PURE__*/ function() {
    var _ref = _async_to_generator(function(blobUrl, fileName) {
        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
                    ];
            }
        });
    });
    return function blobToFile(blobUrl, fileName) {
        return _ref.apply(this, arguments);
    };
}();
/**
 * 分段处理文件上传，避免阻塞主线程
 */ var upLoadFileBatch = /*#__PURE__*/ function() {
    var _ref = _async_to_generator(function(fragmentList, editorProps) {
        var mediaFragments, collectMediaFragments, hideLoading, i, batch, progress, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    mediaFragments = [];
                    // 收集所有需要上传的媒体文件
                    collectMediaFragments = function(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 = message.loading("Uploading ".concat(mediaFragments.length, " files..."), 0);
                    _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(/*#__PURE__*/ function() {
                            var _ref = _async_to_generator(function(fragment) {
                                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
                                            ];
                                    }
                                });
                            });
                            return function(fragment) {
                                return _ref.apply(this, arguments);
                            };
                        }()))
                    ];
                case 3:
                    _state.sent();
                    // 更新进度
                    progress = Math.min((i + BATCH_SIZE) / mediaFragments.length * 100, 100);
                    hideLoading();
                    message.loading("Uploading ".concat(mediaFragments.length, " files... ").concat(Math.round(progress), "%"), 0);
                    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:
                    message.success('Upload completed');
                    return [
                        3,
                        9
                    ];
                case 7:
                    error = _state.sent();
                    console.error('文件上传失败:', error);
                    message.error('Some files failed to upload');
                    return [
                        3,
                        9
                    ];
                case 8:
                    hideLoading();
                    return [
                        7
                    ];
                case 9:
                    return [
                        2
                    ];
            }
        });
    });
    return function upLoadFileBatch(fragmentList, editorProps) {
        return _ref.apply(this, arguments);
    };
}();
/**
 * 分段插入节点，避免一次性插入大量内容导致卡顿
 */ var insertNodesBatch = /*#__PURE__*/ function() {
    var _ref = _async_to_generator(function(editor, nodes, at, options) {
        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
                    ];
            }
        });
    });
    return function insertNodesBatch(editor, nodes, at, options) {
        return _ref.apply(this, arguments);
    };
}();
/**
 * 优化的HTML解析函数，支持分段处理
 */ var parseHtmlOptimized = /*#__PURE__*/ function() {
    var _ref = _async_to_generator(function(html, rtf) {
        return _ts_generator(this, function(_state) {
            // 对于小内容，使用同步处理
            if (html.length < MAX_SYNC_SIZE) {
                return [
                    2,
                    docxDeserializer(rtf, html.trim())
                ];
            }
            // 对于大内容，使用异步处理
            return [
                2,
                new Promise(function(resolve) {
                    // 使用 requestIdleCallback 在空闲时间处理
                    var processInIdle = function() {
                        try {
                            var result = docxDeserializer(rtf, html.trim());
                            resolve(result);
                        } catch (error) {
                            console.error('HTML解析失败:', error);
                            resolve([]);
                        }
                    };
                    if ('requestIdleCallback' in window) {
                        requestIdleCallback(processInIdle, {
                            timeout: 1000
                        });
                    } else {
                        // 降级到 setTimeout
                        setTimeout(processInIdle, 0);
                    }
                })
            ];
        });
    });
    return function parseHtmlOptimized(html, rtf) {
        return _ref.apply(this, arguments);
    };
}();
/**
 * 转化 html 到 slate - 性能优化版本
 * @param editor
 * @param html
 * @returns
 */ export var htmlToFragmentList = function(html, rtl) {
    var fragmentList = docxDeserializer(rtl, html.trim());
    return 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;
    });
};
export var insertParsedHtmlNodes = /*#__PURE__*/ function() {
    var _ref = _async_to_generator(function(editor, html, editorProps, rtl) {
        var hideLoading, fragmentList, _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:
                    // 1. 基础检查
                    if (html.startsWith('<html>\r\n<body>\r\n\x3C!--StartFragment--><img src="')) {
                        return [
                            2,
                            false
                        ];
                    }
                    // 2. 显示解析提示
                    hideLoading = message.loading('parsing...', 0);
                    _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)) {
                        hideLoading();
                        return [
                            2,
                            false
                        ];
                    }
                    // 4. 异步处理文件上传
                    return [
                        4,
                        upLoadFileBatch(fragmentList, editorProps)
                    ];
                case 3:
                    _state.sent();
                    debugLog('wordFragmentList', fragmentList);
                    hideLoading();
                    // 5. 获取当前节点
                    _Editor_nodes = _sliced_to_array(Editor.nodes(editor, {
                        match: function(n) {
                            return Element.isElement(n);
                        }
                    }), 1), node = _Editor_nodes[0];
                    selection = editor.selection;
                    if (!(!selection || !Editor.hasPath(editor, selection.anchor.path))) return [
                        3,
                        5
                    ];
                    processedNodes = fragmentList === null || fragmentList === void 0 ? void 0 : fragmentList.map(function(item) {
                        if (!item.type) {
                            return {
                                type: 'paragraph',
                                children: [
                                    item
                                ]
                            };
                        }
                        return item;
                    });
                    return [
                        4,
                        insertNodesBatch(editor, processedNodes)
                    ];
                case 4:
                    _state.sent();
                    return [
                        2,
                        true
                    ];
                case 5:
                    // 7. 处理非折叠选区
                    if (!Range.isCollapsed(selection)) {
                        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(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]');
                    // 对于代码块，检查是否包含代码相关的标签
                    if ((node === null || node === void 0 ? void 0 : node[0].type) === 'code') {
                        hasCodeTags = html.includes('<pre>') || html.includes('<code>') || inner;
                        if (hasCodeTags) {
                            // 从 HTML 中提取纯文本内容
                            textContent = parsed.textContent || '';
                            if (textContent.trim()) {
                                Transforms.insertText(editor, textContent.trim(), {
                                    at: selection
                                });
                                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' && fragmentList[0].type === 'list')) return [
                        3,
                        12
                    ];
                    children = fragmentList[0].children || [];
                    if (!children.length) {
                        return [
                            2,
                            false
                        ];
                    }
                    _Editor_nodes2 = _sliced_to_array(Editor.nodes(editor, {
                        match: function(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 (!(fragmentList.length > 1)) return [
                        3,
                        11
                    ];
                    return [
                        4,
                        insertNodesBatch(editor, fragmentList.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(fragmentList), {
                            at: selection
                        });
                        return [
                            2,
                            true
                        ];
                    }
                    if (!((node === null || node === void 0 ? void 0 : node[0].type) === 'head')) return [
                        3,
                        15
                    ];
                    if (fragmentList[0].type) {
                        if (fragmentList[0].type !== 'paragraph') {
                            Transforms.insertNodes(editor, {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            }, {
                                at: selection,
                                select: true
                            });
                            return [
                                2,
                                true
                            ];
                        }
                        return [
                            2,
                            false
                        ];
                    }
                    texts = fragmentList.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 (fragmentList.length === 1 && (fragmentList[0].type === 'paragraph' || !fragmentList[0].type) && node) {
                        text = Node.string(fragmentList[0]);
                        if (text) {
                            Transforms.insertText(editor, text, {
                                at: selection
                            });
                            return [
                                2,
                                true
                            ];
                        }
                    }
                    // 14. 默认情况：替换选中节点
                    processedNodes1 = fragmentList === null || fragmentList === void 0 ? void 0 : fragmentList.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;
                    });
                    return [
                        4,
                        insertNodesBatch(editor, processedNodes1)
                    ];
                case 16:
                    _state.sent();
                    return [
                        2,
                        true
                    ];
                case 17:
                    error = _state.sent();
                    console.error('插入HTML节点失败:', error);
                    hideLoading();
                    message.error('Content parsing failed, please try again');
                    return [
                        2,
                        false
                    ];
                case 18:
                    return [
                        2
                    ];
            }
        });
    });
    return function insertParsedHtmlNodes(editor, html, editorProps, rtl) {
        return _ref.apply(this, arguments);
    };
}();
