/* 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, Transforms } from "slate";
import { isMod } from "../../utils";
import { EditorUtils } from "../../utils/editorUtils";
import { BlockMathNodes } from "../elements";
export var EnterKey = /*#__PURE__*/ function() {
    "use strict";
    function EnterKey(store, backspace) {
        _class_call_check(this, EnterKey);
        _define_property(this, "store", void 0);
        _define_property(this, "backspace", void 0);
        _define_property(this, "bracketsMap", void 0);
        this.store = store;
        this.backspace = backspace;
        this.bracketsMap = new Map([
            [
                '[',
                ']'
            ],
            [
                '{',
                '}'
            ]
        ]);
    }
    _create_class(EnterKey, [
        {
            key: "editor",
            get: function get() {
                var _this_store;
                return (_this_store = this.store) === null || _this_store === void 0 ? void 0 : _this_store.editor;
            }
        },
        {
            key: "run",
            value: function run(e) {
                var _this_editor;
                var sel = this.editor.selection;
                if (!sel || this.store.inputComposition) return;
                if (!Range.isCollapsed(sel)) {
                    e.preventDefault();
                    this.backspace.range();
                    return;
                }
                var _Editor_nodes = _sliced_to_array(Editor.nodes(this.editor, {
                    match: function match(n) {
                        return Element.isElement(n);
                    },
                    mode: 'lowest'
                }), 1), node = _Editor_nodes[0];
                if (node) {
                    var _node = _sliced_to_array(node, 2), el = _node[0], path = _node[1];
                    if (el.type === 'card-before') {
                        Transforms.insertNodes(this.editor, EditorUtils.p, {
                            at: Path.parent(path),
                            select: true
                        });
                        e.preventDefault();
                        return;
                    }
                    if (el.type === 'card-after') {
                        Transforms.insertNodes(this.editor, EditorUtils.p, {
                            at: Path.next(Path.parent(path)),
                            select: true
                        });
                        e.preventDefault();
                        return;
                    }
                    if (el.type === 'head') {
                        if (this.head(el, path, sel)) {
                            e.preventDefault();
                            return;
                        }
                    }
                    if (el.type === 'paragraph') {
                        if (this.paragraph(e, node, sel)) {
                            e.preventDefault();
                            return;
                        }
                    }
                    if (el.type === 'table-cell') {
                        var table = Editor.parent(this.editor, path);
                        if (table[0].type === 'table-row') {
                            this.table(table, sel, e);
                            e.preventDefault();
                            return;
                        }
                    }
                    if (el.type === 'blockquote' || el.type === 'list-item') {
                        this.empty(e, path);
                        return;
                    }
                    if (el.type === 'code') {
                        Transforms.insertText(this.editor, '\n');
                        e.preventDefault();
                        return;
                    }
                    if (el.type === 'break') {
                        Transforms.insertNodes(this.editor, {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        });
                        e.preventDefault();
                    }
                }
                (_this_editor = this.editor) === null || _this_editor === void 0 ? void 0 : _this_editor.insertBreak();
            }
        },
        {
            key: "empty",
            value: function empty(e, path) {
                var _this = this;
                var _Editor_parent = _sliced_to_array(Editor.parent(this.editor, path), 2), parent = _Editor_parent[0], parentPath = _Editor_parent[1];
                if (parent.type === 'blockquote') {
                    if (!Path.hasPrevious(path)) {
                        var hashNext = Editor.hasPath(this.editor, Path.next(path));
                        if (!hashNext) {
                            Editor.withoutNormalizing(this.editor, function() {
                                Transforms.delete(_this.editor, {
                                    at: parentPath
                                });
                                Transforms.insertNodes(_this.editor, {
                                    type: 'paragraph',
                                    children: [
                                        {
                                            text: ''
                                        }
                                    ]
                                }, {
                                    at: parentPath,
                                    select: true
                                });
                            });
                            e.preventDefault();
                        }
                    }
                    if (!Editor.hasPath(this.editor, Path.next(path))) {
                        Editor.withoutNormalizing(this.editor, function() {
                            Transforms.delete(_this.editor, {
                                at: path
                            });
                            Transforms.insertNodes(_this.editor, {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            }, {
                                at: Path.next(parentPath),
                                select: true
                            });
                        });
                        e.preventDefault();
                    }
                }
                if (parent.type === 'list-item') {
                    var _Editor_parent1 = _sliced_to_array(Editor.parent(this.editor, parentPath), 2), ul = _Editor_parent1[0], ulPath = _Editor_parent1[1];
                    var realEmpty = parent.children.length === 1;
                    if (ul.children.length === 1 && realEmpty) {
                        e.preventDefault();
                        Editor.withoutNormalizing(this.editor, function() {
                            Transforms.delete(_this.editor, {
                                at: ulPath
                            });
                            Transforms.insertNodes(_this.editor, EditorUtils.p, {
                                at: ulPath,
                                select: true
                            });
                        });
                        return;
                    }
                    if (realEmpty) {
                        e.preventDefault();
                        Editor.withoutNormalizing(this.editor, function() {
                            if (!Path.hasPrevious(parentPath)) {
                                Transforms.delete(_this.editor, {
                                    at: parentPath
                                });
                                Transforms.insertNodes(_this.editor, EditorUtils.p, {
                                    at: ulPath,
                                    select: true
                                });
                            } else if (!Editor.hasPath(_this.editor, Path.next(parentPath))) {
                                Transforms.delete(_this.editor, {
                                    at: parentPath
                                });
                                Transforms.insertNodes(_this.editor, EditorUtils.p, {
                                    at: Path.next(ulPath),
                                    select: true
                                });
                            } else {
                                Transforms.liftNodes(_this.editor, {
                                    at: parentPath
                                });
                                Transforms.delete(_this.editor, {
                                    at: Path.next(ulPath)
                                });
                                Transforms.insertNodes(_this.editor, EditorUtils.p, {
                                    at: Path.next(ulPath),
                                    select: true
                                });
                            }
                        });
                    } else {
                        if (!Editor.hasPath(this.editor, Path.next(path))) {
                            e.preventDefault();
                            Editor.withoutNormalizing(this.editor, function() {
                                Transforms.delete(_this.editor, {
                                    at: path
                                });
                                Transforms.insertNodes(_this.editor, {
                                    type: 'list-item',
                                    checked: typeof parent.checked === 'boolean' ? false : undefined,
                                    children: [
                                        EditorUtils.p
                                    ]
                                }, {
                                    at: Path.next(parentPath),
                                    select: true
                                });
                            });
                        } else if (!Path.hasPrevious(path)) {
                            e.preventDefault();
                            Transforms.insertNodes(this.editor, {
                                type: 'list-item',
                                checked: typeof parent.checked === 'boolean' ? false : undefined,
                                children: [
                                    EditorUtils.p
                                ]
                            }, {
                                at: Path.next(parentPath),
                                select: true
                            });
                        }
                    }
                }
            }
        },
        {
            key: "table",
            value: function table(node, sel, e) {
                if (isMod(e)) {
                    if (e.shiftKey) {
                        Transforms.insertNodes(this.editor, [
                            {
                                type: 'break',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            },
                            {
                                text: ''
                            }
                        ], {
                            select: true
                        });
                        e.preventDefault();
                    } else {
                        var row = Editor.parent(this.editor, node[1]);
                        var insertRow = {
                            type: 'table-row',
                            children: row[0].children.map(function() {
                                return {
                                    type: 'table-cell',
                                    children: [
                                        {
                                            type: 'paragraph',
                                            children: [
                                                {
                                                    text: ''
                                                }
                                            ]
                                        }
                                    ]
                                };
                            })
                        };
                        Transforms.insertNodes(this.editor, insertRow, {
                            at: Path.next(row[1])
                        });
                        Transforms.select(this.editor, Editor.start(this.editor, Path.next(row[1])));
                    }
                } else {
                    var index = node[1][node[1].length - 1];
                    var nextRow = Path.next(Path.parent(node[1]));
                    if (Editor.hasPath(this.editor, nextRow)) {
                        Transforms.select(this.editor, Editor.end(this.editor, _to_consumable_array(nextRow).concat([
                            index
                        ])));
                    } else {
                        var tableNext = Path.next(Path.parent(Path.parent(node[1])));
                        if (Editor.hasPath(this.editor, tableNext)) {
                            Transforms.select(this.editor, Editor.start(this.editor, tableNext));
                        } else {
                            Transforms.insertNodes(this.editor, EditorUtils.p, {
                                at: tableNext,
                                select: true
                            });
                        }
                    }
                }
            }
        },
        {
            key: "head",
            value: function head(el, path, sel) {
                var _this = this;
                var start = Range.start(sel);
                var elStart = Editor.start(this.editor, path);
                if (Point.equals(start, elStart)) {
                    Transforms.insertNodes(this.editor, {
                        type: 'paragraph',
                        children: [
                            {
                                text: ''
                            }
                        ]
                    }, {
                        at: path
                    });
                } else {
                    var end = Range.end(sel);
                    var elEnd = Editor.end(this.editor, path);
                    if (Point.equals(end, elEnd)) {
                        Transforms.insertNodes(this.editor, {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }, {
                            at: Path.next(path),
                            select: true
                        });
                    } else {
                        var fragment = Node.fragment(this.editor, {
                            anchor: end,
                            focus: elEnd
                        });
                        Editor.withoutNormalizing(this.editor, function() {
                            var _fragment_;
                            Transforms.delete(_this.editor, {
                                at: {
                                    anchor: start,
                                    focus: elEnd
                                }
                            });
                            Transforms.insertNodes(_this.editor, {
                                type: 'paragraph',
                                children: ((_fragment_ = fragment[0]) === null || _fragment_ === void 0 ? void 0 : _fragment_.children) || [
                                    {
                                        text: ''
                                    }
                                ]
                            }, {
                                at: Path.next(path)
                            });
                            Transforms.select(_this.editor, Editor.start(_this.editor, Path.next(path)));
                        });
                    }
                }
                return true;
            }
        },
        {
            key: "paragraph",
            value: function paragraph(e, node, sel) {
                var _this = this;
                var parent = Editor.parent(this.editor, node[1]);
                var end = Editor.end(this.editor, node[1]);
                if (Point.equals(end, sel.focus)) {
                    if (parent[0].type !== 'list-item' || Path.hasPrevious(node[1])) {
                        var str = Node.string(node[0]);
                        if (!str) return;
                        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                        try {
                            for(var _iterator = BlockMathNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                                var n = _step.value;
                                if (n.checkAllow && !n.checkAllow({
                                    editor: this.editor,
                                    node: node,
                                    sel: sel
                                })) continue;
                                var m = str === null || str === void 0 ? void 0 : str.match(n.reg);
                                if (m) {
                                    n.run({
                                        editor: this.editor,
                                        path: node[1],
                                        match: m,
                                        el: node[0],
                                        sel: sel,
                                        startText: m[0]
                                    });
                                    e.preventDefault();
                                    return true;
                                }
                            }
                        } catch (err) {
                            _didIteratorError = true;
                            _iteratorError = err;
                        } finally{
                            try {
                                if (!_iteratorNormalCompletion && _iterator.return != null) {
                                    _iterator.return();
                                }
                            } finally{
                                if (_didIteratorError) {
                                    throw _iteratorError;
                                }
                            }
                        }
                    }
                }
                if (parent[0].type === 'list-item') {
                    // 列表为空（仅有一项且该项无内容）时，回车将列表转换为段落
                    var listItemPath = parent[1];
                    var _Editor_parent = _sliced_to_array(Editor.parent(this.editor, listItemPath), 2), listNode = _Editor_parent[0], listPath = _Editor_parent[1];
                    var isListWithSingleEmptyItem = listNode.children.length === 1 && Node.string(node[0]) === '' && !Path.hasPrevious(listItemPath);
                    if (isListWithSingleEmptyItem) {
                        e.preventDefault();
                        Editor.withoutNormalizing(this.editor, function() {
                            Transforms.removeNodes(_this.editor, {
                                at: listPath
                            });
                            Transforms.insertNodes(_this.editor, EditorUtils.p, {
                                at: listPath,
                                select: true
                            });
                        });
                        return true;
                    }
                    if (isMod(e) || Path.hasPrevious(node[1])) {
                        var text = Point.equals(end, sel.focus) ? [
                            {
                                text: ''
                            }
                        ] : EditorUtils.cutText(this.editor, sel.focus);
                        Editor.withoutNormalizing(this.editor, function() {
                            Transforms.insertNodes(_this.editor, {
                                type: 'paragraph',
                                children: text || ' '
                            }, {
                                at: Path.next(node[1])
                            });
                            if (!Point.equals(end, sel.focus)) {
                                Transforms.delete(_this.editor, {
                                    at: {
                                        anchor: sel.focus,
                                        focus: end
                                    }
                                });
                            }
                            if (Editor.hasPath(_this.editor, Path.next(node[1]))) {
                                Transforms.select(_this.editor, Editor.start(_this.editor, Path.next(node[1])));
                            }
                        });
                        e.preventDefault();
                        return true;
                    } else {
                        e.preventDefault();
                        var checked = undefined;
                        if (typeof parent[0].checked === 'boolean') {
                            if (sel.anchor.offset === 0 && !Path.hasPrevious(sel.anchor.path) && !Path.hasPrevious(node[1])) {
                                checked = parent[0].checked;
                                Transforms.insertNodes(this.editor, {
                                    type: 'list-item',
                                    children: [
                                        EditorUtils.p
                                    ],
                                    checked: typeof checked === 'boolean' ? false : undefined
                                }, {
                                    at: parent[1]
                                });
                                Transforms.select(this.editor, Editor.start(this.editor, Path.next(parent[1])));
                                return;
                            } else {
                                checked = false;
                            }
                        }
                        var text1 = Point.equals(Editor.end(this.editor, node[1]), sel.focus) ? [
                            {
                                text: ''
                            }
                        ] : EditorUtils.cutText(this.editor, sel.focus);
                        Editor.withoutNormalizing(this.editor, function() {
                            Transforms.insertNodes(_this.editor, {
                                type: 'list-item',
                                children: [
                                    {
                                        type: 'paragraph',
                                        children: text1 || [
                                            {
                                                text: ''
                                            }
                                        ]
                                    }
                                ],
                                checked: checked
                            }, {
                                at: Path.next(parent[1])
                            });
                            if (!Point.equals(sel.anchor, Editor.end(_this.editor, node[1]))) {
                                Transforms.delete(_this.editor, {
                                    at: {
                                        anchor: sel.anchor,
                                        focus: Editor.end(_this.editor, node[1])
                                    }
                                });
                            }
                            if (Point.equals(sel.anchor, Editor.start(_this.editor, node[1])) && Node.string(Node.get(_this.editor, node[1])) !== '') {
                                EditorUtils.clearMarks(_this.editor);
                            }
                            var nextParentPath = Path.next(parent[1]);
                            if (Editor.hasPath(_this.editor, nextParentPath)) {
                                Transforms.select(_this.editor, Editor.start(_this.editor, nextParentPath));
                            }
                        });
                        return true;
                    }
                }
            }
        }
    ]);
    return EnterKey;
}();
