Skip to content

Commit

Permalink
Merge pull request #94 from JohnsonMao/fix/scroll-position
Browse files Browse the repository at this point in the history
🐛 fix scroll position not reset bug
  • Loading branch information
JohnsonMao authored Sep 28, 2023
2 parents 883027f + 80798a1 commit 7ea3b4c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 20 deletions.
17 changes: 10 additions & 7 deletions src/app/[lang]/posts/[postId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,22 @@ async function PostPage({ params: { postId } }: PostParams) {

return (
<>
<aside className="fixed bottom-0 left-4 top-16 w-40 overflow-auto">
<p className="my-3 text-lg font-semibold text-gray-900 transition-colors dark:text-gray-100">
目錄
</p>
<TableOfContents source={source} />
</aside>
<Container as="main" className="prose prose-xl prose-slate dark:prose-invert">
<Container
as="main"
className="prose prose-xl prose-slate dark:prose-invert"
>
<h1 className="mb-0 mt-4 text-3xl">{frontmatter.title}</h1>
<p className="mt-0">{formattedDate}</p>
<article>{content}</article>
<Link href="/">回首頁</Link>
<Comment />
</Container>
<aside className="fixed bottom-0 left-4 top-16 w-40 overflow-auto">
<p className="my-3 text-lg font-semibold text-gray-900 transition-colors dark:text-gray-100">
目錄
</p>
<TableOfContents source={source} />
</aside>
</>
);
}
Expand Down
16 changes: 3 additions & 13 deletions src/components/TableOfContents/TableOfContents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,15 @@ function TableOfContents({ source }: TableOfContentsProps) {
}, [setElementRef]);

useEffect(() => {
const visibleHeadings = entry.flatMap((headingElement) => {
if (headingElement.isIntersecting) return headingElement;
return [];
});
const visibleHeadings = entry.filter(
({ isIntersecting }) => isIntersecting
);

if (visibleHeadings.length > 0) {
setActiveId(visibleHeadings[0].target.id);
}
}, [entry]);

useEffect(() => {
if (!window.location.hash) {
window.scrollTo({
top: 0,
behavior: 'instant'
})
}
}, []);

return (
<nav aria-label="Table of contents">
<ul>
Expand Down

0 comments on commit 7ea3b4c

Please sign in to comment.