"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.goToNextRow = goToNextRow;
const prosemirror_state_1 = require("prosemirror-state");
const table_utils_1 = require("../../../../table-utils/index.js");
const selection_1 = require("../../../../utils/selection.js");
const Selection_1 = require("../../../behavior/Selection/index.js");
function goToNextRow(dir) {
    return (state, dispatch, view) => {
        const parentTable = (0, table_utils_1.findParentTable)(state.selection);
        const parentRow = (0, table_utils_1.findParentTableRow)(state.selection);
        const parentCell = (0, table_utils_1.findParentTableCell)(state.selection);
        if (!view || !(0, table_utils_1.atEndOfCell)(view, dir === 'up' ? -1 : 1)) {
            return false;
        }
        if (!parentTable || !parentRow || !parentCell) {
            return false;
        }
        const allRows = (0, table_utils_1.findChildTableRows)(parentTable.node);
        const rowIndex = allRows.findIndex((node) => node.node === parentRow.node);
        let cellIndex;
        for (let i = 0; i < parentRow.node.childCount; i++) {
            if (parentRow.node.child(i) === parentCell.node)
                cellIndex = i;
        }
        if (cellIndex === undefined) {
            return false;
        }
        const newRowIndex = rowIndex + (dir === 'up' ? -1 : 1);
        if (newRowIndex < 0 || newRowIndex >= allRows.length) {
            const sel = state.selection;
            if ((0, selection_1.isTextSelection)(sel) && view.endOfTextblock(dir)) {
                const [direction, $cursor] = dir === 'up' ? ['before', sel.$from] : ['after', sel.$to];
                const $pos = (0, Selection_1.findFakeParaPosForTextSelection)(sel, direction) ??
                    (0, Selection_1.findFakeParaPosClosestToPos)($cursor, $cursor.depth - 2, direction);
                if ($pos) {
                    dispatch?.((0, Selection_1.createFakeParagraph)(state.tr, $pos, direction).scrollIntoView());
                    return true;
                }
            }
            return false;
        }
        const newRow = allRows[newRowIndex];
        const childCells = (0, table_utils_1.findChildTableCells)(newRow.node);
        const cell = childCells[cellIndex];
        const from = parentTable.start + newRow.pos + cell.pos + 3;
        dispatch?.(state.tr.setSelection(new prosemirror_state_1.TextSelection(state.doc.resolve(from))).scrollIntoView());
        return true;
    };
}
//# sourceMappingURL=goToNextRow.js.map
