|
| 1 | +/** |
| 2 | + * @author Titus Wormer |
| 3 | + * @copyright 2015 Titus Wormer |
| 4 | + * @license MIT |
| 5 | + * @module mdast:toc |
| 6 | + * @fileoverview Generate a Table of Contents (TOC) from a given Markdown file. |
| 7 | + */ |
| 8 | + |
| 9 | + /* Expose. */ |
| 10 | + module.exports = insert; |
| 11 | + |
| 12 | + /* Dependencies */ |
| 13 | + var listItem = require('./list-item'); |
| 14 | + var list = require('./list'); |
| 15 | + |
| 16 | + /* Constants */ |
| 17 | + var LIST = 'list'; |
| 18 | + var LIST_ITEM = 'listItem'; |
| 19 | + var PARAGRAPH = 'paragraph'; |
| 20 | + var LINK = 'link'; |
| 21 | + var TEXT = 'text'; |
| 22 | + |
| 23 | + /** |
| 24 | + * Insert a `node` into a `parent`. |
| 25 | + * |
| 26 | + * @param {Object} node - `node` to insert. |
| 27 | + * @param {Object} parent - Parent of `node`. |
| 28 | + * @param {boolean?} [tight] - Prefer tight list-items. |
| 29 | + * @return {undefined} |
| 30 | + */ |
| 31 | + function insert(node, parent, tight) { |
| 32 | + var children = parent.children; |
| 33 | + var length = children.length; |
| 34 | + var last = children[length - 1]; |
| 35 | + var isLoose = false; |
| 36 | + var index; |
| 37 | + var item; |
| 38 | + |
| 39 | + if (node.depth === 1) { |
| 40 | + item = listItem(); |
| 41 | + |
| 42 | + item.children.push({ |
| 43 | + type: PARAGRAPH, |
| 44 | + children: [ |
| 45 | + { |
| 46 | + type: LINK, |
| 47 | + title: null, |
| 48 | + url: '#' + node.id, |
| 49 | + children: [ |
| 50 | + { |
| 51 | + type: TEXT, |
| 52 | + value: node.value |
| 53 | + } |
| 54 | + ] |
| 55 | + } |
| 56 | + ] |
| 57 | + }); |
| 58 | + |
| 59 | + children.push(item); |
| 60 | + } else if (last && last.type === LIST_ITEM) { |
| 61 | + insert(node, last, tight); |
| 62 | + } else if (last && last.type === LIST) { |
| 63 | + node.depth--; |
| 64 | + |
| 65 | + insert(node, last); |
| 66 | + } else if (parent.type === LIST) { |
| 67 | + item = listItem(); |
| 68 | + |
| 69 | + insert(node, item); |
| 70 | + |
| 71 | + children.push(item); |
| 72 | + } else { |
| 73 | + item = list(); |
| 74 | + node.depth--; |
| 75 | + |
| 76 | + insert(node, item); |
| 77 | + |
| 78 | + children.push(item); |
| 79 | + } |
| 80 | + |
| 81 | + /* |
| 82 | + * Properly style list-items with new lines. |
| 83 | + */ |
| 84 | + |
| 85 | + if (parent.type === LIST_ITEM) { |
| 86 | + parent.loose = tight ? false : children.length > 1; |
| 87 | + } else { |
| 88 | + if (tight) { |
| 89 | + isLoose = false; |
| 90 | + } else { |
| 91 | + index = -1; |
| 92 | + |
| 93 | + while (++index < length) { |
| 94 | + if (children[index].loose) { |
| 95 | + isLoose = true; |
| 96 | + |
| 97 | + break; |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + index = -1; |
| 103 | + |
| 104 | + while (++index < length) { |
| 105 | + children[index].loose = isLoose; |
| 106 | + } |
| 107 | + } |
| 108 | + } |
0 commit comments