"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.goToNextCell = goToNextCell;
const prosemirror_state_1 = require("prosemirror-state");
const utils_1 = require("../utils.js");
function goToNextCell(dir) {
    return (state, dispatch) => {
        const parentTable = (0, utils_1.findParentTable)(state.selection);
        const parentCell = (0, utils_1.findParentTableCell)(state.selection);
        if (!parentTable || !parentCell) {
            return false;
        }
        const allCells = (0, utils_1.findChildTableCells)(parentTable.node);
        const index = allCells.findIndex((node) => node.node === parentCell.node);
        const isFirstCell = index === 0;
        const isLastCell = index === allCells.length - 1;
        const selectText = (from, to) => {
            dispatch?.(state.tr
                .setSelection(prosemirror_state_1.TextSelection.between(state.doc.resolve(from), state.doc.resolve(to)))
                .scrollIntoView());
        };
        const selectCell = (index) => {
            const cell = allCells[index];
            const from = parentTable.start + cell.pos;
            const to = from + cell.node.nodeSize;
            selectText(from, to);
        };
        const selectPrevCell = () => selectCell(index - 1);
        const selectCurrentCell = () => selectCell(index);
        const selectNextCell = () => selectCell(index + 1);
        if (dir === 'prev') {
            if (isFirstCell) {
                selectCurrentCell();
            }
            else {
                selectPrevCell();
            }
            return true;
        }
        if (dir === 'next') {
            if (isLastCell) {
                selectCurrentCell();
            }
            else {
                selectNextCell();
            }
            return true;
        }
        return false;
    };
}
//# sourceMappingURL=goToNextCell.js.map
