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
        };
    }
}
import { CheckSquareOutlined, CodeOutlined, FontSizeOutlined, OrderedListOutlined, PlayCircleOutlined, TableOutlined, UnorderedListOutlined } from "@ant-design/icons";
import { Button, ConfigProvider, Input, Menu, Tabs } from "antd";
import classNames from "clsx";
import isHotkey from "is-hotkey";
import React, { useCallback, useContext, useEffect, useMemo, useRef } from "react";
import ReactDOM from "react-dom";
import { Editor, Element, Node, Transforms } from "slate";
import { ReactEditor } from "slate-react";
import { I18nContext } from "../../../I18n";
import { useSubject } from "../../hooks/subscribe";
import { selChange$ } from "../plugins/useOnchange";
import { useEditorStore } from "../store";
import { getOffsetLeft } from "../utils/dom";
import { EditorUtils } from "../utils/editorUtils";
import { getRemoteMediaType } from "../utils/media";
import { useLocalState } from "../utils/useLocalState";
import { useStyle } from "./insertAutocompleteStyle";
var ImageIcon = function ImageIcon() {
    return /*#__PURE__*/ React.createElement("svg", {
        className: "ant-menu-item-icon",
        viewBox: "0 0 1024 1024",
        version: "1.1",
        width: "1em",
        height: "1em"
    }, /*#__PURE__*/ React.createElement("path", {
        fill: "currentColor",
        d: "M0 128l0 768 1024 0L1024 128 0 128zM944 816 80 816 80 208l864 0L944 816zM704 368c0 53.024 42.976 96 96 96 53.024 0 96-42.976 96-96 0-53.024-42.976-96-96-96C746.976 272 704 314.976 704 368M888 760l-192-288-128 96-240-304-192 496L888 760z"
    }));
};
var Quote = function Quote() {
    return /*#__PURE__*/ React.createElement("svg", {
        className: "ant-menu-item-icon",
        viewBox: "0 0 1024 1024",
        version: "1.1",
        width: "1em",
        height: "1em"
    }, /*#__PURE__*/ React.createElement("path", {
        d: "M128 472.896h341.344v341.344H128zM128 472.896L272.096 192h110.08l-144.128 280.896z",
        fill: "currentColor"
    }), /*#__PURE__*/ React.createElement("path", {
        d: "M544 472.896h341.344v341.344H544zM544 472.896L688.096 192h110.08l-144.128 280.896z",
        fill: "currentColor"
    }));
};
var replaceUrl = [
    {
        reg: /https?:\/\/youtu.be\/([\w-]+)(\?si=\w+)?/i,
        replace: function replace(match) {
            return "https://www.youtube.com/embed/".concat(match[1]).concat(match[2] || '');
        }
    },
    {
        reg: /https?:\/\/www.bilibili.com\/video\/([\w-]+)\/?/,
        replace: function replace(match) {
            return "https://player.bilibili.com/player.html?isOutside=true&bvid=".concat(match[1]);
        }
    },
    {
        reg: /src=["']([^"\n]+)["']/i,
        replace: function replace(match) {
            return match[1];
        }
    }
];
export var getInsertOptions = function getInsertOptions(ctx, locale) {
    var options = [
        {
            label: [
                '元素',
                'Elements'
            ],
            key: 'element',
            children: [
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.table) || '表格'
                    ],
                    key: 'table',
                    task: 'insertTable',
                    icon: /*#__PURE__*/ React.createElement(TableOutlined, null)
                },
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.quote) || '引用'
                    ],
                    key: 'quote',
                    task: 'insertQuote',
                    icon: /*#__PURE__*/ React.createElement(Quote, null)
                },
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.code) || '代码'
                    ],
                    key: 'code',
                    task: 'insertCode',
                    icon: /*#__PURE__*/ React.createElement(CodeOutlined, null)
                }
            ]
        },
        {
            label: [
                '媒体',
                'media'
            ],
            key: 'media',
            children: [
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.localeImage) || '本地图片'
                    ],
                    task: 'uploadImage',
                    key: 'localeImage',
                    args: [
                        '',
                        true
                    ],
                    icon: /*#__PURE__*/ React.createElement(ImageIcon, null)
                }
            ]
        },
        {
            label: [
                '列表',
                'List'
            ],
            key: 'list',
            children: [
                {
                    label: [
                        locale['b-list'] || '无序列表'
                    ],
                    task: 'list',
                    key: 'b-list',
                    args: [
                        'unordered'
                    ],
                    icon: /*#__PURE__*/ React.createElement(UnorderedListOutlined, null)
                },
                {
                    label: [
                        locale['n-list'] || '有序列表'
                    ],
                    task: 'list',
                    key: 'n-list',
                    args: [
                        'ordered'
                    ],
                    icon: /*#__PURE__*/ React.createElement(OrderedListOutlined, null)
                },
                {
                    label: [
                        locale['t-list'] || '任务列表'
                    ],
                    task: 'list',
                    key: 't-list',
                    args: [
                        'task'
                    ],
                    icon: /*#__PURE__*/ React.createElement(CheckSquareOutlined, null)
                }
            ]
        }
    ];
    if (ctx.isTop) {
        options.splice(2, 0, {
            label: [
                '标题',
                'Heading'
            ],
            key: 'head',
            children: [
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.head1) || '主标题'
                    ],
                    task: 'head',
                    key: 'head1',
                    args: [
                        1
                    ],
                    icon: /*#__PURE__*/ React.createElement(FontSizeOutlined, null)
                },
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.head2) || '段标题'
                    ],
                    task: 'head',
                    key: 'head2',
                    icon: /*#__PURE__*/ React.createElement(FontSizeOutlined, null),
                    args: [
                        2
                    ]
                },
                {
                    label: [
                        (locale === null || locale === void 0 ? void 0 : locale.head3) || '小标题'
                    ],
                    task: 'head',
                    key: 'head3',
                    icon: /*#__PURE__*/ React.createElement(FontSizeOutlined, null),
                    args: [
                        3
                    ]
                }
            ]
        });
    }
    return options;
};
export var InsertAutocomplete = function InsertAutocomplete(props) {
    var _props_optionsRender;
    var _useEditorStore = useEditorStore(), markdownEditorRef = _useEditorStore.markdownEditorRef, markdownContainerRef = _useEditorStore.markdownContainerRef, openInsertCompletion = _useEditorStore.openInsertCompletion, setOpenInsertCompletion = _useEditorStore.setOpenInsertCompletion, keyTask$ = _useEditorStore.keyTask$, insertCompletionText$ = _useEditorStore.insertCompletionText$;
    var dom = useRef(null);
    var ctx = useRef({
        path: [],
        isTop: true
    });
    var _useLocalState = _sliced_to_array(useLocalState({
        index: 0,
        filterOptions: [],
        options: [],
        left: 0,
        insertLink: false,
        insertAttachment: false,
        loading: false,
        insertUrl: '',
        top: 0,
        bottom: 0,
        text: ''
    }), 2), state = _useLocalState[0], setState = _useLocalState[1];
    var clickClose = useCallback(function(e) {
        var _dom_current;
        if (!((_dom_current = dom.current) === null || _dom_current === void 0 ? void 0 : _dom_current.contains(e.target))) {
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            close();
        }
    }, []);
    var close = useCallback(function() {
        setState({
            filterOptions: [],
            options: [],
            index: 0,
            text: '',
            insertLink: false,
            insertAttachment: false,
            insertUrl: ''
        });
        if (typeof window === 'undefined') return;
        window.removeEventListener('click', clickClose);
    }, []);
    var runInsertTask = useCallback(function(op, params) {
        return _async_to_generator(function() {
            var _props_runInsertTask;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!(params === null || params === void 0 ? void 0 : params.isCustom)) return [
                            3,
                            2
                        ];
                        Transforms.delete(markdownEditorRef.current, {
                            at: ctx.current.path
                        });
                        return [
                            4,
                            (_props_runInsertTask = props.runInsertTask) === null || _props_runInsertTask === void 0 ? void 0 : _props_runInsertTask.call(props, op, {
                                x: state.left,
                                y: state.top || state.bottom || 0
                            })
                        ];
                    case 1:
                        _state.sent();
                        if (typeof window === 'undefined') return [
                            2
                        ];
                        if (typeof window.matchMedia === 'undefined') return [
                            2
                        ];
                        setOpenInsertCompletion === null || setOpenInsertCompletion === void 0 ? void 0 : setOpenInsertCompletion(false);
                        close();
                        return [
                            2
                        ];
                    case 2:
                        //@ts-ignore
                        if (op.task === 'image' || op.task === 'attachment') {
                            //@ts-ignore
                            if (op.task === 'image') {
                                setState({
                                    insertLink: true
                                });
                                setTimeout(function() {
                                    var _dom_current_querySelector, _dom_current;
                                    (_dom_current = dom.current) === null || _dom_current === void 0 ? void 0 : (_dom_current_querySelector = _dom_current.querySelector('input')) === null || _dom_current_querySelector === void 0 ? void 0 : _dom_current_querySelector.focus();
                                }, 30);
                            } else {
                                setState({
                                    insertAttachment: true
                                });
                            }
                        } else if (op) {
                            Transforms.insertText(markdownEditorRef.current, '', {
                                at: {
                                    anchor: Editor.start(markdownEditorRef.current, ctx.current.path),
                                    focus: Editor.end(markdownEditorRef.current, ctx.current.path)
                                }
                            });
                            keyTask$.next({
                                key: op.task,
                                args: op.args
                            });
                            if (typeof window === 'undefined') return [
                                2
                            ];
                            if (typeof window.matchMedia === 'undefined') return [
                                2
                            ];
                            setOpenInsertCompletion === null || setOpenInsertCompletion === void 0 ? void 0 : setOpenInsertCompletion(false);
                            close();
                        }
                        return [
                            2
                        ];
                }
            });
        })();
    }, []);
    var insertAttachByLink = useCallback(function() {
        return _async_to_generator(function() {
            var url, size, name, res, match, node, next, _Editor_nodes, m;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        setState({
                            loading: true
                        });
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            ,
                            4,
                            5
                        ]);
                        url = state.insertUrl;
                        size = 0;
                        name = url;
                        if (!/^https?:\/\//.test(url)) return [
                            3,
                            3
                        ];
                        return [
                            4,
                            fetch(url)
                        ];
                    case 2:
                        res = _state.sent();
                        if (!res.ok) {
                            throw new Error();
                        }
                        size = Number(res.headers.get('content-length') || 0);
                        match = url.match(/([\w_-]+)\.\w+$/);
                        if (match) {
                            name = match[1];
                        }
                        _state.label = 3;
                    case 3:
                        Transforms.insertText(markdownEditorRef.current, '', {
                            at: {
                                anchor: Editor.start(markdownEditorRef.current, ctx.current.path),
                                focus: Editor.end(markdownEditorRef.current, ctx.current.path)
                            }
                        });
                        node = {
                            type: 'attach',
                            name: name,
                            url: url,
                            size: size,
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        };
                        Transforms.setNodes(markdownEditorRef.current, node, {
                            at: ctx.current.path
                        });
                        EditorUtils.focus(markdownEditorRef.current);
                        next = Editor.next(markdownEditorRef.current, {
                            at: ctx.current.path
                        });
                        if ((next === null || next === void 0 ? void 0 : next[0].type) === 'paragraph' && !Node.string(next[0])) {
                            Transforms.delete(markdownEditorRef.current, {
                                at: next[1]
                            });
                        }
                        _Editor_nodes = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                            match: function match(n) {
                                return !!n.type;
                            },
                            mode: 'lowest'
                        }), 1), m = _Editor_nodes[0];
                        selChange$.next({
                            node: m,
                            sel: markdownEditorRef.current.selection
                        });
                        close();
                        return [
                            3,
                            5
                        ];
                    case 4:
                        setState({
                            loading: false
                        });
                        return [
                            7
                        ];
                    case 5:
                        return [
                            2
                        ];
                }
            });
        })();
    }, []);
    var keydown = useCallback(function(e) {
        if (state.options.length && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
            e.preventDefault();
            if (e.key === 'ArrowUp' && state.index > 0) {
                setState({
                    index: state.index - 1
                });
                var key = state.options[state.index].key;
                var target = document.querySelector('[data-action="'.concat(key, '"]'));
                if (target && dom.current.scrollTop > target.offsetTop) {
                    dom.current.scroll({
                        top: dom.current.scrollTop - 160 + 30
                    });
                }
            }
            if (e.key === 'ArrowDown' && state.index < state.options.length - 1) {
                setState({
                    index: state.index + 1
                });
                var key1 = state.options[state.index].key;
                var target1 = document.querySelector('[data-action="'.concat(key1, '"]'));
                if (target1 && target1.offsetTop > dom.current.scrollTop + dom.current.clientHeight - 30) {
                    dom.current.scroll({
                        top: target1.offsetTop - 30
                    });
                }
            }
        }
        if (e.key === 'Enter' && openInsertCompletion) {
            var op = state.options[state.index];
            if (op) {
                e.preventDefault();
                e.stopPropagation();
                runInsertTask(op);
            }
        }
        if (isHotkey('esc', e)) {
            setOpenInsertCompletion === null || setOpenInsertCompletion === void 0 ? void 0 : setOpenInsertCompletion(false);
            EditorUtils.focus(markdownEditorRef.current);
        }
        if (isHotkey('backspace', e)) {
            setOpenInsertCompletion === null || setOpenInsertCompletion === void 0 ? void 0 : setOpenInsertCompletion(false);
            EditorUtils.focus(markdownEditorRef.current);
        }
    }, []);
    var i18n = useContext(I18nContext);
    var insertOptions = useMemo(function() {
        return getInsertOptions({
            isTop: ctx.current.isTop
        }, i18n.locale);
    }, [
        i18n.locale,
        ctx.current.isTop
    ]);
    /**
   * 插入媒体
   */ var insertMedia = useCallback(function() {
        return _async_to_generator(function() {
            var url, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, r, m, type, node, _Editor_nodes, n;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        setState({
                            loading: true
                        });
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            ,
                            3,
                            4
                        ]);
                        url = state.insertUrl;
                        _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                        try {
                            for(_iterator = replaceUrl[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                                r = _step.value;
                                m = url.match(r.reg);
                                if (m) {
                                    url = r.replace(m);
                                    break;
                                }
                            }
                        } catch (err) {
                            _didIteratorError = true;
                            _iteratorError = err;
                        } finally{
                            try {
                                if (!_iteratorNormalCompletion && _iterator.return != null) {
                                    _iterator.return();
                                }
                            } finally{
                                if (_didIteratorError) {
                                    throw _iteratorError;
                                }
                            }
                        }
                        if (!/^(\w+:)?\/\//.test(url)) {
                            throw new Error();
                        }
                        return [
                            4,
                            getRemoteMediaType(url)
                        ];
                    case 2:
                        type = _state.sent();
                        if (!type) {
                            throw new Error();
                        }
                        Transforms.insertText(markdownEditorRef.current, '', {
                            at: {
                                anchor: Editor.start(markdownEditorRef.current, ctx.current.path),
                                focus: Editor.end(markdownEditorRef.current, ctx.current.path)
                            }
                        });
                        node = EditorUtils.createMediaNode(url, 'image', {});
                        Transforms.setNodes(markdownEditorRef.current, node, {
                            at: ctx.current.path
                        });
                        EditorUtils.focus(markdownEditorRef.current);
                        _Editor_nodes = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                            match: function match(n) {
                                return !!n.type;
                            },
                            mode: 'lowest'
                        }), 1), n = _Editor_nodes[0];
                        selChange$.next({
                            sel: markdownEditorRef.current.selection,
                            node: n
                        });
                        close();
                        return [
                            3,
                            4
                        ];
                    case 3:
                        setState({
                            loading: false
                        });
                        return [
                            7
                        ];
                    case 4:
                        return [
                            2
                        ];
                }
            });
        })();
    }, []);
    useSubject(insertCompletionText$, function(text) {
        var _props_insertOptions;
        var tempText = text || '';
        var filterOptions = [];
        var options = [];
        if (tempText) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = insertOptions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var item = _step.value;
                    var _options;
                    var ops = item.children.filter(function(op) {
                        return op.label.some(function(l) {
                            return l.toLowerCase().includes(tempText.toLowerCase());
                        });
                    });
                    (_options = options).push.apply(_options, _to_consumable_array(ops));
                    if (ops.length) {
                        filterOptions.push(_object_spread_props(_object_spread({}, item), {
                            children: ops
                        }));
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
        } else {
            filterOptions = insertOptions;
            options = insertOptions.reduce(function(a, b) {
                return a.concat(b.children);
            }, []);
        }
        if (props.insertOptions && (props === null || props === void 0 ? void 0 : (_props_insertOptions = props.insertOptions) === null || _props_insertOptions === void 0 ? void 0 : _props_insertOptions.length)) {
            filterOptions.unshift({
                label: [
                    '快捷设置',
                    'My Quick'
                ],
                key: 'quick',
                children: _to_consumable_array(props.insertOptions)
            });
        }
        setState({
            index: 0,
            text: tempText,
            options: options,
            filterOptions: filterOptions
        });
    });
    useEffect(function() {
        var calculatePosition = function calculatePosition(nodeEl, containerEl) {
            var top = nodeEl.getBoundingClientRect().top;
            var left = getOffsetLeft(nodeEl, containerEl) + 24;
            var containerScrollTop = containerEl.scrollTop;
            var containerHeight = document.documentElement.clientHeight;
            var nodeHeight = nodeEl.clientHeight;
            var nodeTopRelativeToContainer = top - containerScrollTop;
            var nodeBottomRelativeToContainer = nodeTopRelativeToContainer + nodeHeight;
            var spaceAbove = nodeTopRelativeToContainer;
            var spaceBelow = containerHeight - nodeBottomRelativeToContainer;
            // 当节点上方空间不足，且下方空间不足时，触底显示
            if (spaceBelow < 212 && spaceAbove < 212) {
                return {
                    top: undefined,
                    bottom: 0,
                    left: left
                };
            }
            // 如果节点下方空间不足但上方有足够空间，显示在上方
            if (spaceBelow < 212 && spaceAbove >= 212) {
                return {
                    top: undefined,
                    bottom: containerHeight - nodeTopRelativeToContainer,
                    left: left
                };
            }
            // 默认逻辑，优先显示在下方
            if (spaceBelow >= 212) {
                return {
                    top: nodeBottomRelativeToContainer,
                    bottom: undefined,
                    left: left
                };
            }
            return undefined;
        };
        var setupEventListeners = function setupEventListeners() {
            var _markdownContainerRef_current, _markdownContainerRef_current1;
            if (typeof window === 'undefined') return;
            markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.addEventListener('keydown', keydown);
            markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current1 = markdownContainerRef.current) === null || _markdownContainerRef_current1 === void 0 ? void 0 : _markdownContainerRef_current1.addEventListener('click', clickClose);
        };
        var removeEventListeners = function removeEventListeners() {
            var _markdownContainerRef_current, _markdownContainerRef_current1;
            if (typeof window === 'undefined') return;
            markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.removeEventListener('keydown', keydown);
            markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current1 = markdownContainerRef.current) === null || _markdownContainerRef_current1 === void 0 ? void 0 : _markdownContainerRef_current1.removeEventListener('click', clickClose);
        };
        if (openInsertCompletion) {
            var _Editor_nodes = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                match: function match(n) {
                    return Element.isElement(n);
                },
                mode: 'lowest'
            }), 1), node = _Editor_nodes[0];
            if (node) {
                var _node_;
                ctx.current = {
                    path: node[1],
                    isTop: EditorUtils.isTop(markdownEditorRef.current, node[1])
                };
                if ((node === null || node === void 0 ? void 0 : (_node_ = node[0]) === null || _node_ === void 0 ? void 0 : _node_.type) === 'paragraph') {
                    var el = ReactEditor.toDOMNode(markdownEditorRef.current, node[0]);
                    if (el) {
                        var position = calculatePosition(el, document.body);
                        if (position) {
                            setState(position);
                        } else {
                            setState({
                                top: 0,
                                left: 0,
                                bottom: undefined
                            });
                        }
                    }
                }
                setupEventListeners();
                setTimeout(function() {
                    if (dom.current && typeof dom.current.scroll === 'function') {
                        dom.current.scroll({
                            top: 0
                        });
                    }
                });
            }
        } else {
            removeEventListeners();
            close();
        }
        return function() {
            removeEventListeners();
        };
    }, [
        openInsertCompletion
    ]);
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls("agentic-md-editor-insert-autocomplete");
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    return /*#__PURE__*/ ReactDOM.createPortal(wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: dom,
        className: classNames(baseClassName, hashId),
        style: {
            position: 'absolute',
            zIndex: 9999,
            display: !openInsertCompletion || !state.filterOptions.length ? 'none' : 'flex',
            width: state.insertLink || state.insertAttachment ? 320 : undefined,
            maxHeight: 212,
            overflowY: 'auto',
            left: state.left,
            top: state.top,
            bottom: state.bottom
        },
        onMouseDown: function onMouseDown(e) {
            e.preventDefault();
        }
    }, !state.insertLink && !state.insertAttachment && /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(Menu, {
        items: (_props_optionsRender = props.optionsRender) === null || _props_optionsRender === void 0 ? void 0 : _props_optionsRender.call(props, state.filterOptions.map(function(l) {
            var _l_label, _l_children_, _l_children, _l_children1;
            return {
                label: l === null || l === void 0 ? void 0 : (_l_label = l.label) === null || _l_label === void 0 ? void 0 : _l_label[1],
                key: l === null || l === void 0 ? void 0 : l.key,
                icon: l === null || l === void 0 ? void 0 : (_l_children = l.children) === null || _l_children === void 0 ? void 0 : (_l_children_ = _l_children[0]) === null || _l_children_ === void 0 ? void 0 : _l_children_.icon,
                children: l === null || l === void 0 ? void 0 : (_l_children1 = l.children) === null || _l_children1 === void 0 ? void 0 : _l_children1.map(function(el) {
                    var _el_label;
                    return {
                        label: (_el_label = el.label) === null || _el_label === void 0 ? void 0 : _el_label[1],
                        key: el.key,
                        icon: el.icon,
                        onClick: function onClick(_) {
                            var _props_insertOptions_find, _props_insertOptions;
                            _.domEvent.stopPropagation();
                            _.domEvent.preventDefault();
                            var task = insertOptions.map(function(o) {
                                return o === null || o === void 0 ? void 0 : o.children;
                            }).flat(1).find(function(o) {
                                return o.key === el.key;
                            });
                            var myInsertOptions = props === null || props === void 0 ? void 0 : (_props_insertOptions = props.insertOptions) === null || _props_insertOptions === void 0 ? void 0 : (_props_insertOptions_find = _props_insertOptions.find) === null || _props_insertOptions_find === void 0 ? void 0 : _props_insertOptions_find.call(_props_insertOptions, function(o) {
                                return o.key === el.key;
                            });
                            if (myInsertOptions) {
                                runInsertTask(myInsertOptions, {
                                    isCustom: true
                                });
                                return;
                            }
                            if (task) {
                                runInsertTask(task);
                            }
                        }
                    };
                })
            };
        }).map(function(l) {
            return l === null || l === void 0 ? void 0 : l.children;
        }).flat(1) || [])
    })), state.insertLink && /*#__PURE__*/ React.createElement("div", {
        style: {
            padding: 8
        }
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            fontSize: '1em',
            color: 'rgba(0,0,0,0.8)',
            marginBottom: 4,
            display: 'flex',
            alignContent: 'center',
            gap: 4
        }
    }, /*#__PURE__*/ React.createElement(PlayCircleOutlined, null), /*#__PURE__*/ React.createElement("span", null, "Embed media links")), /*#__PURE__*/ React.createElement(Input, {
        placeholder: 'Paste media link',
        onMouseDown: function onMouseDown(e) {
            return e.stopPropagation();
        },
        value: state.insertUrl,
        onKeyDown: function onKeyDown(e) {
            if (isHotkey('enter', e)) {
                insertMedia();
            }
        },
        onChange: function onChange(e) {
            return setState({
                insertUrl: e.target.value
            });
        }
    }), /*#__PURE__*/ React.createElement(Button, {
        block: true,
        loading: state.loading,
        type: 'primary',
        size: 'small',
        style: {
            marginTop: '1em'
        },
        onClick: insertMedia,
        disabled: !state.insertUrl
    }, "Embed")), state.insertAttachment && /*#__PURE__*/ React.createElement("div", {
        style: {
            width: 320,
            padding: 8
        }
    }, /*#__PURE__*/ React.createElement(Tabs, {
        size: 'small',
        items: [
            {
                label: 'Local',
                key: 'local',
                children: /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(Button, {
                    block: true,
                    size: 'small',
                    type: 'primary',
                    onClick: function onClick() {
                        Transforms.insertText(markdownEditorRef.current, '', {
                            at: {
                                anchor: Editor.start(markdownEditorRef.current, ctx.current.path),
                                focus: Editor.end(markdownEditorRef.current, ctx.current.path)
                            }
                        });
                        setState({
                            insertUrl: ''
                        });
                        insertAttachByLink();
                    }
                }, "Choose a file"))
            },
            {
                label: 'Embed Link',
                key: 'embed',
                children: /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(Input, {
                    placeholder: 'Paste attachment link',
                    onMouseDown: function onMouseDown(e) {
                        return e.stopPropagation();
                    },
                    value: state.insertUrl,
                    onKeyDown: function onKeyDown(e) {
                        if (isHotkey('enter', e)) {
                            insertAttachByLink();
                        }
                    },
                    onChange: function onChange(e) {
                        return setState({
                            insertUrl: e.target.value
                        });
                    }
                }), /*#__PURE__*/ React.createElement(Button, {
                    block: true,
                    loading: state.loading,
                    type: 'primary',
                    style: {
                        marginTop: '1em'
                    },
                    size: 'small',
                    onClick: insertAttachByLink,
                    disabled: !state.insertUrl
                }, "Embed"))
            }
        ]
    })))), document.body);
};
