45 lines
1.9 KiB
TypeScript
45 lines
1.9 KiB
TypeScript
|
|
import { useEffect, useRef, useState } from "react";
|
||
|
|
import { createPortal } from "react-dom";
|
||
|
|
import { ArrowUp } from "lucide-react";
|
||
|
|
import { useTranslation } from "react-i18next";
|
||
|
|
|
||
|
|
// A floating "back to top" button that fades in once the current page's scroll container is
|
||
|
|
// scrolled past a threshold, and smooth-scrolls it back to the top. Every page scrolls inside its
|
||
|
|
// own <main class="overflow-y-auto"> (the normal pages share App's; the channel page has its own),
|
||
|
|
// so it targets the live <main> and re-binds whenever `dep` changes (i.e. on navigation). Portaled
|
||
|
|
// to <body> so its fixed position is viewport-relative regardless of transformed ancestors.
|
||
|
|
export default function BackToTop({ dep, threshold = 600 }: { dep?: unknown; threshold?: number }) {
|
||
|
|
const { t } = useTranslation();
|
||
|
|
const [show, setShow] = useState(false);
|
||
|
|
const scrollerRef = useRef<HTMLElement | null>(null);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const el = document.querySelector("main");
|
||
|
|
scrollerRef.current = el;
|
||
|
|
if (!el) {
|
||
|
|
setShow(false);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
const onScroll = () => setShow(el.scrollTop > threshold);
|
||
|
|
onScroll(); // a freshly-bound page starts at the top → hidden
|
||
|
|
el.addEventListener("scroll", onScroll, { passive: true });
|
||
|
|
return () => el.removeEventListener("scroll", onScroll);
|
||
|
|
}, [dep, threshold]);
|
||
|
|
|
||
|
|
const toTop = () => scrollerRef.current?.scrollTo({ top: 0, behavior: "smooth" });
|
||
|
|
|
||
|
|
return createPortal(
|
||
|
|
<button
|
||
|
|
onClick={toTop}
|
||
|
|
aria-label={t("common.backToTop")}
|
||
|
|
title={t("common.backToTop")}
|
||
|
|
className={`fixed bottom-5 right-5 z-30 inline-flex items-center justify-center w-11 h-11 rounded-full bg-card border border-border text-fg shadow-lg hover:border-accent hover:text-accent transition-all duration-200 ${
|
||
|
|
show ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3 pointer-events-none"
|
||
|
|
}`}
|
||
|
|
>
|
||
|
|
<ArrowUp className="w-5 h-5" />
|
||
|
|
</button>,
|
||
|
|
document.body
|
||
|
|
);
|
||
|
|
}
|