/* eslint-disable no-case-declarations */ 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 _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
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 _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);
}
import { Editor, Element, Node, Path, Point, Range, Text, Transforms } from "slate";
import { getListType, isListType } from "../withListsPlugin";
/**
 * TabKey 类用于处理编辑器中的 Tab 键事件。
 */ export var TabKey = /*#__PURE__*/ function() {
    "use strict";
    function TabKey(editor) {
        _class_call_check(this, TabKey);
        _define_property(this, "editor", void 0);
        this.editor = editor;
    }
    _create_class(TabKey, [
        {
            key: "run",
            value: function run(e) {
                var _this = this;
                var sel = this.editor.selection;
                if (!sel) return;
                e.preventDefault();
                if (Range.isCollapsed(sel)) {
                    var _Editor_nodes = _sliced_to_array(Editor.nodes(this.editor, {
                        match: function match(n) {
                            return Element.isElement(n) && [
                                'table-cell',
                                'paragraph'
                            ].includes(n.type);
                        },
                        mode: 'lowest'
                    }), 1), node = _Editor_nodes[0];
                    if (sel && Editor.hasPath(this.editor, sel.anchor.path)) {
                        if (node) {
                            var _node_;
                            var _node = _sliced_to_array(node, 2), el = _node[0], path = _node[1];
                            switch(node === null || node === void 0 ? void 0 : (_node_ = node[0]) === null || _node_ === void 0 ? void 0 : _node_.type){
                                case 'table-cell':
                                    if (this.tableCell(el, path, e.shiftKey)) return;
                                    break;
                                case 'paragraph':
                                    var parent = Editor.parent(this.editor, node[1]);
                                    if (parent && parent[0].type === 'list-item') {
                                        if (this.listItem(node, e)) return;
                                    }
                                    break;
                            }
                        }
                    }
                    if (e.shiftKey) {
                        var _Editor_nodes1 = _sliced_to_array(Editor.nodes(this.editor, {
                            match: function match(n) {
                                return Text.isText(n);
                            }
                        }), 1), leaf = _Editor_nodes1[0];
                        if (leaf) {
                            var str = Node.string(leaf[0]);
                            if (str && /^\t/.test(str)) {
                                Transforms.insertText(this.editor, '', {
                                    at: {
                                        anchor: {
                                            path: leaf[1],
                                            offset: 0
                                        },
                                        focus: {
                                            path: leaf[1],
                                            offset: 1
                                        }
                                    }
                                });
                                Transforms.select(this.editor, {
                                    path: sel.anchor.path,
                                    offset: sel.anchor.offset - 1
                                });
                            }
                        }
                    } else {
                        this.editor.insertText('\t');
                    }
                } else {
                    var _Range_edges = _sliced_to_array(Range.edges(sel), 2), start = _Range_edges[0], end = _Range_edges[1];
                    var _Editor_nodes2 = _sliced_to_array(Editor.nodes(this.editor, {
                        match: function match(n) {
                            return (n === null || n === void 0 ? void 0 : n.type) === 'code';
                        }
                    }), 1), code = _Editor_nodes2[0];
                    if (code) {
                        if (Point.compare(Editor.start(this.editor, code[1]), start) !== 1 && Point.compare(Editor.end(this.editor, code[1]), end) !== -1) {
                            return;
                        }
                    } else if (e.shiftKey) {
                        var _Editor_nodes3 = _sliced_to_array(Editor.nodes(this.editor, {
                            match: function match(n) {
                                return isListType(n);
                            }
                        }), 1), node1 = _Editor_nodes3[0];
                        if (node1) {
                            var _Range_edges1 = _sliced_to_array(Range.edges(sel), 2), start1 = _Range_edges1[0], end1 = _Range_edges1[1];
                            var isStartInNode = Path.isDescendant(start1.path, node1[1]) || Path.equals(start1.path, node1[1]);
                            var isEndInNode = Path.isDescendant(end1.path, node1[1]) || Path.equals(end1.path, node1[1]);
                            var anchor = isStartInNode ? start1 : Editor.start(this.editor, node1[1]);
                            var focus = isEndInNode ? end1 : Editor.end(this.editor, node1[1]);
                            Editor.withoutNormalizing(this.editor, function() {
                                Transforms.liftNodes(_this.editor, {
                                    at: {
                                        anchor: anchor,
                                        focus: focus
                                    }
                                });
                                Transforms.liftNodes(_this.editor);
                            });
                        } else {
                            Transforms.liftNodes(this.editor);
                        }
                        return;
                    }
                    Transforms.select(this.editor, {
                        path: end.path,
                        offset: end.offset
                    });
                }
            }
        },
        {
            key: "tableCell",
            value: function tableCell(node, nodePath) {
                var shift = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
                var sel = this.editor.selection;
                var text = Node.string(node);
                if (shift) {
                    if (Path.hasPrevious(nodePath)) {
                        Transforms.select(this.editor, Editor.end(this.editor, Path.previous(nodePath)));
                    } else if (Path.hasPrevious(Path.parent(nodePath))) {
                        Transforms.select(this.editor, Editor.end(this.editor, Path.previous(Path.parent(nodePath))));
                    }
                    return true;
                } else {
                    if (text.length === sel.anchor.offset) {
                        if (Editor.hasPath(this.editor, Path.next(nodePath))) {
                            Transforms.select(this.editor, Editor.end(this.editor, Path.next(nodePath)));
                        } else if (Editor.hasPath(this.editor, Path.next(Path.parent(nodePath)))) {
                            Transforms.select(this.editor, Editor.end(this.editor, _to_consumable_array(Path.next(Path.parent(nodePath))).concat([
                                0
                            ])));
                        }
                        return true;
                    }
                }
                return false;
            }
        },
        {
            key: "listItem",
            value: /**
   * 处理列表项的 Tab/Shift+Tab 键
   *
   * Tab: 增加缩进（将当前 list-item 移动到前一个 list-item 的子列表中）
   * Shift+Tab: 减少缩进（将当前 list-item 提升一级）
   */ function listItem(node, e) {
                var listItemPath = Path.parent(node[1]);
                var listItem = Node.get(this.editor, listItemPath);
                if (!Element.isElement(listItem) || listItem.type !== 'list-item') {
                    return false;
                }
                var listPath = Path.parent(listItemPath);
                var list = Node.get(this.editor, listPath);
                if (!isListType(list)) {
                    return false;
                }
                if (e.shiftKey) {
                    // Shift+Tab: 减少缩进
                    return this.outdentListItem(listItemPath, listPath);
                } else {
                    // Tab: 增加缩进
                    return this.indentListItem(listItemPath);
                }
            }
        },
        {
            key: "indentListItem",
            value: /**
   * 增加缩进：将当前 list-item 移动到前一个 list-item 的子列表中
   */ function indentListItem(listItemPath) {
                var _this = this;
                // 检查是否是第一个 list-item（第一行按 Tab 应该无效）
                if (!Path.hasPrevious(listItemPath)) {
                    return false;
                }
                var previousListItemPath = Path.previous(listItemPath);
                var previousListItem = Node.get(this.editor, previousListItemPath);
                if (!Element.isElement(previousListItem) || previousListItem.type !== 'list-item') {
                    return false;
                }
                // 检查前一个 list-item 的最后一个子节点是否为列表
                var lastChildIndex = previousListItem.children.length - 1;
                var lastChild = previousListItem.children[lastChildIndex];
                if (isListType(lastChild)) {
                    // 如果最后一个子节点是列表，直接将当前项移动到该列表中
                    var targetListPath = _to_consumable_array(previousListItemPath).concat([
                        lastChildIndex
                    ]);
                    var targetList = Node.get(this.editor, targetListPath);
                    if (isListType(targetList)) {
                        var targetIndex = targetList.children.length;
                        Transforms.moveNodes(this.editor, {
                            at: listItemPath,
                            to: _to_consumable_array(targetListPath).concat([
                                targetIndex
                            ])
                        });
                        return true;
                    }
                } else {
                    var listType = getListType();
                    var currentListItem = Node.get(this.editor, listItemPath);
                    var newList = {
                        type: listType,
                        children: [
                            currentListItem
                        ]
                    };
                    Editor.withoutNormalizing(this.editor, function() {
                        Transforms.removeNodes(_this.editor, {
                            at: listItemPath
                        });
                        Transforms.insertNodes(_this.editor, newList, {
                            at: _to_consumable_array(previousListItemPath).concat([
                                previousListItem.children.length
                            ])
                        });
                        var newListPath = _to_consumable_array(previousListItemPath).concat([
                            previousListItem.children.length
                        ]);
                        var newListItemPath = _to_consumable_array(newListPath).concat([
                            0
                        ]);
                        Transforms.select(_this.editor, Editor.start(_this.editor, newListItemPath));
                    });
                    return true;
                }
                return false;
            }
        },
        {
            key: "outdentListItem",
            value: /**
   * 减少缩进：将当前 list-item 提升一级
   */ function outdentListItem(listItemPath, listPath) {
                var _this = this;
                // 检查当前 list 的父节点
                var listParent = Editor.parent(this.editor, listPath);
                // 如果父节点是 list-item，说明在嵌套列表中，可以提升
                if (Element.isElement(listParent[0]) && listParent[0].type === 'list-item') {
                    var parentListItemPath = listParent[1];
                    // 检查是否是父列表的第一个 list-item
                    var isFirstInParentList = !Path.hasPrevious(listPath);
                    if (isFirstInParentList && !Path.hasPrevious(parentListItemPath)) {
                        // 如果是最顶层的第一个项，不能提升
                        return false;
                    }
                    Editor.withoutNormalizing(this.editor, function() {
                        Transforms.liftNodes(_this.editor, {
                            at: listItemPath
                        });
                        var updatedList = Node.get(_this.editor, listPath);
                        if (isListType(updatedList) && Node.string(updatedList).trim() === '') {
                            Transforms.removeNodes(_this.editor, {
                                at: listPath
                            });
                        }
                    });
                    return true;
                } else {
                    // 已经是最顶层，不能提升
                    return false;
                }
            }
        }
    ]);
    return TabKey;
}();
