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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more