Skip to content

Commit

Permalink
feat(ui): add "go to top" button on post pages
Browse files Browse the repository at this point in the history
resolve #29
  • Loading branch information
mateusfg7 committed May 19, 2023
1 parent b121a1b commit 9ce884b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/app/(blog)/post/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { FiTag } from 'react-icons/fi'
import { allPosts, type Post } from 'contentlayer/generated'

import { Date } from 'components/Date'
import { TopButton } from 'components/TopButton'
import { authors } from 'lib/authors'
import { slug } from 'lib/utils'

Expand Down Expand Up @@ -84,6 +85,7 @@ export default function Page({ params }: Props) {
<div className="post-content">
<MDXContent />
</div>
<TopButton />
</div>
)
}
Expand Down
51 changes: 51 additions & 0 deletions src/components/TopButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use client'

import { CaretUp } from "@phosphor-icons/react"
import { useEffect, useState } from "react"

export function TopButton() {
const [percentScrollPosition, setPercentScrollPosition] = useState(0)
const [scrollPosition, setScrollPosition] = useState(0)
const [maxScrollValue, setMaxScrollValue] = useState(0)

function handleScroll() {
if (window) {
setScrollPosition(window.scrollY)
}
if (document) {
setMaxScrollValue(
document.documentElement.scrollHeight -
document.documentElement.clientHeight
)
}
}

useEffect(() => {
handleScroll()

if (window) {
window.addEventListener('scroll', handleScroll, { passive: true })
}
}, [])

useEffect(() => {
setPercentScrollPosition(
Math.round((scrollPosition / maxScrollValue) * 100)
)
}, [scrollPosition, maxScrollValue])

const isNotOnTop = percentScrollPosition > 0

const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};

return (
<button onClick={scrollToTop} title="Go to top" className={`fixed right-7 bottom-7 rounded-full hidden md:flex items-center justify-center p-2 hover:bg-neutral-200 hover:dark:bg-neutral-900 ${isNotOnTop ? 'opacity-100' : 'opacity-0'}`}>
<CaretUp className="text-2xl" />
</button>
)
}

0 comments on commit 9ce884b

Please sign in to comment.