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 _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_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 _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 _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, Node, Path, Range, Transforms } from "slate";
import { hasRange } from "./utils";
/**
 * 处理代码和标签相关节点的操作
 *
 * @param editor - Slate编辑器实例
 * @param operation - 要处理的操作
 * @param apply - 原始的apply函数
 * @returns 如果操作被处理则返回true，否则返回false
 *
 * @description
 * 处理以下代码和标签相关操作:
 * - 删除文本 (remove_text)，处理特殊触发文本和空标签
 * - 删除节点 (remove_node)，处理代码块周围的空格
 * - 插入文本 (insert_text)，处理代码块中的空格插入
 */ var handleCodeTagOperation = function handleCodeTagOperation(editor, operation, apply) {
    if (operation.type === 'remove_text') {
        var currentNode = Node.get(editor, operation.path);
        if (currentNode === null || currentNode === void 0 ? void 0 : currentNode.tag) {
            var _currentNode_text;
            // 处理空标签的删除
            if (((_currentNode_text = currentNode.text) === null || _currentNode_text === void 0 ? void 0 : _currentNode_text.trim()) === '') {
                Editor.withoutNormalizing(editor, function() {
                    Transforms.setNodes(editor, {
                        tag: false,
                        code: false,
                        text: ' ',
                        triggerText: undefined
                    }, {
                        at: operation.path
                    });
                });
                return true;
            }
            if (currentNode.text === operation.text) {
                Editor.withoutNormalizing(editor, function() {
                    Transforms.removeNodes(editor, {
                        at: operation.path
                    });
                    Transforms.insertNodes(editor, _object_spread_props(_object_spread({}, currentNode), {
                        tag: true,
                        code: true,
                        text: ' '
                    }), {
                        at: operation.path,
                        select: true
                    });
                });
                return true;
            }
            // 光标在 tag 内部，执行原始的删除操作
            apply(operation);
            return true;
        }
    }
    if (operation.type === 'insert_text') {
        var _editor_selection;
        var currentNode1 = Node.get(editor, operation.path);
        if ((currentNode1 === null || currentNode1 === void 0 ? void 0 : currentNode1.tag) && operation.text === ' ' && ((_editor_selection = editor.selection) === null || _editor_selection === void 0 ? void 0 : _editor_selection.focus.offset) === currentNode1.text.length) {
            // 检查前一个字符是否是空格
            var lastChar = currentNode1.text.charAt(currentNode1.text.length - 1);
            if (lastChar === ' ') {
                // 如果前一个输入是空格，且当前输入也是空格，则插入一个空格到 tag 节点外
                Transforms.insertNodes(editor, [
                    {
                        text: ' '
                    }
                ]);
                return true;
            }
        }
        if ((currentNode1 === null || currentNode1 === void 0 ? void 0 : currentNode1.tag) && operation.text.trim().length > 0 && currentNode1.text.trim().length === 0) {
            apply(operation);
            return true;
        }
    }
    if (operation.type === 'split_node') {
        var node = Node.get(editor, operation.path);
        if ((node === null || node === void 0 ? void 0 : node.tag) || (node === null || node === void 0 ? void 0 : node.code)) {
            return true;
        }
    }
    return false;
};
/**
 * 扩展编辑器以处理代码和标签节点的操作
 *
 * @param editor - 要扩展的Slate编辑器实例
 * @returns 增强后的编辑器实例，能够处理代码和标签相关操作
 *
 * @description
 * 该插件重写编辑器的 `apply` 和 `deleteBackward` 方法，添加对代码和标签节点的特殊处理逻辑。
 */ export var withCodeTagPlugin = function withCodeTagPlugin(editor) {
    var apply = editor.apply, deleteBackward = editor.deleteBackward;
    editor.apply = function(operation) {
        // 尝试处理代码和标签相关操作
        if (handleCodeTagOperation(editor, operation, apply)) {
            return;
        }
        // 否则执行原始操作
        apply(operation);
    };
    editor.deleteBackward = function(unit) {
        var selection = editor.selection;
        if (selection && hasRange(editor, selection) && Range.isCollapsed(selection)) {
            var curNode = Node.get(editor, selection.anchor.path);
            // 检查前一个节点是否是 tag
            try {
                var _ref = _sliced_to_array(Editor.previous(editor, {
                    at: selection.anchor.path
                }) || [], 2), previousNode = _ref[0], previousPath = _ref[1];
                var isBeforeTag = selection && selection.anchor.offset <= 1;
                if ((previousNode === null || previousNode === void 0 ? void 0 : previousNode.tag) && previousPath && isBeforeTag) {
                    var _curNode_text, _curNode_text1;
                    // 如果当前节点不为空,且只有一个文本
                    if (((_curNode_text = curNode.text) === null || _curNode_text === void 0 ? void 0 : _curNode_text.trim()) && curNode.text.trimEnd().length === 1 && selection.anchor.offset > 0) {
                        Transforms.insertText(editor, '', {
                            at: selection.anchor.path
                        });
                        Transforms.insertNodes(editor, {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ' '
                                }
                            ]
                        }, {
                            at: selection.anchor.path,
                            select: true
                        });
                        return;
                    } else if (((_curNode_text1 = curNode.text) === null || _curNode_text1 === void 0 ? void 0 : _curNode_text1.trim()) && selection.anchor.offset > 0) {
                        deleteBackward(unit);
                        return;
                    }
                    // 如果前一个节点是 tag，直接删除整个 tag
                    Editor.withoutNormalizing(editor, function() {
                        var parent = Node.get(editor, Path.parent(previousPath));
                        var index = previousPath[previousPath.length - 1];
                        if (parent.children.length === 1) {
                            // 如果是唯一的节点，转换为普通文本
                            Transforms.setNodes(editor, {
                                tag: false,
                                code: false,
                                text: ' ',
                                triggerText: undefined
                            }, {
                                at: previousPath
                            });
                        } else if (index === 0) {
                            // 如果是第一个节点，删除并合并下一个节点
                            Transforms.removeNodes(editor, {
                                at: previousPath
                            });
                        } else {
                            // 如果是中间或最后节点，先合并再删除
                            Transforms.removeNodes(editor, {
                                at: previousPath
                            });
                        }
                    });
                    return;
                }
            } catch (error) {
            // 如果获取前一个节点失败，继续执行原始删除操作
            }
            try {
                var _node_text_trim, _node_text, _selection_anchor;
                var node = Node.get(editor, selection.anchor.path);
                if ((node === null || node === void 0 ? void 0 : node.tag) && (node === null || node === void 0 ? void 0 : (_node_text = node.text) === null || _node_text === void 0 ? void 0 : (_node_text_trim = _node_text.trim()) === null || _node_text_trim === void 0 ? void 0 : _node_text_trim.length) < 1 && (selection === null || selection === void 0 ? void 0 : (_selection_anchor = selection.anchor) === null || _selection_anchor === void 0 ? void 0 : _selection_anchor.offset) < 1) {
                    var _node_text1;
                    var text = node === null || node === void 0 ? void 0 : (_node_text1 = node.text) === null || _node_text1 === void 0 ? void 0 : _node_text1.replace(node.triggerText || '', '');
                    Transforms.setNodes(editor, {
                        tag: false,
                        code: false
                    }, {
                        at: selection.anchor.path
                    });
                    Transforms.insertText(editor, text, {
                        at: selection.anchor.path
                    });
                    return;
                }
            } catch (unused) {}
        }
        deleteBackward(unit);
    };
    return editor;
};
