|
2 | 2 |
|
3 | 3 | module.exports = table
|
4 | 4 |
|
| 5 | +var xtend = require('xtend') |
5 | 6 | var visit = require('unist-util-visit')
|
6 | 7 | var all = require('../all')
|
7 | 8 |
|
8 | 9 | function table(h, node) {
|
9 | 10 | var align = alignment(node)
|
10 |
| - return h(node, 'table', {align: align}, patch(all(h, node), align.length)) |
| 11 | + return h(node, 'table', {align: align}, toRows(all(h, node), align.length)) |
11 | 12 | }
|
12 | 13 |
|
13 | 14 | // Infer the alignment of the table.
|
@@ -60,23 +61,74 @@ function cell(node) {
|
60 | 61 | }
|
61 | 62 |
|
62 | 63 | // Ensure the amount of cells in a row matches `align.left`.
|
63 |
| -function patch(rows, count) { |
| 64 | +function toRows(rows, count) { |
| 65 | + var nodes = [] |
64 | 66 | var length = rows.length
|
65 | 67 | var index = -1
|
| 68 | + var node |
| 69 | + var queue |
66 | 70 |
|
67 | 71 | while (++index < length) {
|
68 |
| - one(rows[index], count) |
| 72 | + node = rows[index] |
| 73 | + |
| 74 | + if (node.type === 'tableRow') { |
| 75 | + flush() |
| 76 | + add(node) |
| 77 | + } else { |
| 78 | + queue = (queue || []).concat(node) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + flush() |
| 83 | + |
| 84 | + return nodes |
| 85 | + |
| 86 | + function flush() { |
| 87 | + if (queue) { |
| 88 | + add({type: 'tableRow', children: queue}) |
| 89 | + queue = undefined |
| 90 | + } |
69 | 91 | }
|
70 | 92 |
|
71 |
| - return rows |
| 93 | + function add(node) { |
| 94 | + nodes.push(cells(node, count)) |
| 95 | + } |
72 | 96 | }
|
73 | 97 |
|
74 |
| -function one(row, count) { |
75 |
| - var children = row.children |
76 |
| - var length = count + 1 |
77 |
| - var index = children.length |
| 98 | +function cells(row, count) { |
| 99 | + var nodes = [] |
| 100 | + var cells = row.children |
| 101 | + var length = cells.length |
| 102 | + var index = -1 |
| 103 | + var node |
| 104 | + var queue |
| 105 | + |
| 106 | + while (++index < length) { |
| 107 | + node = cells[index] |
| 108 | + |
| 109 | + if (node.type === 'tableCell') { |
| 110 | + flush() |
| 111 | + nodes.push(node) |
| 112 | + } else { |
| 113 | + queue = (queue || []).concat(node) |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + flush() |
| 118 | + |
| 119 | + index = nodes.length |
| 120 | + length = count + 1 |
78 | 121 |
|
79 | 122 | while (++index < length) {
|
80 |
| - children.push({type: 'tableCell', children: []}) |
| 123 | + nodes.push({type: 'tableCell', children: []}) |
| 124 | + } |
| 125 | + |
| 126 | + return xtend(row, {children: nodes}) |
| 127 | + |
| 128 | + function flush() { |
| 129 | + if (queue) { |
| 130 | + nodes.push({type: 'tableCell', children: queue}) |
| 131 | + queue = undefined |
| 132 | + } |
81 | 133 | }
|
82 | 134 | }
|
0 commit comments