| 1 | function processContent(content: string): string { |
| 2 | return content.replace(/<table>[\s\S]*?<\/table>/g, (htmlTable) => { |
| 3 | try { |
| 4 | // Clean up whitespace and newlines |
| 5 | const cleanHtml = htmlTable.replace(/\n\s*/g, ''); |
| 6 | const rows = cleanHtml.match(/<tr>(.*?)<\/tr>/g); |
| 7 | if (!rows) return htmlTable; |
| 8 | |
| 9 | // Parse table data |
| 10 | let tableData: string[][] = []; |
| 11 | let maxColumns = 0; |
| 12 | |
| 13 | // Try to convert to markdown table |
| 14 | try { |
| 15 | rows.forEach((row, rowIndex) => { |
| 16 | if (!tableData[rowIndex]) { |
| 17 | tableData[rowIndex] = []; |
| 18 | } |
| 19 | let colIndex = 0; |
| 20 | const cells = row.match(/<td.*?>(.*?)<\/td>/g) || []; |
| 21 | |
| 22 | cells.forEach((cell) => { |
| 23 | while (tableData[rowIndex][colIndex]) { |
| 24 | colIndex++; |
| 25 | } |
| 26 | const colspan = parseInt(cell.match(/colspan="(\d+)"/)?.[1] || '1'); |
| 27 | const rowspan = parseInt(cell.match(/rowspan="(\d+)"/)?.[1] || '1'); |
| 28 | const content = cell.replace(/<td.*?>|<\/td>/g, '').trim(); |
| 29 | |
| 30 | for (let i = 0; i < rowspan; i++) { |
| 31 | for (let j = 0; j < colspan; j++) { |
| 32 | if (!tableData[rowIndex + i]) { |
| 33 | tableData[rowIndex + i] = []; |
| 34 | } |
| 35 | tableData[rowIndex + i][colIndex + j] = i === 0 && j === 0 ? content : '^^'; |
| 36 | } |
| 37 | } |
| 38 | colIndex += colspan; |
| 39 | maxColumns = Math.max(maxColumns, colIndex); |
| 40 | }); |
| 41 | |
| 42 | for (let i = 0; i < maxColumns; i++) { |
| 43 | if (!tableData[rowIndex][i]) { |
| 44 | tableData[rowIndex][i] = ' '; |
| 45 | } |
| 46 | } |
| 47 | }); |
| 48 | const chunks: string[] = []; |
| 49 | |
| 50 | const headerCells = tableData[0] |
| 51 | .slice(0, maxColumns) |
| 52 | .map((cell) => (cell === '^^' ? ' ' : cell || ' ')); |
| 53 | const headerRow = '| ' + headerCells.join(' | ') + ' |'; |
| 54 | chunks.push(headerRow); |
| 55 | |
| 56 | const separator = '| ' + Array(headerCells.length).fill('---').join(' | ') + ' |'; |
| 57 | chunks.push(separator); |
| 58 | |
| 59 | tableData.slice(1).forEach((row) => { |
| 60 | const paddedRow = row |