fix: scroll to anchor when init url with anchor (#599)

This commit is contained in:
Birdgg
2023-06-04 17:56:27 +01:00
committed by GitHub
parent 3c5ddf3213
commit a0b7d76179
2 changed files with 38 additions and 22 deletions
+16 -22
View File
@@ -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 (
<div
+22
View File
@@ -0,0 +1,22 @@
import { useCallback, useEffect, useState } from "react"
export function useHash() {
const [hash, setHash] = useState("")
const onHashChange = useCallback(() => {
setHash(window.location.hash)
}, [])
useEffect(() => {
setHash(window.location.hash)
}, [])
useEffect(() => {
window.addEventListener("hashchange", onHashChange)
return () => {
window.removeEventListener("hashchange", onHashChange)
}
})
return hash
}