Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
add pagination on search and sort documents
Ashish Viradiya26992d8cc1e0
diff --git a/components/documents/documents-pagination.tsx b/components/documents/documents-pagination.tsxnew file mode 100644index 00000000..3f47d787--- /dev/null+++ b/components/documents/documents-pagination.tsx@@ -0,0 +1,103 @@+import {+ ChevronLeftIcon,+ ChevronRightIcon,+ ChevronsLeftIcon,+ ChevronsRightIcon,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++interface DocumentsPaginationProps {+ currentPage: number;+ pageSize: number;+ totalDocuments: number;+ totalPages: number;+ onPageChange: (page: number) => void;+ onPageSizeChange: (size: number) => void;+ totalShownDocuments: number;+}++export function DocumentsPagination({+ currentPage,+ pageSize,+ totalDocuments,+ totalPages,+ onPageChange,+ onPageSizeChange,+ totalShownDocuments,+}: DocumentsPaginationProps) {+ return (+ <div className="mt-4 flex items-center justify-between p-4 rounded-lg bottom-0 left-0 right-0 bg-white w-full border border-gray-200 dark:border-gray-800">+ <div className="flex-1 text-sm text-muted-foreground">+ Showing {totalShownDocuments} of {totalDocuments} documents+ </div>+ <div className="flex items-center space-x-6 lg:space-x-8">+ <div className="hidden items-center space-x-2 sm:flex">+ <p className="text-sm font-medium">Items per page</p>+ <Select+ value={`${pageSize}`}+ onValueChange={(value) => onPageSizeChange(Number(value))}+ >+ <SelectTrigger className="h-8 w-[70px]">+ <SelectValue placeholder={pageSize} />+ </SelectTrigger>+ <SelectContent side="top">+ {[10, 20, 30, 40, 50].map((size) => (+ <SelectItem key={size} value={`${size}`}>+ {size}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex w-[100px] items-center justify-center text-sm font-medium">+ Page {currentPage} of {totalPages || 1}+ </div>+ <div className="flex items-center space-x-2">+ <Button+ variant="outline"+ className="hidden h-8 w-8 p-0 lg:flex"+ onClick={() => onPageChange(1)}+ disabled={currentPage === 1}+ >+ <span className="sr-only">Go to first page</span>+ <ChevronsLeftIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="h-8 w-8 p-0"+ onClick={() => onPageChange(currentPage - 1)}+ disabled={currentPage === 1}+ >+ <span className="sr-only">Go to previous page</span>+ <ChevronLeftIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="h-8 w-8 p-0"+ onClick={() => onPageChange(currentPage + 1)}+ disabled={currentPage === totalPages || totalPages === 0}+ >+ <span className="sr-only">Go to next page</span>+ <ChevronRightIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="hidden h-8 w-8 p-0 lg:flex"+ onClick={() => onPageChange(totalPages)}+ disabled={currentPage === totalPages || totalPages === 0}+ >+ <span className="sr-only">Go to last page</span>+ <ChevronsRightIcon className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ );+}\ No newline at end of filediff --git a/components/documents/filters/sort-button.tsx b/components/documents/filters/sort-button.tsxindex 9050b715..cecfb17b 100644--- a/components/documents/filters/sort-button.tsx+++ b/components/documents/filters/sort-button.tsx@@ -47,6 +47,8 @@ export default function SortButton() {if (sortBy === null) {delete currentQuery.sort;+ delete currentQuery.page;+ delete currentQuery.limit;} else {currentQuery.sort = sortBy;}diff --git a/components/search-box.tsx b/components/search-box.tsxindex 3b9bc208..beafa919 100644--- a/components/search-box.tsx+++ b/components/search-box.tsx@@ -128,6 +128,8 @@ export function SearchBoxPersisted({if (queryParams[urlParam] ?? "" !== debouncedValue)if (debouncedValue === "") {delete queryParams[urlParam];+ delete queryParams["page"];+ delete queryParams["limit"];router.push({pathname: router.pathname,diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.tsindex dfd644d4..8c055ac4 100644--- a/lib/swr/use-documents.ts+++ b/lib/swr/use-documents.ts@@ -15,14 +15,30 @@ export default function useDocuments() {const queryParams = router.query;const searchQuery = queryParams["search"];const sortQuery = queryParams["sort"];+ const page = Number(queryParams["page"]) || 1;+ const pageSize = Number(queryParams["limit"]) || 10;++ const paginationParams = (searchQuery || sortQuery)+ ? `&page=${page}&limit=${pageSize}`+ : '';const {- data: documents,+ data,isValidating,error,- } = useSWR<DocumentWithLinksAndLinkCountAndViewCount[]>(+ } = useSWR<{+ documents: DocumentWithLinksAndLinkCountAndViewCount[];+ pagination?: {+ total: number;+ pages: number;+ currentPage: number;+ pageSize: number;+ };+ }>(teamId &&- `/api/teams/${teamId}/documents${searchQuery ? `?query=${searchQuery}` : ""}${sortQuery ? (searchQuery ? `&sort=${sortQuery}` : `?sort=${sortQuery}`) : ""}`,+ `/api/teams/${teamId}/documents?${+ searchQuery ? `query=${searchQuery}` : ""+ }${sortQuery ? `&sort=${sortQuery}` : ""}${paginationParams}`.replace(/^\?&/, '?'),fetcher,{revalidateOnFocus: false,@@ -32,9 +48,10 @@ export default function useDocuments() {);return {- documents,+ documents: data?.documents || [],+ pagination: data?.pagination,isValidating,- loading: !documents && !error,+ loading: !data && !error,isFiltered: !!searchQuery || !!sortQuery,error,};diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 637ffa19..3823f887 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -35,6 +35,10 @@ export default async function handle(const { query, sort } = req.query as { query?: string; sort?: string };const userId = (session.user as CustomUser).id;+ const usePagination = !!(query || sort);+ const page = usePagination ? (Number(req.query.page) || 1) : undefined;+ const limit = usePagination ? (Number(req.query.limit) || 10) : undefined;+try {const team = await prisma.team.findUnique({where: {@@ -52,23 +56,43 @@ export default async function handle(}let orderBy: Prisma.DocumentOrderByWithRelationInput;- switch (sort) {- case "createdAt":- orderBy = { createdAt: "desc" };- break;- case "views":- orderBy = { views: { _count: "desc" } };- break;- case "name":- orderBy = { name: "asc" };- break;- case "links":- orderBy = { links: { _count: "desc" } };- break;- default:- orderBy = { createdAt: "desc" };++ if (query || sort) {+ switch (sort) {+ case "createdAt":+ orderBy = { createdAt: "desc" };+ break;+ case "views":+ orderBy = { views: { _count: "desc" } };+ break;+ case "name":+ orderBy = { name: "asc" };+ break;+ case "links":+ orderBy = { links: { _count: "desc" } };+ break;+ default:+ orderBy = { createdAt: "desc" };+ }+ } else {+ orderBy = { createdAt: "desc" };}+ const totalDocuments = usePagination ? await prisma.document.count({+ where: {+ teamId: teamId,+ ...(query && {+ name: {+ contains: query,+ mode: "insensitive",+ },+ }),+ ...(!(query || sort) && {+ folderId: null,+ }),+ },+ }) : undefined;+const documents = await prisma.document.findMany({where: {teamId: teamId,@@ -83,15 +107,18 @@ export default async function handle(}),},orderBy,+ ...(usePagination && {+ skip: ((page as number) - 1) * (limit as number),+ take: limit,+ }),include: {- ...(sort &&- sort === "lastViewed" && {- views: {- select: { viewedAt: true },- orderBy: { viewedAt: "desc" },- take: 1,- },- }),+ ...(query && sort === "lastViewed" && {+ views: {+ select: { viewedAt: true },+ orderBy: { viewedAt: "desc" },+ take: 1,+ },+ }),_count: {select: { links: true, views: true, versions: true },},@@ -100,7 +127,7 @@ export default async function handle(let sortedDocuments = documents;- if (sort === "lastViewed") {+ if ((query || sort) && sort === "lastViewed") {sortedDocuments = documents.sort((a, b) => {const aLastView = a.views[0]?.viewedAt;const bLastView = b.views[0]?.viewedAt;@@ -112,13 +139,23 @@ export default async function handle(});}- if (sort === "name") {+ if ((query || sort) && sort === "name") {sortedDocuments = documents.sort((a, b) =>a.name.toLowerCase().localeCompare(b.name.toLowerCase()),);}- return res.status(200).json(sortedDocuments);+ return res.status(200).json({+ documents: sortedDocuments,+ ...(usePagination && {+ pagination: {+ total: totalDocuments,+ pages: Math.ceil(totalDocuments! / limit!),+ currentPage: page,+ pageSize: limit,+ },+ }),+ });} catch (error) {errorhandler(error, res);}diff --git a/pages/documents/index.tsx b/pages/documents/index.tsxindex c3997bf3..d01c68b0 100644--- a/pages/documents/index.tsx+++ b/pages/documents/index.tsx@@ -1,5 +1,13 @@import { useTeam } from "@/context/team-context";import { FolderPlusIcon, PlusIcon } from "lucide-react";+import { useState } from "react";+import {+ ChevronLeftIcon,+ ChevronRightIcon,+ ChevronsLeftIcon,+ ChevronsRightIcon,+} from "lucide-react";+import { useRouter } from "next/router";import { AddDocumentModal } from "@/components/documents/add-document-modal";import { DocumentsList } from "@/components/documents/documents-list";@@ -9,14 +17,40 @@ import AppLayout from "@/components/layouts/app";import { SearchBoxPersisted } from "@/components/search-box";import { Button } from "@/components/ui/button";import { Separator } from "@/components/ui/separator";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import useDocuments, { useRootFolders } from "@/lib/swr/use-documents";+import { DocumentsPagination } from "@/components/documents/documents-pagination";export default function Documents() {+ const router = useRouter();const teamInfo = useTeam();+ const queryParams = router.query;+ const currentPage = Number(queryParams["page"]) || 1;+ const pageSize = Number(queryParams["limit"]) || 10;const { folders } = useRootFolders();- const { documents, isValidating, isFiltered } = useDocuments();+ const { documents, pagination, isValidating, isFiltered } = useDocuments();++ const updatePagination = (newPage?: number, newPageSize?: number) => {+ const params = new URLSearchParams(window.location.search);++ if (newPage) params.set("page", newPage.toString());+ if (newPageSize) {+ params.set("limit", newPageSize.toString());+ params.set("page", "1");+ }++ router.push(`/documents?${params.toString()}`, undefined, { shallow: true });+ };++ const displayFolders = isFiltered ? [] : folders;return (<AppLayout>@@ -68,9 +102,21 @@ export default function Documents() {<DocumentsListdocuments={documents}- folders={isFiltered ? [] : folders}+ folders={displayFolders}teamInfo={teamInfo}/>++ {isFiltered && pagination && (+ <DocumentsPagination+ currentPage={currentPage}+ pageSize={pageSize}+ totalDocuments={pagination.total}+ totalShownDocuments={documents.length}+ totalPages={pagination.pages}+ onPageChange={updatePagination}+ onPageSizeChange={(size) => updatePagination(undefined, size)}+ />+ )}</div></AppLayout>);