From 0d5f8f55408082d8105be0500738bd682dac672b Mon Sep 17 00:00:00 2001 From: olayway Date: Thu, 26 May 2022 19:41:59 +0200 Subject: [PATCH] [components/toc][s]: comments added --- site/components/MDX.js | 5 +++++ site/components/MdxContent.js | 2 ++ site/components/_getIntersectionObserver.js | 4 ++-- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/site/components/MDX.js b/site/components/MDX.js index 2c02a15..90e1549 100644 --- a/site/components/MDX.js +++ b/site/components/MDX.js @@ -22,6 +22,7 @@ export default function MdxPage({ body, frontMatter, editUrl }) { const [observer, setObserver] = useState(null); // run only after first render, in order to preserve the observer + // between component rerenders useEffect((() => { const observer = getObserver((entry) => { if (entry.isIntersecting) { @@ -34,6 +35,9 @@ export default function MdxPage({ body, frontMatter, editUrl }) { }), []) useEffect(() => { + // on initial render activeHeading will be `null` + // however, we still want to highlight the current heading in the toc + // based on the current url if (!activeHeading) { try { const path = window.location.hash; @@ -48,6 +52,7 @@ export default function MdxPage({ body, frontMatter, editUrl }) { return } } + const tocLink = document.querySelector(`.toc-link[href="#${activeHeading}"]`) tocLink.classList.add("active"); diff --git a/site/components/MdxContent.js b/site/components/MdxContent.js index b59e64e..35c51cf 100644 --- a/site/components/MdxContent.js +++ b/site/components/MdxContent.js @@ -23,4 +23,6 @@ const MdxContent = ({ body, observer }) => { return }; +// prevent rerendering of the component if it's props don't change +// i.e. re-render only when the observer is set export default React.memo(MdxContent); diff --git a/site/components/_getIntersectionObserver.js b/site/components/_getIntersectionObserver.js index 2be2208..b69fce2 100644 --- a/site/components/_getIntersectionObserver.js +++ b/site/components/_getIntersectionObserver.js @@ -1,3 +1,4 @@ +// an Intersection Observer to keep track of currently viewed headings const getIntersectionObserver = (callback) => { return new IntersectionObserver( (entries) => { @@ -7,8 +8,7 @@ const getIntersectionObserver = (callback) => { }, { root: null, - // 65px is a navbar height - rootMargin: `-65px 0% -90% 0%` + rootMargin: "-65px 0% -90% 0%" // 65px is a navbar height } ); };