Fix TOC highlight

This commit is contained in:
Joshen Lim committed 2022-11-25 16:52:13 +08:00
1 parent 5a917682eb
commit de2d0f732a
3 files changed
+40 -4

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import { useState, useCallback, useEffect } from 'react'
const useHash = () => {
const [hash, setHash] = useState(() =>
typeof window !== 'undefined' ? window.location.hash.split('#')[1] : undefined
)
const hashChangeHandler = useCallback(() => {
setHash(window.location.hash.split('#')[1])
}, [])
useEffect(() => {
window.addEventListener('hashchange', hashChangeHandler)
return () => {
window.removeEventListener('hashchange', hashChangeHandler)
}
}, [])
const updateHash = useCallback(
(newHash) => {
if (newHash !== hash) window.location.hash = newHash
},
[hash]
)
return [hash, updateHash]
}
export default useHash
-2
View File
@@ -19,8 +19,6 @@ interface Props {
const Layout: FC<Props> = ({ meta, children, toc }) => {
const { asPath } = useRouter()
console.log('asPath', asPath)
useEffect(() => {
const key = localStorage.getItem('supabaseDarkMode')
if (!key) {
+11 -2
View File
@@ -3,7 +3,9 @@ import { NextSeo } from 'next-seo'
import { useRouter } from 'next/router'
import { FC, useEffect, useRef, useState } from 'react'
import components from '~/components'
import { highlightSelectedTocItem } from '~/components/CustomHTMLElements/CustomHTMLElements.utils'
import GuidesTableOfContents from '~/components/GuidesTableOfContents'
import useHash from '~/hooks/useHash'
import { getPageType } from '~/lib/helpers'
interface Props {
@@ -14,8 +16,12 @@ interface Props {
}
const Layout: FC<Props> = (props) => {
const [hash] = useHash()
const [active, setActive] = useState(false)
const articleRef = useRef()
const [tocList, setTocList] = useState([])
const { asPath } = useRouter()
const page = getPageType(asPath)
@@ -29,8 +35,11 @@ const Layout: FC<Props> = (props) => {
}
}, [])
const articleRef = useRef()
const [tocList, setTocList] = useState([])
useEffect(() => {
if (hash && tocList.length > 0) {
highlightSelectedTocItem(hash as string)
}
}, [hash, JSON.stringify(tocList)])
useEffect(() => {
const articleEl = articleRef.current as HTMLElement