From a4ef6870b789de77c2806e14730c0bf9d88eadba Mon Sep 17 00:00:00 2001 From: Dom Christie Date: Fri, 24 Nov 2017 11:18:27 +0000 Subject: [PATCH] Improve table heading row conversion --- src/tables.js | 38 ++++++++++++++++-- test/index.html | 102 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+), 3 deletions(-) diff --git a/src/tables.js b/src/tables.js index cfeb1e246..a5fd2096c 100644 --- a/src/tables.js +++ b/src/tables.js @@ -1,3 +1,5 @@ +var indexOf = Array.prototype.indexOf +var every = Array.prototype.every var rules = {} rules.tableCell = { @@ -13,10 +15,10 @@ rules.tableRow = { var borderCells = '' var alignMap = { left: ':--', right: '--:', center: ':-:' } - if (node.parentNode.nodeName === 'THEAD') { + if (isHeadingRow(node)) { for (var i = 0; i < node.childNodes.length; i++) { - var align = node.childNodes[i].attributes.align var border = '---' + var align = node.childNodes[i].attributes.align if (align) border = alignMap[align.value] || border @@ -43,8 +45,38 @@ rules.tableSection = { } } +// A tr is a heading row if: +// - the parent is a THEAD +// - or if its the first child of the TABLE or the first TBODY (possibly +// following a blank THEAD) +// - and every cell is a TH +function isHeadingRow (tr) { + var parentNode = tr.parentNode + return ( + parentNode.nodeName === 'THEAD' || + ( + parentNode.firstChild === tr && + (parentNode.nodeName === 'TABLE' || isFirstTbody(parentNode)) && + every.call(tr.childNodes, function (n) { return n.nodeName === 'TH' }) + ) + ) +} + +function isFirstTbody (element) { + var previousSibling = element.previousSibling + return ( + element.nodeName === 'TBODY' && ( + !previousSibling || + ( + previousSibling.nodeName === 'THEAD' && + /^\s*$/i.test(previousSibling.textContent) + ) + ) + ) +} + function cell (content, node) { - var index = Array.prototype.indexOf.call(node.parentNode.childNodes, node) + var index = indexOf.call(node.parentNode.childNodes, node) var prefix = ' ' if (index === 0) prefix = '| ' return prefix + content + ' |' diff --git a/test/index.html b/test/index.html index bb5ac6d1b..659e1d0ee 100644 --- a/test/index.html +++ b/test/index.html @@ -171,6 +171,108 @@ | Row 3 | Row 3 | +
+
+ + + + + + + +
Heading
Content
+
+
| Heading |
+| --- |
+| Content |
+
+ +
+
+ + + + + + + + + +
Heading
Content
+
+
| Heading |
+| --- |
+| Content |
+
+ +
+
+ + + + + + + + + + + + + + + + + +
Heading
Content
Heading
Content
+
+
| Heading |
+| --- |
+| Content |
+| Heading |
+| Content |
+
+ +
+
+ + + + + + + + + +
HeadingNot a heading
HeadingNot a heading
+
+
| Heading | Not a heading |
+| Heading | Not a heading |
+
+ +
+
+ + + +
Heading
Cell
+
+
| Heading |
+| --- |
+| Cell |
+
+ +
+
+ + + +
Heading
+
+
| Heading |
+| --- |
+
+