Skip to content

Commit

Permalink
Fix markdown table cell linebreak rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
Trinovantes committed Jun 30, 2024
1 parent e52cb17 commit 74f4b59
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/RstNode/Table/TableCell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,19 @@ export const tableCellGenerators = createNodeGenerators(

(generatorState, node) => {
const cellText = generatorState.getChildrenText(() => {
for (const child of node.children) {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i]
if (!(child instanceof RstParagraph)) {
throw new RstGeneratorError(generatorState, 'Cannot render non-paragraphs in Markdown tables')
}
if (i > 0) {
generatorState.writeText('<br>')
}

generatorState.visitNodes(child.children)
}
})

generatorState.writeText(` ${cellText.replaceAll('\n', '<br>')} `)
generatorState.writeText(` ${cellText.replaceAll('\n', ' ')} `)
},
)
100 changes: 100 additions & 0 deletions tests/unit/RstNode/Table/GridTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,3 +593,103 @@ describe('complex grid table', () => {
</table>
`)
})

describe('when cell has multiple paragraphs, it renders as line breaks in markdown', () => {
const input = `
+-+-+
|A|B|
+=+=+
|C|D|
| |D|
|C|D|
+-+-+
`

testParser(input, [
{
type: RstNodeType.Table,
children: [
{
type: RstNodeType.TableRow,
data: {
isHeadRow: true,
},
children: [
{
type: RstNodeType.TableCell,
text: 'A',
},
{
type: RstNodeType.TableCell,
text: 'B',
},
],
},
{
type: RstNodeType.TableRow,
children: [
{
type: RstNodeType.TableCell,
children: [
{
type: RstNodeType.Paragraph,
text: 'C',
},
{
type: RstNodeType.Paragraph,
text: 'C',
},
],
},
{
type: RstNodeType.TableCell,
text: 'D\nD\nD',
},
],
},
],
},
])

testGenerator(input, `
<table>
<thead>
<tr>
<th>
<p>
A
</p>
</th>
<th>
<p>
B
</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>
C
</p>
<p>
C
</p>
</td>
<td>
<p>
D
D
D
</p>
</td>
</tr>
</tbody>
</table>
`, `
| A | B |
| --- | --- |
| C<br>C | D D D |
`)
})
2 changes: 1 addition & 1 deletion tests/unit/RstNode/Table/SimpleTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ describe('when there is empty cell in second row in first column, it parses as s
</tbody>
</table>
`, `
| col 1 | col 2<br>test |
| col 1 | col 2 test |
| --- | --- |
| test1 | test2 |
`)
Expand Down

0 comments on commit 74f4b59

Please sign in to comment.