Files
aragrp/components/scroll-to-top.tsx
T
2026-02-05 14:54:19 +03:30

55 lines
1.3 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { ChevronUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
const SCROLL_THRESHOLD = 0.4; // show after 40% scroll
export function ScrollToTop({ className }: { className?: string }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
function onScroll() {
const maxScroll =
document.documentElement.scrollHeight - window.innerHeight;
if (maxScroll <= 0) {
setVisible(false);
return;
}
const ratio = window.scrollY / maxScroll;
setVisible(ratio >= SCROLL_THRESHOLD);
}
onScroll();
window.addEventListener("scroll", onScroll, { passive: true });
return () => window.removeEventListener("scroll", onScroll);
}, []);
const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
};
if (!visible) return null;
return (
<div
className={cn(
"fixed bottom-6 start-6 z-50 transition-opacity duration-300",
className
)}
>
<Button
size="icon"
variant="outline"
onClick={scrollToTop}
aria-label="برگشت به بالا"
className="size-10 rounded-md shadow-md"
>
<ChevronUp className="size-5" />
</Button>
</div>
);
}