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 _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 _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 _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);
}
/* eslint-disable @typescript-eslint/no-use-before-define */ import { DeleteOutlined } from "@ant-design/icons";
import { Input, Modal, Tooltip } from "antd";
import React, { useContext, useRef } from "react";
import { Text, Transforms } from "slate";
import { useRefFunction } from "../../../Hooks/useRefFunction";
import { I18nContext } from "../../../I18n";
import { useSubject } from "../../hooks/subscribe";
import { useEditorStore } from "../store";
import { useGetSetState } from "../utils";
import { EditorUtils } from "../utils/editorUtils";
import { isLink, parsePath } from "../utils/path";
/**
 * 插入链接组件
 *
 * 该组件提供在 Markdown 编辑器中插入和编辑链接的功能。
 * 支持多种链接插入方式：
 * - 手动输入链接URL
 * - 从文档列表中选择内部链接
 * - 自动检测和转换选中文本为链接
 * - 支持锚点链接和相对路径
 *
 * 功能特性：
 * - 模态框界面，用户体验友好
 * - 实时链接验证和预览
 * - 支持删除现有链接
 * - 智能文本选择和替换
 * - 国际化支持
 * - 键盘快捷键支持
 *
 * @returns 插入链接的模态框组件，如果未打开则返回null
 *
 * @example
 * ```tsx
 * // 组件会自动监听编辑器的 openInsertLink$ 事件
 * <InsertLink />
 * ```
 *
 * @remarks
 * - 组件通过 `useSubject` 监听 `store.openInsertLink$` 事件
 * - 使用 `useGetSetState` 管理模态框状态
 * - 支持通过 EditorUtils 操作 Slate.js 编辑器
 * - 提供链接有效性检查和用户反馈
 */ export var InsertLink = function InsertLink() {
    var _useEditorStore = useEditorStore(), markdownContainerRef = _useEditorStore.markdownContainerRef, openInsertLink$ = _useEditorStore.openInsertLink$, domRect = _useEditorStore.domRect, markdownEditorRef = _useEditorStore.markdownEditorRef;
    var locale = useContext(I18nContext).locale;
    var selRef = useRef();
    var inputRef = useRef(null);
    var _useGetSetState = _sliced_to_array(useGetSetState({
        open: false,
        inputKeyword: '',
        oldUrl: '',
        index: 0,
        docs: [],
        filterDocs: [],
        anchors: [],
        filterAnchors: []
    }), 2), state = _useGetSetState[0], setState = _useGetSetState[1];
    var prevent = useRefFunction(function(e) {
        e.preventDefault();
    });
    var setPath = useRefFunction(function(path) {
        if (isLink(path)) {
            close(path);
        } else {
            var parse = parsePath(path);
            if (!parse.path && parse.hash) {
                return close('#' + parse.hash);
            }
            var realPath = parse.path;
            var relativePath = realPath;
            close("".concat(relativePath).concat(parse.hash ? "#".concat(parse.hash) : ''));
        }
    });
    var openInsertLink = useRefFunction(function(sel) {
        if (domRect) {
            var _markdownContainerRef_current_parentElement;
            selRef.current = sel;
            (_markdownContainerRef_current_parentElement = markdownContainerRef.current.parentElement) === null || _markdownContainerRef_current_parentElement === void 0 ? void 0 : _markdownContainerRef_current_parentElement.addEventListener('wheel', prevent, {
                passive: false
            });
            var url = EditorUtils.getUrl(markdownEditorRef.current);
            var path = url;
            if (url && !url.startsWith('#') && !isLink(url)) {
                path = url;
            }
            var parse = parsePath(path);
            setState({
                oldUrl: url || '',
                open: true,
                filterDocs: [],
                docs: [],
                inputKeyword: path
            });
            if (parse.hash) {} else {
                setState({
                    filterAnchors: [],
                    anchors: []
                });
            }
            setTimeout(function() {
                var _inputRef_current;
                (_inputRef_current = inputRef.current) === null || _inputRef_current === void 0 ? void 0 : _inputRef_current.focus();
            }, 16);
        }
    });
    useSubject(openInsertLink$, openInsertLink);
    var close = useRefFunction(function(url) {
        var _markdownContainerRef_current_parentElement;
        (_markdownContainerRef_current_parentElement = markdownContainerRef.current.parentElement) === null || _markdownContainerRef_current_parentElement === void 0 ? void 0 : _markdownContainerRef_current_parentElement.removeEventListener('wheel', prevent);
        setState({
            open: false
        });
        EditorUtils.focus(markdownEditorRef.current);
        Transforms.setNodes(markdownEditorRef.current, {
            url: url
        }, {
            match: Text.isText,
            split: true
        });
        if (typeof window === 'undefined') return;
        if (typeof window.matchMedia === 'undefined') return;
    });
    if (!state().open) return null;
    return /*#__PURE__*/ React.createElement(Modal, {
        afterClose: function afterClose() {
            close(state().oldUrl);
        },
        open: state().open,
        onOk: function onOk(e) {
            e.preventDefault();
            if (isLink(state().inputKeyword)) {
                close(state().inputKeyword);
            } else {
                if (state().anchors.length) {
                    var target = state().filterAnchors[state().index];
                    if (target) {
                        setPath(target.item.path + target.value);
                    }
                } else {
                    var target1 = state().filterDocs[state().index];
                    if (target1) {
                        setPath(target1.path);
                    } else {
                        close(state().inputKeyword);
                    }
                }
            }
        },
        onCancel: function onCancel() {
            close(state().oldUrl);
        },
        style: {
            pointerEvents: 'auto',
            width: 370
        },
        title: " "
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            alignItems: 'center',
            padding: '0 6px',
            width: '100%',
            gap: 8
        }
    }, /*#__PURE__*/ React.createElement(Input.TextArea, {
        ref: inputRef,
        value: state().inputKeyword,
        spellCheck: false,
        onKeyDown: function onKeyDown(e) {
            if (e.key.toLowerCase() === 'backspace' && state().anchors.length && (e.metaKey || e.altKey || state().inputKeyword.endsWith('#') || !state().inputKeyword.includes('#'))) {
                setState({
                    anchors: [],
                    filterAnchors: []
                });
            }
        },
        onChange: function onChange(e) {
            var key = e.target.value.toLowerCase();
            if (state().anchors.length) {
                var parse = parsePath(key);
                var filterAnchors = state().anchors.filter(function(d) {
                    return !parse.hash || d.value.toLowerCase().includes(parse.hash);
                });
                setState({
                    filterAnchors: filterAnchors
                });
            } else {
                var filterDocs = state().docs.filter(function(d) {
                    return d.path.toLowerCase().includes(key);
                });
                setState({
                    filterDocs: filterDocs
                });
            }
            setState({
                inputKeyword: e.target.value,
                index: 0
            });
        },
        style: {
            flex: 1
        }
    }), /*#__PURE__*/ React.createElement(Tooltip, {
        title: (locale === null || locale === void 0 ? void 0 : locale.removeLink) || '移除链接'
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            cursor: 'pointer',
            fontSize: '1.1em',
            color: 'rgba(0,0,0,0.5)'
        },
        onClick: function onClick() {
            close();
        }
    }, /*#__PURE__*/ React.createElement(DeleteOutlined, null)))));
};
