121 lines
3.0 KiB
TypeScript

"use client";
import { usePathname } from "next/navigation";
interface PaginationProps {
page: number;
hasPreviousPage: boolean;
hasNextPage: boolean;
totalPages: number;
usePathParams?: boolean;
}
export default function Pagination({
page,
hasPreviousPage,
hasNextPage,
totalPages,
usePathParams = false,
}: PaginationProps) {
const activePage = page;
const pathName = usePathname();
// Function to handle page change
const handlePageChange = (page: string | number) => {
if (typeof page === "string") return;
if (typeof window === "undefined") return;
const url = new URL(window.location.href);
const searchParams = new URLSearchParams(url.search);
if (usePathParams) {
let updatedPath = "";
if (pathName.includes("/page")) {
updatedPath = pathName.replace(/\/page\/\d+/, `/page/${page}`);
} else {
updatedPath = `${pathName}/page/${page}`;
}
window.location.href = `${updatedPath}?${searchParams}`;
} else {
searchParams.set("page", `${page}`);
window.location.href = `${pathName}/?${searchParams}`;
}
};
const getPageNumbers = () => {
const pages = [];
const showEllipsisStart = activePage > 4;
const showEllipsisEnd = activePage < totalPages - 3;
if (totalPages <= 7) {
// Show all pages if total is 7 or less
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
// Always show first page
pages.push(1);
if (showEllipsisStart) {
pages.push("...");
}
// Show pages around current page
const start = showEllipsisStart ? Math.max(2, activePage - 1) : 2;
const end = showEllipsisEnd ? Math.min(totalPages - 1, activePage + 1) : totalPages - 1;
for (let i = start; i <= end; i++) {
pages.push(i);
}
if (showEllipsisEnd) {
pages.push("...");
}
// Always show last page
pages.push(totalPages);
}
return pages;
};
return (
<ul className={"pagination-custom"}>
{/* Previous Page Button */}
{hasPreviousPage && (
<>
<li className="cursor-pointer">
<a
onClick={() => activePage > 1 && handlePageChange(activePage - 1)}
className={activePage === 1 ? "disabled" : ""}
>
{"<"}
</a>
</li>
</>
)}
{getPageNumbers().map((page, key) => (
<li key={key} className="cursor-pointer">
<a onClick={() => handlePageChange(page)} className={activePage === page ? "active" : ""}>
{page}
</a>
</li>
))}
{/* Next Page Button */}
{hasNextPage && (
<>
<li className="cursor-pointer">
<a
onClick={() => activePage < totalPages && handlePageChange(activePage + 1)}
className={activePage === totalPages ? "disabled" : ""}
>
{">"}
</a>
</li>
</>
)}
</ul>
);
}