From de2d0f732a5a29f6e4e86f17f9082dfe5b2323d3 Mon Sep 17 00:00:00 2001 From: Joshen Lim Date: Fri, 25 Nov 2022 16:52:13 +0800 Subject: [PATCH] Fix TOC highlight --- apps/docs/hooks/useHash.ts | 29 ++++++++++++++++++++++++++++ apps/docs/layouts/Default.tsx | 2 -- apps/docs/layouts/guides/current.tsx | 13 +++++++++++-- 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 apps/docs/hooks/useHash.ts diff --git a/apps/docs/hooks/useHash.ts b/apps/docs/hooks/useHash.ts new file mode 100644 index 00000000000..92c0cec4fb8 --- /dev/null +++ b/apps/docs/hooks/useHash.ts @@ -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 diff --git a/apps/docs/layouts/Default.tsx b/apps/docs/layouts/Default.tsx index 321d0617a96..186bb39307b 100644 --- a/apps/docs/layouts/Default.tsx +++ b/apps/docs/layouts/Default.tsx @@ -19,8 +19,6 @@ interface Props { const Layout: FC = ({ meta, children, toc }) => { const { asPath } = useRouter() - console.log('asPath', asPath) - useEffect(() => { const key = localStorage.getItem('supabaseDarkMode') if (!key) { diff --git a/apps/docs/layouts/guides/current.tsx b/apps/docs/layouts/guides/current.tsx index 61ae52db8ec..bfd50b6f739 100644 --- a/apps/docs/layouts/guides/current.tsx +++ b/apps/docs/layouts/guides/current.tsx @@ -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) => { + 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) => { } }, []) - 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