Published
Edited
Sep 29, 2020
Fork of TOC
Importers
5 stars
Insert cell
Insert cell
Insert cell
toc('sample table of contents', 'h1,h2,h3,h4,h5,h6')
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
htags = document.querySelectorAll('h1,h2,h3')
Insert cell
htext = Array.from(htags).map(h => h.tagName +': ' +h.textContent)
Insert cell
hlevels = Array.from(htags).map(h => parseInt(h.tagName[1], 10))
Insert cell
Insert cell
toc = (title='Table of Contents', selector='h1,h2,h3') => {
return Generators.observe(notify => {
let old = [];
const level = (h) => parseInt(h.tagName[1], 10);
const observed = () => {
const now = Array.from(document.querySelectorAll(selector));
if ( !(now.length !== old.length || now.some((h, i) => h !== old[i])) ) return;
const header = (title && title.length > 0) ? `<b>${title}</b>` : '';
const list = (old = now).map(h => Object.assign(
html`${'<ul>'.repeat(level(h)-1)}<li><a href=#${h.id}>${DOM.text(h.textContent)}`,
{onclick: e => (e.preventDefault(), h.scrollIntoView())}
));
notify(html`${header}<ul>${list}`);
};

observed();
const observer = new MutationObserver(observed);
observer.observe(document.body, {childList: true, subtree: true});
return () => observer.disconnect();
});
}
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