Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update useTocHighlight.tsx #7227

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/components/Layout/useTocHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ export function useTocHighlight() {
const scrollPosition = window.scrollY + window.innerHeight;
const headersAnchors = getHeaderAnchors();

if (headersAnchors.length === 0) {
setCurrentIndex(0);
return;
}

if (scrollPosition >= 0 && pageHeight - scrollPosition <= 0) {
// Scrolled to bottom of page.
// Scrolled to the bottom of the page.
setCurrentIndex(headersAnchors.length - 1);
return;
}
Expand Down Expand Up @@ -76,7 +81,28 @@ export function useTocHighlight() {
};
}, []);

// Adding a click listener to update the ToC highlight when an item is clicked
useEffect(() => {
function updateActiveLinkOnClick(event: MouseEvent) {
const target = event.target as HTMLAnchorElement;
const headersAnchors = getHeaderAnchors();

headersAnchors.forEach((anchor, index) => {
if (anchor.href === target.href) {
setCurrentIndex(index);
}
});
}

document.addEventListener('click', updateActiveLinkOnClick);

return () => {
document.removeEventListener('click', updateActiveLinkOnClick);
};
}, []);

return {
currentIndex,
};
}

Loading