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_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _async_iterator(iterable) {
    var method, async, sync, retry = 2;
    for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
        if (async && null != (method = iterable[async])) return method.call(iterable);
        if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
        async = "@@asyncIterator", sync = "@@iterator";
    }
    throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(s) {
    function AsyncFromSyncIteratorContinuation(r) {
        if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
        var done = r.done;
        return Promise.resolve(r.value).then(function(value) {
            return {
                value: value,
                done: done
            };
        });
    }
    return AsyncFromSyncIterator = function(s) {
        this.s = s, this.n = s.next;
    }, AsyncFromSyncIterator.prototype = {
        s: null,
        n: null,
        next: function() {
            return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
        },
        return: function(value) {
            var ret = this.s.return;
            return void 0 === ret ? Promise.resolve({
                value: value,
                done: !0
            }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
        },
        throw: function(value) {
            var thr = this.s.return;
            return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
        }
    }, new AsyncFromSyncIterator(s);
}
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 _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 _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
        };
    }
}
import { Editor, Element, Node, Path, Text, Transforms } from "slate";
import { isMarkdown } from "../utils";
import { getMediaType } from "../utils/dom";
import { EditorUtils } from "../utils/editorUtils";
import { isHtml } from "../utils/htmlToMarkdown";
import { toUnixPath } from "../utils/path";
import { insertParsedHtmlNodes } from "./insertParsedHtmlNodes";
import { parseMarkdownToNodesAndInsert } from "./parseMarkdownToNodesAndInsert";
var isValidSlateNode = function isValidSlateNode(node) {
    if (Element.isElement(node)) return true;
    if (Text.isText(node)) return true;
    return false;
};
/**
 * 处理粘贴的 Slate Markdown 片段
 */ export var handleSlateMarkdownFragment = function handleSlateMarkdownFragment(editor, clipboardData, currentTextSelection) {
    try {
        var encoded = clipboardData.getData('application/x-slate-md-fragment');
        var raw = JSON.parse(encoded || '[]');
        var parsed = (Array.isArray(raw) ? raw : []).filter(isValidSlateNode);
        var fragment = parsed.map(function(node) {
            if (Element.isElement(node) && node.type === 'card') {
                return _object_spread_props(_object_spread({}, node), {
                    children: [
                        {
                            type: 'card-before',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }
                    ].concat(_to_consumable_array(node.children), [
                        {
                            type: 'card-after',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }
                    ])
                });
            }
            return node;
        });
        if (fragment.length === 1 && (fragment === null || fragment === void 0 ? void 0 : fragment.at(0).type) === 'paragraph' && currentTextSelection) {
            var text = Node.string(fragment.at(0));
            if (text) {
                Transforms.insertText(editor, text, {
                    at: currentTextSelection.focus
                });
                return true;
            }
            return true;
        }
        if (fragment.length === 0) return true;
        EditorUtils.replaceSelectedNode(editor, fragment);
        return true;
    } catch (error) {
        console.log('error', error);
        return false;
    }
};
/**
 * 处理粘贴的 HTML 内容
 */ export var handleHtmlPaste = function handleHtmlPaste(editor, clipboardData, editorProps) {
    return _async_to_generator(function() {
        var html, rtf, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    _state.trys.push([
                        0,
                        5,
                        ,
                        6
                    ]);
                    return [
                        4,
                        clipboardData.getData('text/html')
                    ];
                case 1:
                    html = _state.sent();
                    return [
                        4,
                        clipboardData.getData('text/rtf')
                    ];
                case 2:
                    rtf = _state.sent();
                    if (!html) return [
                        3,
                        4
                    ];
                    return [
                        4,
                        insertParsedHtmlNodes(editor, html, editorProps, rtf)
                    ];
                case 3:
                    return [
                        2,
                        _state.sent()
                    ];
                case 4:
                    return [
                        2,
                        false
                    ];
                case 5:
                    error = _state.sent();
                    console.log('error', error);
                    return [
                        2,
                        false
                    ];
                case 6:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 处理粘贴的文件
 */ export var handleFilesPaste = function handleFilesPaste(editor, clipboardData, editorProps) {
    return _async_to_generator(function() {
        var _editorProps_image, fileList, _editor_selection_focus, _editor_selection, url, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, file, _editorProps_image1, serverUrl, err, selection, node, at, error, error1;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    _state.trys.push([
                        0,
                        17,
                        ,
                        18
                    ]);
                    fileList = clipboardData.files;
                    if (!(fileList.length > 0 && ((_editorProps_image = editorProps.image) === null || _editorProps_image === void 0 ? void 0 : _editorProps_image.upload))) return [
                        3,
                        16
                    ];
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        15,
                        ,
                        16
                    ]);
                    url = [];
                    _iteratorAbruptCompletion = false, _didIteratorError = false;
                    _state.label = 2;
                case 2:
                    _state.trys.push([
                        2,
                        8,
                        9,
                        14
                    ]);
                    _iterator = _async_iterator(fileList);
                    _state.label = 3;
                case 3:
                    return [
                        4,
                        _iterator.next()
                    ];
                case 4:
                    if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
                        3,
                        7
                    ];
                    _value = _step.value;
                    file = _value;
                    if (!((_editorProps_image1 = editorProps.image) === null || _editorProps_image1 === void 0 ? void 0 : _editorProps_image1.upload)) return [
                        3,
                        6
                    ];
                    return [
                        4,
                        editorProps.image.upload([
                            file
                        ])
                    ];
                case 5:
                    serverUrl = _state.sent();
                    url.push(serverUrl);
                    _state.label = 6;
                case 6:
                    _iteratorAbruptCompletion = false;
                    return [
                        3,
                        3
                    ];
                case 7:
                    return [
                        3,
                        14
                    ];
                case 8:
                    err = _state.sent();
                    _didIteratorError = true;
                    _iteratorError = err;
                    return [
                        3,
                        14
                    ];
                case 9:
                    _state.trys.push([
                        9,
                        ,
                        12,
                        13
                    ]);
                    if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
                        3,
                        11
                    ];
                    return [
                        4,
                        _iterator.return()
                    ];
                case 10:
                    _state.sent();
                    _state.label = 11;
                case 11:
                    return [
                        3,
                        13
                    ];
                case 12:
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                    return [
                        7
                    ];
                case 13:
                    return [
                        7
                    ];
                case 14:
                    selection = editor === null || editor === void 0 ? void 0 : (_editor_selection = editor.selection) === null || _editor_selection === void 0 ? void 0 : (_editor_selection_focus = _editor_selection.focus) === null || _editor_selection_focus === void 0 ? void 0 : _editor_selection_focus.path;
                    node = selection ? Node.get(editor, Path.parent(selection)) : null;
                    at = selection ? EditorUtils.findNext(editor, selection) : undefined;
                    [
                        url
                    ].flat(2).forEach(function(u) {
                        if (!u) return null;
                        Transforms.insertNodes(editor, EditorUtils.createMediaNode(u, 'image'), {
                            at: _to_consumable_array(node && node.type === 'table-cell' ? selection : at ? at : [
                                editor.children.length - 1
                            ])
                        });
                    });
                    return [
                        2,
                        true
                    ];
                case 15:
                    error = _state.sent();
                    console.log('error', error);
                    return [
                        2,
                        false
                    ];
                case 16:
                    return [
                        2,
                        false
                    ];
                case 17:
                    error1 = _state.sent();
                    console.log('error', error1);
                    return [
                        2,
                        false
                    ];
                case 18:
                    return [
                        2
                    ];
            }
        });
    })();
};
/**
 * 处理特殊文本格式（media:// 和 attach:// 链接）
 */ export var handleSpecialTextPaste = function handleSpecialTextPaste(editor, text, selection) {
    if (text.startsWith('media://') || text.startsWith('attach://')) {
        var path = EditorUtils.findMediaInsertPath(editor);
        var urlObject = new URL(text);
        var url = urlObject.searchParams.get('url');
        if (url && !url.startsWith('http') && !url.startsWith('blob:http')) {
            url = toUnixPath(url);
        }
        if (path && url) {
            if (text.startsWith('media://')) {
                Editor.withoutNormalizing(editor, function() {
                    Transforms.insertNodes(editor, EditorUtils.createMediaNode(url, 'image'), {
                        select: true,
                        at: path
                    });
                    var next = Editor.next(editor, {
                        at: path
                    });
                    if (next && next[0].type === 'paragraph' && !Node.string(next[0])) {
                        Transforms.delete(editor, {
                            at: selection
                        });
                    }
                });
                return true;
            }
            if (text.startsWith('attach://')) {
                Editor.withoutNormalizing(editor, function() {
                    Transforms.insertNodes(editor, {
                        type: 'attach',
                        name: urlObject.searchParams.get('name'),
                        size: Number(urlObject.searchParams.get('size') || 0),
                        url: url || undefined,
                        children: [
                            {
                                text: ''
                            }
                        ]
                    }, {
                        select: true,
                        at: path
                    });
                    var next = Editor.next(editor, {
                        at: path
                    });
                    if (next && next[0].type === 'paragraph' && !Node.string(next[0])) {
                        Transforms.delete(editor, {
                            at: selection
                        });
                    }
                });
                return true;
            }
        }
    }
    return false;
};
/**
 * 处理 HTTP 链接
 */ export var handleHttpLinkPaste = function handleHttpLinkPaste(editor, text, selection, store) {
    if (text.startsWith('http')) {
        // 添加更严格的URL类型判断，避免误识别
        var mediaType = getMediaType(text);
        // 检查是否为明确的媒体类型
        if ([
            'image',
            'video',
            'audio'
        ].includes(mediaType)) {
            // 进一步验证URL是否真的包含媒体文件
            var isValidMediaUrl = function isValidMediaUrl(url, type) {
                if (!url) return false;
                // 检查是否为blob URL或data URL
                if (url.startsWith('blob:') || url.startsWith('data:')) {
                    return true;
                }
                // 根据媒体类型检查文件扩展名
                var mediaExtensions = {
                    image: [
                        '.jpg',
                        '.jpeg',
                        '.png',
                        '.gif',
                        '.svg',
                        '.webp',
                        '.bmp',
                        '.ico'
                    ],
                    video: [
                        '.mp4',
                        '.webm',
                        '.ogg',
                        '.avi',
                        '.mov',
                        '.wmv',
                        '.flv'
                    ],
                    audio: [
                        '.mp3',
                        '.wav',
                        '.ogg',
                        '.aac',
                        '.m4a',
                        '.flac'
                    ]
                };
                var extensions = mediaExtensions[type] || [];
                var hasValidExtension = extensions.some(function(ext) {
                    return url.toLowerCase().includes(ext);
                });
                // 检查URL是否包含媒体相关的路径
                var mediaPaths = {
                    image: [
                        '/image',
                        '/img',
                        '/photo',
                        '/picture',
                        '/avatar',
                        '/icon'
                    ],
                    video: [
                        '/video',
                        '/media',
                        '/movie',
                        '/clip'
                    ],
                    audio: [
                        '/audio',
                        '/music',
                        '/sound',
                        '/voice'
                    ]
                };
                var paths = mediaPaths[type] || [];
                var hasMediaPath = paths.some(function(path) {
                    return url.toLowerCase().includes(path);
                });
                return hasValidExtension || hasMediaPath;
            };
            // 只有当URL确实是媒体文件时才作为媒体处理
            if (isValidMediaUrl(text, mediaType)) {
                var path = EditorUtils.findMediaInsertPath(editor);
                if (!path) return false;
                Transforms.insertNodes(editor, EditorUtils.createMediaNode(text, 'image'), {
                    select: true,
                    at: selection
                });
                return true;
            }
        }
        // 如果不是明确的媒体文件，或者验证失败，则作为链接处理
        store.insertLink(text);
        return true;
    }
    return false;
};
/**
 * 处理普通文本粘贴
 */ export var handlePlainTextPaste = function handlePlainTextPaste(editor, text, selection, plugins) {
    return _async_to_generator(function() {
        var success;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (!isMarkdown(text)) return [
                        3,
                        2
                    ];
                    return [
                        4,
                        parseMarkdownToNodesAndInsert(editor, text, plugins)
                    ];
                case 1:
                    _state.sent();
                    return [
                        2,
                        true
                    ];
                case 2:
                    if (!isHtml(text)) return [
                        3,
                        4
                    ];
                    return [
                        4,
                        insertParsedHtmlNodes(editor, text, plugins, '')
                    ];
                case 3:
                    success = _state.sent();
                    if (success) return [
                        2,
                        true
                    ];
                    _state.label = 4;
                case 4:
                    if (selection) {
                        Transforms.insertText(editor, text, {
                            at: selection
                        });
                    } else {
                        Transforms.insertNodes(editor, [
                            {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: text
                                    }
                                ]
                            }
                        ]);
                    }
                    return [
                        2,
                        true
                    ];
            }
        });
    })();
};
/**
 * 检查是否需要直接插入文本（在特定节点类型中）
 */ export var shouldInsertTextDirectly = function shouldInsertTextDirectly(editor, selection) {
    if (!(selection === null || selection === void 0 ? void 0 : selection.focus)) return false;
    var rangeNodes = Editor === null || Editor === void 0 ? void 0 : Editor.node(editor, [
        selection.focus.path.at(0)
    ]);
    if (!rangeNodes) return false;
    var rangeNode = rangeNodes.at(0);
    return [
        'table-cell',
        'table-row',
        'table',
        'code',
        'schema',
        'apaasify',
        'agentic-ui-task',
        'agentic-ui-toolusebar',
        'agentic-ui-usertoolbar',
        'agentic-ui-filemap'
    ].includes(rangeNode.type);
};
/**
 * 处理标签节点的粘贴
 */ export var handleTagNodePaste = function handleTagNodePaste(editor, currentTextSelection, clipboardData, curNode) {
    if (curNode === null || curNode === void 0 ? void 0 : curNode.tag) {
        var text = clipboardData.getData('text/plain');
        if (text) {
            Transforms.insertText(editor, text, {
                at: currentTextSelection.focus
            });
            return true;
        }
    }
    return false;
};
