Published
Edited
Jun 15, 2021
Fork of TOC
1 fork
Importers
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
function toc(selector = "h1,h2,h3", heading = "<b>Table of Contents</b>") {
return Generators.observe(notify => {
let headings = [];

function observed() {
const h = Array.from(document.querySelectorAll(selector));
if (h.length !== headings.length || h.some((h, i) => headings[i] !== h)) {
notify(html`<details><summary>${heading}</summary><ul>${Array.from(headings = h, h => {
// this level is taken from https://observablehq.com/@matthewkenny/toc
const level = parseInt(h.tagName.slice(1)) - 1;
return Object.assign(
html`${level > 1 ? '<ul>'.repeat(level-1) + '<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
### Test Level 2
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