|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +module.exports = table; |
| 4 | + |
| 5 | +var visit = require('unist-util-visit'); |
| 6 | +var all = require('../all'); |
| 7 | + |
| 8 | +function table(h, node) { |
| 9 | + var align = alignment(node); |
| 10 | + return h(node, 'table', {align: align}, patch(all(h, node), align.length)); |
| 11 | +} |
| 12 | + |
| 13 | +/* Infer the alignment of the table. */ |
| 14 | +function alignment(node) { |
| 15 | + var align = []; |
| 16 | + |
| 17 | + visit(node, visitor); |
| 18 | + |
| 19 | + return align; |
| 20 | + |
| 21 | + function visitor(child, index, parent) { |
| 22 | + var pos; |
| 23 | + |
| 24 | + if (cell(child)) { |
| 25 | + pos = cellsBefore(parent, child); |
| 26 | + if (!align[pos]) { |
| 27 | + align[pos] = infer(child) || null; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/* Get the alignment of a cell. */ |
| 34 | +function infer(node) { |
| 35 | + return node.properties.align; |
| 36 | +} |
| 37 | + |
| 38 | +/* Count cells in `parent` before `node`. */ |
| 39 | +function cellsBefore(parent, node) { |
| 40 | + var children = parent.children; |
| 41 | + var length = children.length; |
| 42 | + var index = -1; |
| 43 | + var child; |
| 44 | + var pos = 0; |
| 45 | + |
| 46 | + while (++index < length) { |
| 47 | + child = children[index]; |
| 48 | + |
| 49 | + if (child === node) { |
| 50 | + break; |
| 51 | + } |
| 52 | + |
| 53 | + if (cell(child)) { |
| 54 | + pos++; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return pos; |
| 59 | +} |
| 60 | + |
| 61 | +/* Check if `node` is a cell. */ |
| 62 | +function cell(node) { |
| 63 | + return node.tagName === 'th' || node.tagName === 'td'; |
| 64 | +} |
| 65 | + |
| 66 | +/* Ensure the amount of cells in a row matches `align.left`. */ |
| 67 | +function patch(rows, count) { |
| 68 | + var length = rows.length; |
| 69 | + var index = -1; |
| 70 | + |
| 71 | + while (++index < length) { |
| 72 | + one(rows[index], count); |
| 73 | + } |
| 74 | + |
| 75 | + return rows; |
| 76 | +} |
| 77 | + |
| 78 | +function one(row, count) { |
| 79 | + var children = row.children; |
| 80 | + var length = count + 1; |
| 81 | + var index = children.length; |
| 82 | + |
| 83 | + while (++index < length) { |
| 84 | + children.push({type: 'tableCell', children: []}); |
| 85 | + } |
| 86 | +} |
0 commit comments