|
| 1 | +import { |
| 2 | + createTableCell, |
| 3 | + createTableRow, |
| 4 | + trimModelForSelection, |
| 5 | +} from 'roosterjs-content-model-dom'; |
| 6 | +import type { |
| 7 | + ContentModelBlock, |
| 8 | + ContentModelTable, |
| 9 | + ContentModelTableCellFormat, |
| 10 | + IEditor, |
| 11 | + ReadonlyContentModelTable, |
| 12 | +} from 'roosterjs-content-model-types'; |
| 13 | + |
| 14 | +/** |
| 15 | + * @internal |
| 16 | + */ |
| 17 | +export function getSelectedContentForTable(editor: IEditor): ContentModelBlock[][] { |
| 18 | + const selectedRows: ContentModelBlock[][] = []; |
| 19 | + const selection = editor.getDOMSelection(); |
| 20 | + if (selection && (selection?.type !== 'range' || !selection.range.collapsed)) { |
| 21 | + const selectedModel = editor.getContentModelCopy('disconnected'); |
| 22 | + trimModelForSelection(selectedModel, selection); |
| 23 | + |
| 24 | + for (const block of selectedModel.blocks) { |
| 25 | + if (block.blockType === 'Table') { |
| 26 | + extractTableCellsContent(block, selectedRows); |
| 27 | + } else { |
| 28 | + selectedRows.push([block as ContentModelBlock]); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return selectedRows; |
| 34 | +} |
| 35 | + |
| 36 | +function extractTableCellsContent( |
| 37 | + table: ReadonlyContentModelTable, |
| 38 | + selectedRows: ContentModelBlock[][] |
| 39 | +) { |
| 40 | + for (const row of table.rows) { |
| 41 | + const rowBlocks: ContentModelBlock[] = []; |
| 42 | + for (const cell of row.cells) { |
| 43 | + if (!cell.spanLeft && !cell.spanAbove) { |
| 44 | + rowBlocks.push(...(cell.blocks as ContentModelBlock[])); |
| 45 | + } |
| 46 | + } |
| 47 | + if (rowBlocks.length > 0) { |
| 48 | + selectedRows.push(rowBlocks); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * @internal |
| 55 | + */ |
| 56 | +export function insertTableContent( |
| 57 | + table: ContentModelTable, |
| 58 | + contentRows: ContentModelBlock[][], |
| 59 | + colNumber: number, |
| 60 | + customCellFormat?: ContentModelTableCellFormat |
| 61 | +) { |
| 62 | + let rowIndex = 0; |
| 63 | + for (const rowBlocks of contentRows) { |
| 64 | + if (!table.rows[rowIndex]) { |
| 65 | + const row = createTableRow(); |
| 66 | + for (let i = 0; i < colNumber; i++) { |
| 67 | + const cell = createTableCell( |
| 68 | + undefined /*spanLeftOrColSpan */, |
| 69 | + undefined /*spanAboveOrRowSpan */, |
| 70 | + undefined /* isHeader */, |
| 71 | + customCellFormat |
| 72 | + ); |
| 73 | + row.cells.push(cell); |
| 74 | + } |
| 75 | + table.rows.push(row); |
| 76 | + } |
| 77 | + |
| 78 | + let cellIndex = 0; |
| 79 | + for (const block of rowBlocks) { |
| 80 | + if (cellIndex < table.rows[rowIndex].cells.length) { |
| 81 | + table.rows[rowIndex].cells[cellIndex].blocks = [block]; |
| 82 | + } |
| 83 | + cellIndex++; |
| 84 | + } |
| 85 | + rowIndex++; |
| 86 | + } |
| 87 | +} |
0 commit comments