"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertEmptyRow = void 0;
const state_1 = require("../../../../../../pm/state.js");
const lodash_1 = require("../../../../../../lodash.js");
const table_desc_1 = require("../../../../../../table-utils/table-desc.js");
const YfmTableSpecs_1 = require("../../../YfmTableSpecs/index.js");
const insertEmptyRow = (params) => {
    return (state, dispatch) => {
        const table = state.doc.nodeAt(params.tablePos);
        const tableDesc = table && table_desc_1.TableDesc.create(table)?.bind(params.tablePos);
        if (!tableDesc)
            return false;
        const rowIdx = Math.min(Math.max(params.rowIndex, 0), tableDesc.rows);
        if (dispatch) {
            let posToInsert;
            let newCellsCount = tableDesc.cols;
            const incrementRowspan = [];
            if (rowIdx === 0 || rowIdx === tableDesc.rows) {
                posToInsert =
                    rowIdx === 0
                        ? tableDesc.getPosForRow(0).from
                        : tableDesc.getPosForRow(tableDesc.rows - 1).to;
            }
            else {
                posToInsert = tableDesc.getPosForRow(rowIdx).from;
                for (let colIdx = 0; colIdx < tableDesc.cols; colIdx++) {
                    const cell = tableDesc.base.rowsDesc[rowIdx].cells[colIdx];
                    if (cell.type === 'virtual' && cell.rowspan) {
                        newCellsCount--;
                        incrementRowspan.push(cell.rowspan);
                    }
                }
            }
            const { tr } = state;
            for (const [rowIdx, colIdx] of (0, lodash_1.uniqWith)(incrementRowspan, lodash_1.isEqual)) {
                const cell = tableDesc.base.rowsDesc[rowIdx].cells[colIdx];
                const cellPos = tableDesc.getPosForCell(rowIdx, colIdx);
                tr.setNodeAttribute(cellPos.from, 'rowspan', cell.rowspan + 1);
            }
            tr.insert(posToInsert, createSimpleRow(state.schema, newCellsCount));
            tr.setSelection(state_1.TextSelection.near(tr.doc.resolve(posToInsert), 1));
            dispatch(tr.scrollIntoView());
        }
        return true;
    };
};
exports.insertEmptyRow = insertEmptyRow;
const createSimpleRow = (schema, cols) => {
    const tr = (0, YfmTableSpecs_1.yfmTableRowType)(schema);
    const td = (0, YfmTableSpecs_1.yfmTableCellType)(schema);
    return tr.create(null, (0, lodash_1.range)(0, cols).map(() => td.createAndFill()));
};
//# sourceMappingURL=insert-empty-row.js.map
