Skip to content
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);
}
});
}
Comment on lines +85 to +95

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The updateActiveLinkOnClick function currently assumes that event.target is always an HTMLAnchorElement. To avoid runtime errors, you should first check if event.target is indeed an anchor element before proceeding.

Suggested Fix:

if (target.tagName !== 'A') return;


document.addEventListener('click', updateActiveLinkOnClick);

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

return {
currentIndex,
};
}

Loading