From e77328fb23151191ce356f87163ddba96d173dd6 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Thu, 17 May 2018 01:01:36 +0100 Subject: [PATCH 1/2] Handle tables with no headers by creating an empty Markdown header --- src/tables.js | 16 ++++++++++++---- test/index.html | 14 ++++++++++---- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/tables.js b/src/tables.js index e4fd987..2cb862b 100644 --- a/src/tables.js +++ b/src/tables.js @@ -35,13 +35,21 @@ rules.table = { // Only convert tables with a heading row. // Tables with no heading row are kept using `keep` (see below). filter: function (node) { - return node.nodeName === 'TABLE' && isHeadingRow(node.rows[0]) + return node.nodeName === 'TABLE' }, - replacement: function (content) { + replacement: function (content, node) { + // If table has no heading, add an empty one so as to get a valid Markdown table + var firstRow = node.rows.length ? node.rows[0] : null + var columnCount = firstRow ? firstRow.childNodes.length : 0 + var emptyHeader = '' + if (columnCount && !isHeadingRow(firstRow)) { + emptyHeader = '|' + ' |'.repeat(columnCount) + '\n' + '|' + ' --- |'.repeat(columnCount) + } + // Ensure there are no blank lines content = content.replace('\n\n', '\n') - return '\n\n' + content + '\n\n' + return '\n\n' + emptyHeader + content + '\n\n' } } @@ -91,7 +99,7 @@ function cell (content, node) { export default function tables (turndownService) { turndownService.keep(function (node) { - return node.nodeName === 'TABLE' && !isHeadingRow(node.rows[0]) + return node.nodeName === 'TABLE' }) for (var key in rules) turndownService.addRule(key, rules[key]) } diff --git a/test/index.html b/test/index.html index f14088f..8e73118 100644 --- a/test/index.html +++ b/test/index.html @@ -262,17 +262,20 @@ | --- | -
+
Row 1 Cell 1Row 1 Cell 2
Row 2 Cell 1Row 2 Cell 2
-
<table><tbody><tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr><tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr></tbody></table>
+
|     |     |
+| --- | --- |
+| Row 1 Cell 1 | Row 1 Cell 2 |
+| Row 2 Cell 1 | Row 2 Cell 2 |
-
+
@@ -285,7 +288,10 @@
-
<table><tbody><tr><th>Heading</th><td>Not a heading</td></tr><tr><td>Heading</td><td>Not a heading</td></tr></tbody></table>
+
|     |     |
+| --- | --- |
+| Heading | Not a heading |
+| Heading | Not a heading |
From 813b9a61b024b14606e57f78f15c02e5125bdd7c Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Thu, 17 May 2018 01:29:33 +0100 Subject: [PATCH 2/2] Fix trailing space issue --- src/tables.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tables.js b/src/tables.js index 2cb862b..ce0d483 100644 --- a/src/tables.js +++ b/src/tables.js @@ -46,7 +46,7 @@ rules.table = { if (columnCount && !isHeadingRow(firstRow)) { emptyHeader = '|' + ' |'.repeat(columnCount) + '\n' + '|' + ' --- |'.repeat(columnCount) } - + // Ensure there are no blank lines content = content.replace('\n\n', '\n') return '\n\n' + emptyHeader + content + '\n\n'