[components/toc][s]: comments added

This commit is contained in:
olayway 2022-05-26 19:41:59 +02:00
parent 73adb71e10
commit 0d5f8f5540
3 changed files with 9 additions and 2 deletions

View File

@ -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");

View File

@ -23,4 +23,6 @@ const MdxContent = ({ body, observer }) => {
return <Component components={ customComponents }/>
};
// 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);

View File

@ -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
}
);
};