fix(toc): enhance hash navigation handling and adjust observer sensitivity (#754)

This commit is contained in:
Xin
2025-08-15 10:33:49 +08:00
committed by GitHub
parent 2033d50005
commit 91cc6b53d8

View File

@@ -20,10 +20,14 @@ document.addEventListener("DOMContentLoaded", function () {
if (headings.length === 0) return;
let currentActiveLink = null;
let isHashNavigation = false;
// Create intersection observer
const observer = new IntersectionObserver(
(entries) => {
// Skip observer updates during hash navigation
if (isHashNavigation) return;
const visibleHeadings = entries.filter((entry) => entry.isIntersecting).map((entry) => entry.target);
if (visibleHeadings.length === 0) return;
@@ -50,7 +54,7 @@ document.addEventListener("DOMContentLoaded", function () {
}
},
{
rootMargin: "-20px 0px -80% 0px", // Adjust sensitivity
rootMargin: "-20px 0px -60% 0px", // Adjust sensitivity
threshold: [0, 0.1, 0.5, 1],
}
);
@@ -58,11 +62,31 @@ document.addEventListener("DOMContentLoaded", function () {
// Observe all headings
headings.forEach((heading) => observer.observe(heading));
// Handle edge case: if no headings are visible on initial load
setTimeout(() => {
if (!currentActiveLink && tocLinks.length > 0) {
tocLinks[0].classList.add("hextra-toc-active");
currentActiveLink = tocLinks[0];
// Handle direct navigation to page with hash
function handleHashNavigation() {
const hash = window.location.hash;
if (hash) {
const targetLink = toc.querySelector(`a[href="${hash}"]`);
if (targetLink) {
// Disable observer temporarily during hash navigation
isHashNavigation = true;
if (currentActiveLink) {
currentActiveLink.classList.remove("hextra-toc-active");
}
}, 100);
targetLink.classList.add("hextra-toc-active");
currentActiveLink = targetLink;
// Re-enable observer after scroll settles
setTimeout(() => { isHashNavigation = false; }, 500);
return;
}
}
}
// Handle hash changes navigation
window.addEventListener("hashchange", handleHashNavigation);
// Handle initial load
setTimeout(handleHashNavigation, 100);
});