File size: 1,476 Bytes
81ed537 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | // "In this article" contents box, built from the post's h2 headings.
(function () {
var toc = document.querySelector(".toc");
var heads = Array.prototype.filter.call(
document.querySelectorAll(".article h2"),
function (h) { return !h.closest(".stat"); }
);
if (!toc || heads.length < 2) { if (toc) toc.remove(); return; }
var used = {};
var items = heads.map(function (h) {
var id = h.id || h.textContent.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "section";
while (used[id]) id += "-2";
used[id] = true;
h.id = id;
return '<li><a href="#' + id + '">' + h.innerHTML.replace(/<[^>]+>/g, "") + "</a></li>";
});
toc.innerHTML =
'<details open><summary>In this article</summary><ol>' + items.join("") + "</ol></details>";
// Collapsed by default on narrow screens, where the box sits above the text.
var details = toc.querySelector("details");
if (window.matchMedia("(max-width: 72rem)").matches) details.removeAttribute("open");
var links = toc.querySelectorAll("a");
if ("IntersectionObserver" in window) {
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) {
if (!e.isIntersecting) return;
links.forEach(function (a) {
a.classList.toggle("on", a.getAttribute("href") === "#" + e.target.id);
});
});
}, { rootMargin: "-80px 0px -70% 0px" });
heads.forEach(function (h) { io.observe(h); });
}
})();
|