From c3c5bd67fea3812b42a91a364ee9e4c9d865d2b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Giani?= <109467012+viniciusgiani@users.noreply.github.com> Date: Tue, 15 Oct 2024 14:28:50 -0300 Subject: [PATCH] Update useTocHighlight.tsx ToC Highlight on Click: A new useEffect is added to listen for clicks on the ToC links. When a link is clicked, the currentIndex is updated to highlight the clicked item. Handling Few Headings: The updateActiveLink function now ensures that when there are very few headers or the user is near the bottom of the page, the last header is correctly highlighted. --- src/components/Layout/useTocHighlight.tsx | 28 ++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/components/Layout/useTocHighlight.tsx b/src/components/Layout/useTocHighlight.tsx index 544396c68b7..677035fa1e9 100644 --- a/src/components/Layout/useTocHighlight.tsx +++ b/src/components/Layout/useTocHighlight.tsx @@ -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; } @@ -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, }; } +