"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.splitDeflist = exports.wrapToDeflist = void 0;
// @ts-ignore // TODO: fix cjs build
const prosemirror_utils_1 = require("prosemirror-utils");
const selection_1 = require("../../../utils/selection.js");
const utils_1 = require("./utils.js");
const wrapToDeflist = (state, dispatch) => {
    const parent = (0, prosemirror_utils_1.findParentNode)((node) => node.isTextblock)(state.selection);
    if (!parent)
        return false;
    dispatch?.((0, prosemirror_utils_1.replaceParentNodeOfType)(parent.node.type, (0, utils_1.defListType)(state.schema).create(null, [
        (0, utils_1.defTermType)(state.schema).create(),
        (0, utils_1.defDescType)(state.schema).create(null, parent.node.copy(parent.node.content)),
    ]))(state.tr).scrollIntoView());
    return true;
};
exports.wrapToDeflist = wrapToDeflist;
const splitDeflist = (state, dispatch) => {
    const { selection } = state;
    if ((0, selection_1.isNodeSelection)(selection))
        return false;
    const parentTextblock = (0, prosemirror_utils_1.findParentNode)((node) => node.isTextblock)(selection);
    if (!parentTextblock)
        return false; // check if parent is textblock
    const isParentEmpty = parentTextblock.node.textContent === '';
    if (!isParentEmpty)
        return false; // check if parent textblock is empty
    // check if parent textblock is inside description node
    const desc = selection.$from.node(parentTextblock.depth - 1);
    if (!desc || desc.type !== (0, utils_1.defDescType)(state.schema))
        return false;
    // check if parent is last child and desc has other children
    const isParentLastChild = desc.lastChild === parentTextblock.node;
    if (desc.childCount < 2 || !isParentLastChild)
        return false; // 5 || 4
    const tr = state.tr;
    dispatch?.(tr
        // remove parent text block
        .delete(parentTextblock.pos, parentTextblock.pos + parentTextblock.node.nodeSize)
        // insert empty textblock after deflist node
        .insert(tr.mapping.map(selection.$from.after(parentTextblock.depth - 2)), parentTextblock.node.type.create(parentTextblock.node.attrs)));
    return true;
};
exports.splitDeflist = splitDeflist;
//# sourceMappingURL=commands.js.map
