From a0b7d761793615565dac8ca0606db37aeb981a32 Mon Sep 17 00:00:00 2001 From: Birdgg Date: Mon, 5 Jun 2023 00:56:27 +0800 Subject: [PATCH] fix: scroll to anchor when init url with anchor (#599) --- src/components/common/PageContent.tsx | 38 +++++++++++---------------- src/hooks/useHash.ts | 22 ++++++++++++++++ 2 files changed, 38 insertions(+), 22 deletions(-) create mode 100644 src/hooks/useHash.ts diff --git a/src/components/common/PageContent.tsx b/src/components/common/PageContent.tsx index 811969b7..7f717b3d 100644 --- a/src/components/common/PageContent.tsx +++ b/src/components/common/PageContent.tsx @@ -5,6 +5,7 @@ import { MutableRefObject, useEffect, useMemo } from "react" import { PostActions } from "~/components/site/PostActions" import { PostToc } from "~/components/site/PostToc" import { useCodeCopy } from "~/hooks/useCodeCopy" +import { useHash } from "~/hooks/useHash" import { ExpandedCharacter, ExpandedNote } from "~/lib/types" import { calculateElementTop, cn } from "~/lib/utils" import { renderPageContent } from "~/markdown" @@ -34,6 +35,7 @@ export const PageContent: React.FC<{ site, withActions, }) => { + const hash = useHash() useCodeCopy() const inParsedContent = useMemo(() => { @@ -48,30 +50,22 @@ export const PageContent: React.FC<{ }, [content, isComment, parsedContent]) useEffect(() => { - const hashChangeHandler = () => { - const hash = decodeURIComponent(location.hash.slice(1)) - if (hash) { - if (history.state?.preventScrollToToc) { - history.state.preventScrollToToc = false - return - } - const targetElement = document.querySelector( - `#user-content-${decodeURIComponent(hash)}`, - ) as HTMLElement - if (!targetElement) return - - window.scrollTo({ - top: calculateElementTop(targetElement) - 20, - behavior: "smooth", - }) - } + const _hash = decodeURIComponent(hash.slice(1)) + if (!_hash) return + if (history.state?.preventScrollToToc) { + history.state.preventScrollToToc = false + return } + const targetElement = document.querySelector( + `#user-content-${decodeURIComponent(_hash)}`, + ) as HTMLElement + if (!targetElement) return - window.addEventListener("hashchange", hashChangeHandler) - return () => { - window.removeEventListener("hashchange", hashChangeHandler) - } - }, []) + window.scrollTo({ + top: calculateElementTop(targetElement) - 20, + behavior: "smooth", + }) + }, [hash]) return (
{ + setHash(window.location.hash) + }, []) + + useEffect(() => { + setHash(window.location.hash) + }, []) + + useEffect(() => { + window.addEventListener("hashchange", onHashChange) + return () => { + window.removeEventListener("hashchange", onHashChange) + } + }) + + return hash +}