tailwind-nextjs-blog/components/ScrollTopAndComment.tsx

61 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-08-16 23:55:57 +08:00
'use client';
2023-08-16 23:55:57 +08:00
import siteMetadata from '@/data/siteMetadata';
import { useEffect, useState } from 'react';
2022-07-17 21:40:41 +08:00
const ScrollTopAndComment = () => {
2023-08-16 23:55:57 +08:00
const [show, setShow] = useState(false);
2022-07-17 21:40:41 +08:00
useEffect(() => {
const handleWindowScroll = () => {
2023-08-16 23:55:57 +08:00
if (window.scrollY > 50) setShow(true);
else setShow(false);
};
2022-07-17 21:40:41 +08:00
2023-08-16 23:55:57 +08:00
window.addEventListener('scroll', handleWindowScroll);
return () => window.removeEventListener('scroll', handleWindowScroll);
}, []);
2022-07-17 21:40:41 +08:00
const handleScrollTop = () => {
2023-08-16 23:55:57 +08:00
window.scrollTo({ top: 0 });
};
2022-07-17 21:40:41 +08:00
const handleScrollToComment = () => {
2023-08-16 23:55:57 +08:00
document.getElementById('comment')?.scrollIntoView();
};
2022-07-17 21:40:41 +08:00
return (
<div
2023-08-16 23:55:57 +08:00
className={`fixed bottom-8 right-8 hidden flex-col gap-3 ${
show ? 'md:flex' : 'md:hidden'
}`}>
{siteMetadata.comments?.provider && (
<button
aria-label="Scroll To Comment"
onClick={handleScrollToComment}
2023-08-16 23:55:57 +08:00
className="rounded-full bg-gray-200 p-2 text-gray-500 transition-all hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600">
<svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z"
clipRule="evenodd"
/>
</svg>
</button>
)}
2022-07-17 21:40:41 +08:00
<button
aria-label="Scroll To Top"
onClick={handleScrollTop}
2023-08-16 23:55:57 +08:00
className="rounded-full bg-gray-200 p-2 text-gray-500 transition-all hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600">
2022-07-17 21:40:41 +08:00
<svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
2023-08-16 23:55:57 +08:00
);
};
2022-07-17 21:40:41 +08:00
2023-08-16 23:55:57 +08:00
export default ScrollTopAndComment;