All files / components/custom pagination.tsx

100% Statements 15/15
100% Branches 6/6
100% Functions 4/4
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741x                                       1x 8x 8x 8x   8x   3x                       4x 4x 4x   4x 8x 8x 8x     4x                                                
"use client";
import { FC } from "react";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
 
import { Pagination, PaginationContent, PaginationItem } from "@/components/ui/pagination";
 
import { Button } from "@/components/ui/button";
 
interface PaginationProps {
  pageCount: number;
  className?: string;
}
 
interface PaginationArrowProps {
  direction: "left" | "right";
  href: string;
  isDisabled: boolean;
}
 
const PaginationArrow: FC<PaginationArrowProps> = ({ direction, href, isDisabled }) => {
  const router = useRouter();
  const isLeft = direction === "left";
  const disabledClassName = isDisabled ? "opacity-50 cursor-not-allowed" : "";
 
  return (
    <Button
      onClick={() => router.push(href)}
      className={`hover:bg-primary ${disabledClassName}`}
      aria-disabled={isDisabled}
      disabled={isDisabled}
      variant={"outline"}
    >
      {isLeft ? "«" : "»"}
    </Button>
  );
};
 
export function PaginationComponent({ pageCount, className }: Readonly<PaginationProps>) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const currentPage = Number(searchParams.get("page")) || 1;
 
  const createPageURL = (pageNumber: number | string) => {
    const params = new URLSearchParams(searchParams);
    params.set("page", pageNumber.toString());
    return `${pathname}?${params.toString()}`;
  };
 
  return (
    <Pagination className={cn(className)}>
      <PaginationContent>
        <PaginationItem>
          <PaginationArrow
            direction="left"
            href={createPageURL(currentPage - 1)}
            isDisabled={currentPage <= 1}
          />
        </PaginationItem>
        <PaginationItem>
          <span className="p-2 font-semibold text-primary">Page {currentPage}</span>
        </PaginationItem>
        <PaginationItem>
          <PaginationArrow
            direction="right"
            href={createPageURL(currentPage + 1)}
            isDisabled={currentPage >= pageCount}
          />
        </PaginationItem>
      </PaginationContent>
    </Pagination>
  );
}