(document)
| 106 | } |
| 107 | |
| 108 | function generateTableOfContents (document) { |
| 109 | const headers = walkHeaders(document.getElementById('_content')) |
| 110 | |
| 111 | // The nesting depth of headers are not necessarily the header level. |
| 112 | // (eg, h1 > h3 > h5 is a depth of three even though there's an h5.) |
| 113 | const hierarchy = [] |
| 114 | for (const header of headers) { |
| 115 | const level = headerLevel(header) |
| 116 | |
| 117 | while (hierarchy.length && hierarchy[hierarchy.length - 1].headerLevel > level) { |
| 118 | hierarchy.pop() |
| 119 | } |
| 120 | |
| 121 | if (!hierarchy.length || hierarchy[hierarchy.length - 1].headerLevel < level) { |
| 122 | const newList = document.createElement('ul') |
| 123 | newList.headerLevel = level |
| 124 | |
| 125 | if (hierarchy.length) { |
| 126 | hierarchy[hierarchy.length - 1].appendChild(newList) |
| 127 | } |
| 128 | |
| 129 | hierarchy.push(newList) |
| 130 | } |
| 131 | |
| 132 | const element = document.createElement('li') |
| 133 | |
| 134 | const link = document.createElement('a') |
| 135 | link.setAttribute('href', `#${header.getAttribute('id')}`) |
| 136 | link.innerHTML = header.innerHTML |
| 137 | element.appendChild(link) |
| 138 | |
| 139 | hierarchy[hierarchy.length - 1].appendChild(element) |
| 140 | } |
| 141 | |
| 142 | return hierarchy[0] |
| 143 | } |
| 144 | |
| 145 | function walkHeaders (element, headers = []) { |
| 146 | for (const child of element.childNodes) { |
no test coverage detected