62 lines
1.8 KiB
JavaScript

function renderTableOfContents() {
const root = document.querySelector("table-of-contents");
const list = document.createElement("ul");
const headers = document.querySelectorAll("h2,h3,h4,h5,h6");
const ancestors = [];
for (const header of headers) {
const depth = parseInt(header.tagName.slice(1)) - 1;
while (ancestors.length >= depth) {
ancestors.pop();
}
const li = document.createElement("li");
const a = document.createElement("a");
a.textContent = header.textContent;
a.href = `#${header.id}`;
const ul = document.createElement("ul");
li.replaceChildren(a, ul);
const mostRecent = ancestors[ancestors.length - 1];
if (mostRecent === undefined) {
list.appendChild(li);
} else {
mostRecent.appendChild(li);
}
ancestors.push(ul);
}
root.replaceChildren(list);
}
function slugify(elements) {
console.log(elements);
return elements
.map((element, i) => {
if (i === 0) return null;
const content = element.textContent.trim();
if (content.startsWith("lib.")) {
const [name] = content.match(/^lib\.[^\(]+/);
return name.trim();
}
return content;
})
.filter((x) => x !== null)
.join("-");
}
function attachIdToHeaders() {
const headers = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
const ancestors = [];
for (const header of headers) {
const depth = parseInt(header.tagName.slice(1));
while (ancestors.length >= depth) {
ancestors.pop();
}
ancestors.push(header);
if (depth > 1) header.id = slugify(ancestors);
}
}
attachIdToHeaders();
renderTableOfContents();