|
| 1 | +import {Command, TextSelection} from 'prosemirror-state'; |
| 2 | +import {atEndOfCell, findChildTableRows, findParentTableRow} from '../../../../table-utils'; |
| 3 | +import { |
| 4 | + findChildTableCells, |
| 5 | + findParentTable, |
| 6 | + findParentTableCell, |
| 7 | +} from '../../../../table-utils/utils'; |
| 8 | +import {createFakeParagraphNear} from '../../../../utils/selection'; |
| 9 | + |
| 10 | +export function goToNextRow(dir: 'up' | 'down'): Command { |
| 11 | + return (state, dispatch, view) => { |
| 12 | + const parentTable = findParentTable(state.selection); |
| 13 | + const parentRow = findParentTableRow(state.selection); |
| 14 | + const parentCell = findParentTableCell(state.selection); |
| 15 | + |
| 16 | + if (!view || !atEndOfCell(view, dir === 'up' ? -1 : 1)) { |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + if (!parentTable || !parentRow || !parentCell) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + const allRows = findChildTableRows(parentTable.node); |
| 25 | + const rowIndex = allRows.findIndex((node) => node.node === parentRow.node); |
| 26 | + |
| 27 | + let cellIndex; |
| 28 | + |
| 29 | + for (let i = 0; i < parentRow.node.childCount; i++) { |
| 30 | + if (parentRow.node.child(i) === parentCell.node) cellIndex = i; |
| 31 | + } |
| 32 | + |
| 33 | + if (cellIndex === undefined) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + const newRowIndex = rowIndex + (dir === 'up' ? -1 : 1); |
| 38 | + |
| 39 | + if (newRowIndex < 0 || newRowIndex >= allRows.length) { |
| 40 | + createFakeParagraphNear(dir, parentTable)(state, dispatch); |
| 41 | + |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + const newRow = allRows[newRowIndex]; |
| 46 | + const childCells = findChildTableCells(newRow.node); |
| 47 | + const cell = childCells[cellIndex]; |
| 48 | + |
| 49 | + const from = parentTable.start + newRow.pos + cell.pos + 3; |
| 50 | + |
| 51 | + dispatch?.( |
| 52 | + state.tr.setSelection(new TextSelection(state.doc.resolve(from))).scrollIntoView(), |
| 53 | + ); |
| 54 | + |
| 55 | + return true; |
| 56 | + }; |
| 57 | +} |
0 commit comments