From c44f9f685d1aceddb5f848aa84b7e9e715097189 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Fri, 16 Jan 2026 11:17:33 +0500 Subject: [PATCH] editor: parse csv directly to prosemirror nodes --- .../editor/src/extensions/table/actions.ts | 53 ++++++++----------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/packages/editor/src/extensions/table/actions.ts b/packages/editor/src/extensions/table/actions.ts index 97715eafe..97b7fa438 100644 --- a/packages/editor/src/extensions/table/actions.ts +++ b/packages/editor/src/extensions/table/actions.ts @@ -25,6 +25,8 @@ import { saveAs } from "file-saver"; import { unparse, parse } from "papaparse"; import { hasPermission } from "../../types.js"; import { useToolbarStore } from "../../toolbar/stores/toolbar-store.js"; +import { getTableNodeTypes } from "./utilities/getTableNodeTypes.js"; +import { createCell } from "./utilities/createCell.js"; type TableCell = { cell: Node; @@ -193,44 +195,34 @@ function selectColumn( return true; } -function escapeCell(cell: string): string { - return (cell || "") - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -} - function importCsvToTable(csvText: string, editor: Editor) { - const result = parse(csvText, { + const result = parse(csvText, { skipEmptyLines: true }); if (!result.data || result.data.length === 0) return ""; - const rows = result.data as string[][]; - let tableHTML = ""; + const { schema } = editor.state; + const types = getTableNodeTypes(schema); - if (rows.length > 0) { - tableHTML += ""; - for (const cell of rows[0]) { - tableHTML += ``; - } - tableHTML += ""; - } + const tableRows = result.data.map((row, rowIndex) => { + const isHeaderRow = rowIndex === 0; + const cellType = isHeaderRow ? types.header_cell : types.cell; - tableHTML += ""; - for (let i = 1; i < rows.length; i++) { - const row = rows[i]; - tableHTML += ""; - for (const cell of row) { - tableHTML += ``; - } - tableHTML += ""; - } - tableHTML += "

${escapeCell(cell)}

${escapeCell(cell)}

"; + const cells = row + .map((cellText) => { + const paragraphNode = cellText + ? schema.nodes.paragraph.create(null, schema.text(cellText)) + : schema.nodes.paragraph.create(); + return createCell(cellType, paragraphNode); + }) + .filter((cell): cell is Node => cell != null); - editor.chain().focus().insertContent(tableHTML).run(); + return types.row.createChecked(null, cells); + }); + + const tableNode = types.table.createChecked(null, tableRows); + + editor.chain().focus().insertContent(tableNode.toJSON()).run(); } function exportToCSV(editor?: Editor) { @@ -261,6 +253,5 @@ export { selectRow, selectColumn, exportToCSV, - escapeCell, importCsvToTable };