feat(ui): floating back-to-top button on long scrollable pages
A reusable BackToTop fades in once the active page's <main> is scrolled past ~600px and smooth-scrolls it back to the top. Rendered once at the App root, portaled to <body> for viewport-fixed placement (bottom-right, below the chat dock), and re-binds to the live <main> on navigation (page or channel change) so it works on every scrollable page incl. the channel page. EN/HU/DE.
This commit is contained in:
parent
f25d0768a1
commit
6b47b0d357
5 changed files with 53 additions and 3 deletions
44
frontend/src/components/BackToTop.tsx
Normal file
44
frontend/src/components/BackToTop.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
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
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue