Build a nested heading tree and assign unique slug ids
A documentation site shows an “On this page” sidebar next to every article. The sidebar is a nested list of the article’s headings, and each entry links to #id of its heading. Authors rarely add ids by hand, so the outline builder must create readable, unique ids and write them onto the headings so the links work.
Implement buildOutline(root). It reads the headings inside the DOM element root and returns a tree of outline nodes.
buildOutline(root) // => Array<{ id: string, text: string, level: number, children: Node[] }>
<h1> to <h6> that is a descendant of root, in document order. root itself is not included.level is the heading’s number: 1 for <h1>, 6 for <h6>.text is the heading’s textContent with every run of whitespace collapsed to one space and the ends trimmed.text is empty, if it has a data-toc-skip attribute, or if it or any ancestor below root has the hidden attribute. Skipped headings get no id and do not affect nesting.A heading becomes a child of the closest earlier (counted) heading with a smaller level. If there is none, it is a top-level node. Levels can skip: an <h4> right after an <h2> is a child of that <h2>. A heading with the same or a smaller level than the previous one closes that branch.
id attribute keeps it, and the node uses it as-is.text: lowercase it, replace every run of characters other than a-z and 0-9 with one -, and trim - from both ends. If that leaves an empty string, use section.root (on any element, not just headings) or any id generated earlier in this call. If the slug is taken, try slug-2, slug-3, and so on, and use the first free one.id attribute. Do not change the DOM in any other way.root.innerHTML = `
<h1>Getting Started</h1>
<p id="install">Run the installer first.</p>
<h2>Install</h2>
<h4>On macOS</h4>
<h3 id="cfg">Configure</h3>
<h2>FAQ & Help!</h2>
<h2 data-toc-skip>Edit this page</h2>
<h2>Install</h2>
`;
buildOutline(root);
// => [
// { id: 'getting-started', text: 'Getting Started', level: 1, children: [
// { id: 'install-2', text: 'Install', level: 2, children: [
// { id: 'on-macos', text: 'On macOS', level: 4, children: [] },
// { id: 'cfg', text: 'Configure', level: 3, children: [] },
// ] },
// { id: 'faq-help', text: 'FAQ & Help!', level: 2, children: [] },
// { id: 'install-3', text: 'Install', level: 2, children: [] },
// ] },
// ]
root.querySelector('h4').id; // => 'on-macos'
The first “Install” heading gets install-2 because a paragraph already uses install. The <h3> is a child of “Install”, not of “On macOS”, because 3 is not smaller than 4.
[] when there are no counted headings.buildOutline again on the same root returns the same tree, because the generated ids are now real ids.