Scroll to top on page change (#161)

This commit is contained in:
Matt Rubens 2025-06-30 15:47:30 -04:00 committed by GitHub
parent 362d9b2b2c
commit 314a64b3ce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 34 additions and 6 deletions

View file

@ -1,4 +1,4 @@
import { useMemo, useEffect } from 'react';
import { useMemo, useEffect, useRef } from 'react';
import { useAuth } from '@clerk/nextjs';
import { useQuery } from '@tanstack/react-query';
@ -27,6 +27,7 @@ export const Tasks = ({
}) => {
const { orgId } = useAuth();
const polling = useRealtimePolling({ enabled: true, interval: 5000 });
const tasksListRef = useRef<HTMLDivElement>(null);
// Initialize cursor-based pagination
const pagination = useCursorPagination(100);
@ -102,7 +103,7 @@ export const Tasks = ({
return (
<div className="space-y-4">
<div className="space-y-3 sm:space-y-4">
<div ref={tasksListRef} className="space-y-3 sm:space-y-4">
{tasks.map((task) => (
<TaskCard
key={task.taskId}
@ -115,7 +116,10 @@ export const Tasks = ({
{/* Cursor Pagination Controls */}
<div className="flex justify-center mt-6">
<CursorPaginationControls pagination={pagination} />
<CursorPaginationControls
pagination={pagination}
scrollTargetRef={tasksListRef}
/>
</div>
</div>
);

View file

@ -6,11 +6,12 @@ interface CursorPaginationControlsProps {
pagination: CursorPaginationHook;
className?: string;
showPageInfo?: boolean;
scrollTargetRef?: React.RefObject<HTMLElement | null>;
}
export const CursorPaginationControls: React.FC<
CursorPaginationControlsProps
> = ({ pagination, className = '', showPageInfo = true }) => {
> = ({ pagination, className = '', showPageInfo = true, scrollTargetRef }) => {
const {
hasNextPage,
hasPreviousPage,
@ -19,6 +20,29 @@ export const CursorPaginationControls: React.FC<
currentPageIndex,
} = pagination;
const scrollToTarget = () => {
setTimeout(() => {
if (scrollTargetRef?.current) {
const rect = scrollTargetRef.current.getBoundingClientRect();
const scrollTop = window.pageYOffset + rect.top - 20;
window.scrollTo({
top: scrollTop,
behavior: 'smooth',
});
}
}, 100);
};
const handleNextPage = () => {
nextPage();
scrollToTarget();
};
const handlePreviousPage = () => {
previousPage();
scrollToTarget();
};
// Don't show pagination if we're on the first page and there's no next page
if (currentPageIndex === 0 && !hasNextPage) {
return null;
@ -29,7 +53,7 @@ export const CursorPaginationControls: React.FC<
<Button
variant="outline"
size="sm"
onClick={previousPage}
onClick={handlePreviousPage}
disabled={!hasPreviousPage}
className="px-3 py-2"
>
@ -45,7 +69,7 @@ export const CursorPaginationControls: React.FC<
<Button
variant="outline"
size="sm"
onClick={nextPage}
onClick={handleNextPage}
disabled={!hasNextPage}
className="px-3 py-2"
>