From a64a5165e79bd2424e594b793843a7158e7d4fb4 Mon Sep 17 00:00:00 2001 From: "Lucas.Xu" Date: Mon, 26 Aug 2024 15:13:46 +0800 Subject: [PATCH] fix: table cell insertion error (#870) --- .../table_block_component/table_action.dart | 55 +++++++++++++++---- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/lib/src/editor/block_component/table_block_component/table_action.dart b/lib/src/editor/block_component/table_block_component/table_action.dart index a4509cb58..95e9603a9 100644 --- a/lib/src/editor/block_component/table_block_component/table_action.dart +++ b/lib/src/editor/block_component/table_block_component/table_action.dart @@ -131,8 +131,10 @@ void _addRow(Node tableNode, int position, EditorState editorState) async { final int rowsLen = tableNode.attributes[TableBlockKeys.rowsLen]; final int colsLen = tableNode.attributes[TableBlockKeys.colsLen]; - final transaction = editorState.transaction; + // insert new rows + var error = false; + // generate new table cell nodes & update node attributes for (var i = 0; i < colsLen; i++) { final firstCellInCol = getCellNode(tableNode, i, 0); final colBgColor = @@ -150,27 +152,58 @@ void _addRow(Node tableNode, int position, EditorState editorState) async { children: [paragraphNode()], ); - final Path insertPath; + late Path insertPath; if (position == 0) { - insertPath = getCellNode(tableNode, i, 0)!.path; + final firstCellInCol = getCellNode(tableNode, i, 0); + if (firstCellInCol == null) { + error = true; + break; + } + insertPath = firstCellInCol.path; } else { - insertPath = getCellNode(tableNode, i, position - 1)!.path.next; + final cellInPrevRow = getCellNode(tableNode, i, position - 1); + if (cellInPrevRow == null) { + error = true; + break; + } + insertPath = cellInPrevRow.path.next; } + final transaction = editorState.transaction; + if (position != rowsLen) { for (var j = position; j < rowsLen; j++) { - final node = getCellNode(tableNode, i, j)!; - transaction.updateNode(node, {TableCellBlockKeys.rowPosition: j + 1}); + final cellNode = getCellNode(tableNode, i, j); + if (cellNode == null) { + error = true; + break; + } + transaction.updateNode( + cellNode, + { + TableCellBlockKeys.rowPosition: j + 1, + }, + ); } } - transaction.insertNode( - insertPath, - newCellNode(tableNode, node), - ); + transaction.insertNode(insertPath, node); + + await editorState.apply(transaction, withUpdateSelection: false); } - transaction.updateNode(tableNode, {TableBlockKeys.rowsLen: rowsLen + 1}); + if (error) { + Log.editor.debug('unable to insert row'); + return; + } + + final transaction = editorState.transaction; + + // update the row length + transaction.updateNode(tableNode, { + TableBlockKeys.rowsLen: rowsLen + 1, + }); + await editorState.apply(transaction, withUpdateSelection: false); }