diff --git a/shared/editor/nodes/TableHeader.ts b/shared/editor/nodes/TableHeader.ts index a05383043d..9941625d65 100644 --- a/shared/editor/nodes/TableHeader.ts +++ b/shared/editor/nodes/TableHeader.ts @@ -132,13 +132,24 @@ function setupColumnDragTracking( document.body.classList.remove(EditorStyleHelper.tableDragging); if (isDragging && currentToIndex !== fromIndex && isInTable(view.state)) { - const moved = moveTableColumn({ from: fromIndex, to: currentToIndex })( - view.state, - view.dispatch - ); - if (moved) { - // Select the column at its new position - selectColumn(currentToIndex)(view.state, view.dispatch); + // Verify both indices are still valid for the current table. The document + // may have changed during the drag (e.g. collaborative editing) + const currentCols = getCellsInRow(0)(view.state); + const inBounds = + fromIndex >= 0 && + fromIndex < currentCols.length && + currentToIndex >= 0 && + currentToIndex < currentCols.length; + + if (inBounds) { + const moved = moveTableColumn({ from: fromIndex, to: currentToIndex })( + view.state, + view.dispatch + ); + if (moved) { + // Select the column at its new position + selectColumn(currentToIndex)(view.state, view.dispatch); + } } } diff --git a/shared/editor/nodes/TableRow.ts b/shared/editor/nodes/TableRow.ts index de63b1ed41..69998793dd 100644 --- a/shared/editor/nodes/TableRow.ts +++ b/shared/editor/nodes/TableRow.ts @@ -120,13 +120,24 @@ function setupRowDragTracking( document.body.classList.remove(EditorStyleHelper.tableDragging); if (isDragging && currentToIndex !== fromIndex && isInTable(view.state)) { - const moved = moveTableRow({ from: fromIndex, to: currentToIndex })( - view.state, - view.dispatch - ); - if (moved) { - // Select the row at its new position - selectRow(currentToIndex)(view.state, view.dispatch); + // Verify both indices are still valid for the current table. The document + // may have changed during the drag (e.g. collaborative editing) + const currentRows = getRowsInTable(view.state); + const inBounds = + fromIndex >= 0 && + fromIndex < currentRows.length && + currentToIndex >= 0 && + currentToIndex < currentRows.length; + + if (inBounds) { + const moved = moveTableRow({ from: fromIndex, to: currentToIndex })( + view.state, + view.dispatch + ); + if (moved) { + // Select the row at its new position + selectRow(currentToIndex)(view.state, view.dispatch); + } } }