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);
}
import isHotkey from "is-hotkey";
import { useMemo } from "react";
import { Editor, Element, Node, Path, Range, Transforms } from "slate";
import { EditorUtils } from "../utils/editorUtils";
import { BackspaceKey } from "./hotKeyCommands/backspace";
import { EnterKey } from "./hotKeyCommands/enter";
import { MatchKey } from "./hotKeyCommands/match";
import { TabKey } from "./hotKeyCommands/tab";
import { NativeTableKeyboard } from "../../utils/native-table";
import { useEditorStore } from "../store";
/**
 * 键盘事件处理 Hook - 管理 Markdown 编辑器的所有键盘交互
 *
 * 该 Hook 负责拦截和处理各种键盘快捷键和特殊按键操作，提供丰富的编辑体验：
 *
 * 支持的快捷键操作：
 * - Tab/Shift+Tab：代码块缩进控制、列表层级调整
 * - Backspace：智能删除、格式清理、列表处理
 * - Enter：段落分割、列表项创建、代码块换行
 * - 方向键：光标移动、选择范围调整
 * - Ctrl/Cmd 组合键：文本格式化（粗体、斜体等）
 *
 * 特殊功能：
 * - 自动补全面板的键盘导航
 * - 表格单元格间的 Tab 导航
 * - 代码块的语法高亮触发
 * - Markdown 语法的智能识别和转换
 *
 * @param store - 编辑器的全局状态管理对象
 * @param markdownEditorRef - 指向 Slate.js 编辑器实例的引用
 * @param props - 编辑器的属性配置对象
 * @returns 返回键盘事件处理函数，用于绑定到 Slate.js 的 onKeyDown 属性
 *
 * @example
 * ```typescript
 * const onKeyDown = useKeyboard(store, editorRef, editorProps);
 *
 * return (
 *   <Slate editor={editor} initialValue={value}>
 *     <Editable onKeyDown={onKeyDown} />
 *   </Slate>
 * );
 * ```
 *
 * @remarks
 * - 所有按键处理都经过 isHotkey 库进行精确匹配
 * - 支持跨平台快捷键（Windows/Mac）
 * - 与编辑器状态深度集成，实现上下文相关的行为
 * - 提供良好的用户体验和 Markdown 编辑效率
 */ export var useKeyboard = function(store, markdownEditorRef, props) {
    var _useEditorStore = useEditorStore(), openInsertCompletion = _useEditorStore.openInsertCompletion, insertCompletionText$ = _useEditorStore.insertCompletionText$, setOpenInsertCompletion = _useEditorStore.setOpenInsertCompletion;
    return useMemo(function() {
        var tab = new TabKey(markdownEditorRef.current);
        var backspace = new BackspaceKey(markdownEditorRef.current);
        var enter = new EnterKey(store, backspace);
        var match = new MatchKey(markdownEditorRef.current);
        return function(e) {
            var _props_markdown, _node_;
            // 处理表格键盘事件
            if (NativeTableKeyboard.shouldHandle(markdownEditorRef.current)) {
                if (NativeTableKeyboard.handleKeyDown(markdownEditorRef.current, e.nativeEvent)) {
                    return;
                }
            }
            if (openInsertCompletion && (isHotkey('up', e) || isHotkey('down', e))) {
                e.preventDefault();
                return;
            }
            if (isHotkey('mod+ArrowDown', e)) {
                e.preventDefault();
                Transforms.select(markdownEditorRef.current, Editor.end(markdownEditorRef.current, []));
            }
            if (isHotkey('mod+ArrowUp', e)) {
                e.preventDefault();
                Transforms.select(markdownEditorRef.current, Editor.start(markdownEditorRef.current, []));
            }
            if (isHotkey('backspace', e) && markdownEditorRef.current.selection) {
                if (Range.isCollapsed(markdownEditorRef.current.selection)) {
                    if (backspace.run()) {
                        e.stopPropagation();
                        e.preventDefault();
                        return;
                    }
                }
                if (backspace.range()) {
                    e.stopPropagation();
                    e.preventDefault();
                    return;
                }
            }
            if (isHotkey('mod+shift+v', e)) {
                e.preventDefault();
            }
            if (isHotkey('mod+alt+v', e) || isHotkey('mod+opt+v', e)) {
                e.preventDefault();
            }
            if (isHotkey('mod+shift+s', e)) {
                e.preventDefault();
            }
            if (props === null || props === void 0 ? void 0 : (_props_markdown = props.markdown) === null || _props_markdown === void 0 ? void 0 : _props_markdown.matchInputToNode) {
                match.run(e);
                return;
            }
            if (e.key.toLowerCase().startsWith('arrow')) {
                if ([
                    'ArrowUp',
                    'ArrowDown'
                ].includes(e.key)) return;
                // 处理 tag 前的空格插入
                if (e.key === 'ArrowLeft') {
                    var selection = markdownEditorRef.current.selection;
                    if (selection && Range.isCollapsed(selection)) {
                        var _Editor_nodes = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                            at: selection.focus.path,
                            match: function(n) {
                                return n.tag === true;
                            }
                        }), 1), node = _Editor_nodes[0];
                        if (node) {
                            var _node = _sliced_to_array(node, 2), tagPath = _node[1];
                            var offset = selection.focus.offset;
                            // 当光标在 tag 开始位置时，检查前面是否需要插入空格
                            if (offset === 0) {
                                var _prevNode_text;
                                var _ref = _sliced_to_array(Editor.previous(markdownEditorRef.current, {
                                    at: tagPath
                                }) || [], 1), prevNode = _ref[0];
                                if (!prevNode || !((_prevNode_text = prevNode.text) === null || _prevNode_text === void 0 ? void 0 : _prevNode_text.endsWith('\uFEFF'))) {
                                    e.preventDefault();
                                    Transforms.insertNodes(markdownEditorRef.current, [
                                        {
                                            text: '\uFEFF'
                                        }
                                    ], {
                                        at: tagPath,
                                        select: true
                                    });
                                    return;
                                }
                            }
                        }
                    }
                }
                return;
            }
            if (e.key === 'Tab') tab.run(e);
            // Enter 发送，Shift+Enter 换行
            if (e.key === 'Enter' && e.shiftKey && !(e.ctrlKey || e.metaKey)) {
                e.stopPropagation();
                e.preventDefault();
                enter.run(e);
                return;
            }
            // Enter 键（无 Shift）处理：如果在列表项中，让 EnterKey 处理；否则由 MarkdownInputField 处理发送
            if (e.key === 'Enter' && !(e.ctrlKey || e.metaKey) && !e.shiftKey) {
                // 检查当前是否在列表项中
                var selection1 = markdownEditorRef.current.selection;
                if (selection1 && Range.isCollapsed(selection1)) {
                    var _Editor_nodes1 = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                        at: selection1.focus.path,
                        match: function(n) {
                            return Element.isElement(n) && n.type === 'list-item';
                        },
                        mode: 'lowest'
                    }), 1), node1 = _Editor_nodes1[0];
                    if (node1) {
                        // 在列表项中，让 EnterKey 处理
                        e.stopPropagation();
                        e.preventDefault();
                        enter.run(e);
                        return;
                    }
                }
                // 不在列表项中，让 MarkdownInputField 处理发送
                return;
            }
            var _Editor_nodes2 = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                match: function(n) {
                    return Element.isElement(n);
                },
                mode: 'lowest'
            }), 1), node2 = _Editor_nodes2[0];
            if (!node2) return;
            if ((node2 === null || node2 === void 0 ? void 0 : (_node_ = node2[0]) === null || _node_ === void 0 ? void 0 : _node_.type) === 'paragraph') {
                var _Editor_nodes3 = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
                    match: function(n) {
                        return Element.isElement(n) && n.type === 'paragraph';
                    },
                    mode: 'lowest'
                }), 1), node3 = _Editor_nodes3[0];
                if (node3 && node3[0].children.length === 1 && !EditorUtils.isDirtLeaf(node3[0].children[0]) && (e.key === 'Backspace' || /^[^\n]$/.test(e.key))) {
                    var str = Node.string(node3[0]) || '';
                    var codeMatch = str.match(/^```([\w+\-#]+)$/i);
                    if (codeMatch) {} else {
                        var insertMatch = str.match(/^\/([^\n]+)?$/i);
                        if (insertMatch && !(!Path.hasPrevious(node3[1]) && Node.parent(markdownEditorRef.current, node3[1]).type === 'list-item')) {
                            setOpenInsertCompletion === null || setOpenInsertCompletion === void 0 ? void 0 : setOpenInsertCompletion(true);
                            setTimeout(function() {
                                insertCompletionText$.next(insertMatch[1]);
                            });
                        }
                    }
                }
            }
        };
    }, [
        markdownEditorRef.current
    ]);
};
