diff --git a/src/components/common/PageContent.tsx b/src/components/common/PageContent.tsx index 6c1fcc05..3aa4853c 100644 --- a/src/components/common/PageContent.tsx +++ b/src/components/common/PageContent.tsx @@ -2,7 +2,8 @@ import { cn } from "~/lib/utils" import { useCodeCopy } from "~/hooks/useCodeCopy" import { renderPageContent } from "~/markdown" import { PostToc } from "~/components/site/PostToc" -import { MutableRefObject, useMemo } from "react" +import { MutableRefObject, useEffect, useMemo } from "react" +import { scroller } from "react-scroll" export const PageContent: React.FC<{ content?: string @@ -34,6 +35,24 @@ export const PageContent: React.FC<{ } }, [content, parsedContent]) + useEffect(() => { + const hashChangeHandler = () => { + const hash = decodeURIComponent(location.hash.slice(1)) + if (hash) { + scroller.scrollTo(`user-content-${decodeURIComponent(hash)}`, { + smooth: true, + offset: -20, + duration: 500, + }) + } + } + + window.addEventListener("hashchange", hashChangeHandler) + return () => { + window.removeEventListener("hashchange", hashChangeHandler) + } + }, []) + return (