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; if (headings.length === 0) return;
let currentActiveLink = null; let currentActiveLink = null;
let isHashNavigation = false;
// Create intersection observer // Create intersection observer
const observer = new IntersectionObserver( const observer = new IntersectionObserver(
(entries) => { (entries) => {
// Skip observer updates during hash navigation
if (isHashNavigation) return;
const visibleHeadings = entries.filter((entry) => entry.isIntersecting).map((entry) => entry.target); const visibleHeadings = entries.filter((entry) => entry.isIntersecting).map((entry) => entry.target);
if (visibleHeadings.length === 0) return; 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], threshold: [0, 0.1, 0.5, 1],
} }
); );
@@ -58,11 +62,31 @@ document.addEventListener("DOMContentLoaded", function () {
// Observe all headings // Observe all headings
headings.forEach((heading) => observer.observe(heading)); headings.forEach((heading) => observer.observe(heading));
// Handle edge case: if no headings are visible on initial load // Handle direct navigation to page with hash
setTimeout(() => { function handleHashNavigation() {
if (!currentActiveLink && tocLinks.length > 0) { const hash = window.location.hash;
tocLinks[0].classList.add("hextra-toc-active"); if (hash) {
currentActiveLink = tocLinks[0]; 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");
}
targetLink.classList.add("hextra-toc-active");
currentActiveLink = targetLink;
// Re-enable observer after scroll settles
setTimeout(() => { isHashNavigation = false; }, 500);
return;
}
} }
}, 100); }
// Handle hash changes navigation
window.addEventListener("hashchange", handleHashNavigation);
// Handle initial load
setTimeout(handleHashNavigation, 100);
}); });