Skip to content

Instantly share code, notes, and snippets.

@Atulin
Last active June 14, 2022 18:53
Show Gist options
  • Save Atulin/2a6d4db6f3e9c7cea303fdde8db515e8 to your computer and use it in GitHub Desktop.
Save Atulin/2a6d4db6f3e9c7cea303fdde8db515e8 to your computer and use it in GitHub Desktop.
Microsoft Devblog TOC

Microsoft Devblog TOC

Microsoft devblogs don't have ToC for some reason. So here's a fix.

// ==UserScript==
// @name MS Devblog TOC
// @version 1
// @grant none
// @source https://gist.github.com/Atulin/b6a5975ac4f260d16496a2b519f6a698
// @match https://devblogs.microsoft.com/*
// ==/UserScript==
(() => {
const nodes = document.querySelector("article > #featured > div").children;
console.log(`Found ${nodes.length} nodes`);
const toc = [...nodes]
.filter((n) => n.nodeName.startsWith("H"))
.map((n) => ({ class: n.nodeName, text: n.innerText }));
console.log(toc);
const style = document.createElement("style");
style.innerText = /* css */ `
.__GENERATED_TOC {
position: fixed;
top: 1rem;
right: 2rem;
display: flex;
flex-direction: column;
background-color: white;
padding: .5rem;
font-size: .8rem;
z-index: 999;
box-shadow: 2px 2px 8px rgba(0,0,0,.1);
transition: all 200ms ease-in-out;
}
.__GENERATED_TOC.hidden {
right: -100%
}
.__TOC_BUTTON {
position: fixed;
top: 1rem;
right: 0;
writing-mode: vertical-rl;
background-color: white;
padding: .5rem;
font-size: .8rem;
z-index: 999;
box-shadow: 2px 2px 8px rgba(0,0,0,.1);
border: none;
cursor: pointer;
}
`;
for (let i = 0; i <= 10; i++) {
style.innerText += /* css */ `
.__GENERATED_TOC > .toc-h${i + 1} {
padding: .25rem;
padding-left: ${i * (i + 1) * 0.25 + 0.25}rem;
color: #5290c2;
}
.__GENERATED_TOC > .toc-h${i}:hover {
background-color: #5290c2;
color: white;
}
`;
}
document.head.appendChild(style);
const list = document.createElement("nav");
list.classList.add("__GENERATED_TOC");
for (const t of toc) {
/** @type {HtmlAnchorElement} */
const a = document.createElement("a");
a.classList.add(`toc-${t.class.toLowerCase()}`);
a.innerText = t.text;
a.href = `#${t.text.toLowerCase().replace(" ", "-")}`;
list.appendChild(a);
}
const hidebtn = document.createElement("button");
hidebtn.innerText = "toggle TOC";
hidebtn.classList.add("__TOC_BUTTON");
hidebtn.addEventListener("click", () => list.classList.toggle("hidden"));
document.body.appendChild(list);
document.body.appendChild(hidebtn);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment