feat: improve heading markup and scroll behavior

Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
This commit is contained in:
David Karlsson 2023-11-10 16:39:08 +01:00
parent dadaefce3f
commit db85f53af1
2 changed files with 27 additions and 42 deletions

View File

@ -1,43 +1,29 @@
const toc = document.querySelector("#TableOfContents") const toc = document.querySelector("#TableOfContents");
const headings = document.querySelectorAll("main article h2, main article h3");
if (toc) { if (toc) {
const prose = document.querySelector("article.prose") window.addEventListener("scroll", updateToc);
const headings = prose.querySelectorAll("h2, h3") updateToc();
// grab the yposition and targets for all anchor links }
const anchorLinks = Array.from(headings)
.map((h) => h.previousElementSibling) function updateToc() {
.map((a) => [a.offsetTop - 64, `#${a.name}`]) // find the heading currently in view
.sort((a, b) => (a[0] > b[0] ? 1 : 0)) const currentSection = Array.from(headings).reduce((previous, current) => {
const { top } = current.getBoundingClientRect();
let closestHeading // if current is in the top 100px of the viewport
// 100px is an arbitrary value
// find the closest anchor link based on window scrollpos // Should be header height + margin
function findClosestHeading() { if (top < 100) {
yPos = window.scrollY return current;
closest = anchorLinks.reduce((prev, curr) => { }
return Math.abs(curr[0] - yPos) < Math.abs(prev[0] - yPos) && return previous
curr[0] <= yPos });
? curr const prev = toc.querySelector('a[aria-current="true"]');
: prev const next = toc.querySelector(`a[href="#${currentSection.id}"]`);
}) if (prev) {
return closest prev.removeAttribute("aria-current");
} }
if (next) {
function updateToc() { next.setAttribute("aria-current", "true");
const prev = toc.querySelector('a[aria-current="true"]') }
const next = toc.querySelector(`a[href="${closestHeading[1]}"]`)
if (prev) {
prev.removeAttribute("aria-current")
}
if (next) {
next.setAttribute("aria-current", "true")
}
}
function handleScroll() {
closestHeading = findClosestHeading()
updateToc()
}
window.addEventListener("scroll", handleScroll)
} }

View File

@ -1,6 +1,5 @@
{{ $id := .id | default (anchorize (plainify .text)) }} {{ $id := .id | default (anchorize (plainify .text)) }}
<a class="relative -top-16" name="{{ $id }}"></a> <h{{ .level }} class="{{ .class }} scroll-mt-20" id="{{ $id }}">
<h{{ .level }} {{ with .class }} class="{{ . }}" {{ end }}>
<a class="text-black dark:text-white no-underline hover:underline" href="#{{ $id }}"> <a class="text-black dark:text-white no-underline hover:underline" href="#{{ $id }}">
{{ .text }} {{ .text }}
</a> </a>