Published
Edited
May 24, 2020
Fork of TOC
Importers
1 star
Insert cell
Insert cell
toc({selector: "h2,h3,h4,h5 "})
Insert cell
toc({selector: "#example.just-one > h3, #example.just-one > h4,#example.just-one > h5 ", heading: "Just one section"})
Insert cell
Insert cell
function toc(config) {
const selector = config && config.selector ? config.selector : "h1,h2,h3,h4,h5,h6";
const heading = config && config.heading ? config.heading : "Table of Contents";
return Generators.observe(notify => {
let headings = [];

function observed() {
const minSelector = Math.min(...selector.split(",").map(d => +d.replace(/.*h/, "")));
const h = Array.from(document.querySelectorAll(selector));
if (h.length !== headings.length || h.some((h, i) => headings[i] !== h)) {
notify(html`<b>${heading}</b><ul>${Array.from(headings = h, h => {
console.log(h.tagName, minSelector, h)
const level = parseInt(h.tagName.slice(1));
return Object.assign(
html`${level > minSelector ? '<ul>'.repeat(level - minSelector) + '<li>' : '<li>'}<a href=#${h.id}>${DOM.text(h.textContent)}`,
{onclick: e => (e.preventDefault(), h.scrollIntoView())}
);
})}`);
}
}

const observer = new MutationObserver(observed);
observer.observe(document.body, {childList: true, subtree: true});
observed();
return () => observer.disconnect();
});
}
Insert cell
Insert cell
Insert cell
Insert cell
html`<div id="example" class="just-one"><h4>A separate sub-sub-section?</h4><h5>A separate sub-sub-section?</h5></div>`
Insert cell
html`<div id="example2" class="just-one">${md`
#### A separate sub-sub-section?
##### A separate sub-sub-section!
`}</div>`
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more