import { TextSelection } from "prosemirror-state";
import { isInTable, selectionCell } from "./queries.js";
function findNextCell($cell, dir) {
  if (dir < 0) {
    const before = $cell.nodeBefore;
    if (before) {
      return $cell.pos - before.nodeSize;
    }
    for (let row = $cell.index(-1) - 1, rowEnd = $cell.before(); row >= 0; row--) {
      const rowNode = $cell.node(-1).child(row);
      const lastChild = rowNode.lastChild;
      if (lastChild) {
        return rowEnd - 1 - lastChild.nodeSize;
      }
      rowEnd -= rowNode.nodeSize;
    }
  } else {
    if ($cell.index() < $cell.parent.childCount - 1) {
      return $cell.pos + $cell.nodeAfter.nodeSize;
    }
    const table = $cell.node(-1);
    for (let row = $cell.indexAfter(-1), rowStart = $cell.after(); row < table.childCount; row++) {
      const rowNode = table.child(row);
      if (rowNode.childCount) {
        return rowStart + 1;
      }
      rowStart += rowNode.nodeSize;
    }
  }
  return null;
}
function moveCellForward($pos) {
  return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize);
}
function goToNextCell(direction) {
  return function(state, dispatch) {
    if (!isInTable(state)) {
      return false;
    }
    const cell = findNextCell(selectionCell(state), direction);
    if (cell === null) {
      return false;
    }
    if (dispatch) {
      const $cell = state.doc.resolve(cell);
      dispatch(
        state.tr.setSelection(TextSelection.between($cell, moveCellForward($cell))).scrollIntoView()
      );
    }
    return true;
  };
}
export {
  goToNextCell,
  moveCellForward
};
//# sourceMappingURL=navigation.js.map
