"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixPastedTableBodies = fixPastedTableBodies;
exports.unpackSingleCellTable = unpackSingleCellTable;
const prosemirror_model_1 = require("prosemirror-model");
const const_1 = require("../../../table-utils/const.js");
const nodes_1 = require("../../../utils/nodes.js");
const utils_1 = require("./utils.js");
function fixPastedTableBodies(slice, schema) {
    if (slice.content.firstChild?.type === (0, utils_1.yfmTableBodyType)(schema)) {
        const tRows = [];
        let bodiesSize = 0;
        for (const { node, offset } of (0, nodes_1.getChildrenOfNode)(slice.content)) {
            if (node.type !== (0, utils_1.yfmTableBodyType)(schema))
                break;
            tRows.push(...(0, nodes_1.getChildrenOfNode)(node).map((item) => item.node));
            bodiesSize = offset + node.nodeSize;
        }
        const tableNode = (0, utils_1.yfmTableType)(schema).create(null, (0, utils_1.yfmTableBodyType)(schema).create(null, tRows));
        slice = new prosemirror_model_1.Slice(prosemirror_model_1.Fragment.from(tableNode).append(slice.content.cut(bodiesSize)), 0, 0);
    }
    return slice;
}
function unpackSingleCellTable(slice) {
    if (slice.content.childCount !== 1)
        return slice;
    if (!isSingeCellTable(slice.content.child(0)))
        return slice;
    let node = slice.content.child(0);
    while (node && node.type.spec.tableRole !== const_1.TableRole.Cell) {
        node = node.lastChild;
    }
    // get content from tableCell
    const newFragment = prosemirror_model_1.Fragment.from(node?.content);
    const newSlice = new prosemirror_model_1.Slice(newFragment, 0, 0);
    return newSlice;
}
function isSingeCellTable(node) {
    const { schema } = node.type;
    if (node.type === (0, utils_1.yfmTableCellType)(schema))
        return true;
    if (node.type === (0, utils_1.yfmTableRowType)(schema) && node.childCount === 1)
        return isSingeCellTable(node.child(0));
    if (node.type === (0, utils_1.yfmTableBodyType)(schema) && node.childCount === 1)
        return isSingeCellTable(node.child(0));
    if (node.type === (0, utils_1.yfmTableType)(schema) && node.lastChild?.type === (0, utils_1.yfmTableBodyType)(schema))
        return isSingeCellTable(node.lastChild);
    return false;
}
//# sourceMappingURL=paste.js.map
