Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add sorting to documents

Marc Seitzd393008fdea3
diff --git a/components/documents/filters/sort-button.tsx b/components/documents/filters/sort-button.tsx
new file mode 100644
index 00000000..0ebd1db9
--- /dev/null
+++ b/components/documents/filters/sort-button.tsx
@@ -0,0 +1,129 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import {
+ ArrowDownWideNarrowIcon,
+ CalendarArrowDownIcon,
+ CheckIcon,
+ ClockArrowDownIcon,
+ Eye,
+ XCircleIcon,
+} from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+
+import { cn } from "@/lib/utils";
+
+export default function SortButton() {
+ const router = useRouter();
+ const [sortBy, setSortBy] = useState<string | null>(null);
+
+ useEffect(() => {
+ const { sort } = router.query;
+ if (sort && ["createdAt", "views", "lastViewed"].includes(sort as string)) {
+ setSortBy(sort as string);
+ } else {
+ setSortBy(null);
+ }
+ }, [router.query]);
+
+ useEffect(() => {
+ const currentQuery = { ...router.query };
+
+ if (sortBy === null) {
+ delete currentQuery.sort;
+ } else {
+ currentQuery.sort = sortBy;
+ }
+
+ router.push(
+ {
+ pathname: router.pathname,
+ query: currentQuery,
+ },
+ undefined,
+ { shallow: true },
+ );
+ }, [sortBy]);
+
+ const resetSort = () => setSortBy(null);
+
+ const getSortLabel = () => {
+ switch (sortBy) {
+ case "createdAt":
+ return "Date Added";
+ case "lastViewed":
+ return "Recently Viewed";
+ case "views":
+ return "Number of Views";
+ default:
+ return "";
+ }
+ };
+
+ return (
+ <div className="relative inline-block">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ size={sortBy === null ? "icon" : "default"}
+ variant={"outline"}
+ title="Sort documents"
+ className={cn(
+ "space-x-2",
+ sortBy !== null && "border-2 border-foreground",
+ )}
+ >
+ <ArrowDownWideNarrowIcon className="h-4 w-4" />
+ {sortBy !== null && (
+ <span className="font-medium">{getSortLabel()}</span>
+ )}
+ <span className="sr-only">Sort documents</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-48" align="end">
+ <DropdownMenuLabel>Sort by</DropdownMenuLabel>
+ <DropdownMenuItem
+ onClick={() => setSortBy("createdAt")}
+ disabled={sortBy === "createdAt"}
+ >
+ <CalendarArrowDownIcon className="mr-2 h-4 w-4" />
+ Date Added
+ {sortBy === "createdAt" && (
+ <CheckIcon className="ml-auto h-4 w-4" />
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setSortBy("lastViewed")}>
+ <ClockArrowDownIcon className="mr-2 h-4 w-4" />
+ Recently Viewed
+ {sortBy === "lastViewed" && (
+ <CheckIcon className="ml-auto h-4 w-4" />
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setSortBy("views")}>
+ <Eye className="mr-2 h-4 w-4" />
+ Number of Views
+ {sortBy === "views" && <CheckIcon className="ml-auto h-4 w-4" />}
+ </DropdownMenuItem>
+ {sortBy !== null && (
+ <DropdownMenuItem
+ onClick={resetSort}
+ className="text-destructive focus:bg-destructive/80"
+ >
+ <XCircleIcon className="mr-2 h-4 w-4" />
+ Reset Sort
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+}
diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.ts
index 3e3eaa92..dfd644d4 100644
--- a/lib/swr/use-documents.ts
+++ b/lib/swr/use-documents.ts
@@ -14,6 +14,7 @@ export default function useDocuments() {
const queryParams = router.query;
const searchQuery = queryParams["search"];
+ const sortQuery = queryParams["sort"];
const {
data: documents,
@@ -21,7 +22,7 @@ export default function useDocuments() {
error,
} = useSWR<DocumentWithLinksAndLinkCountAndViewCount[]>(
teamId &&
- `/api/teams/${teamId}/documents${searchQuery ? `/search?query=${searchQuery}` : ""}`,
+ `/api/teams/${teamId}/documents${searchQuery ? `?query=${searchQuery}` : ""}${sortQuery ? (searchQuery ? `&sort=${sortQuery}` : `?sort=${sortQuery}`) : ""}`,
fetcher,
{
revalidateOnFocus: false,
@@ -34,7 +35,7 @@ export default function useDocuments() {
documents,
isValidating,
loading: !documents && !error,
- isSearchResult: !!searchQuery,
+ isFiltered: !!searchQuery || !!sortQuery,
error,
};
}
diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.ts
index 56a5a454..1502c23a 100644
--- a/pages/api/teams/[teamId]/documents/index.ts
+++ b/pages/api/teams/[teamId]/documents/index.ts
@@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { client } from "@/trigger";
-import { DocumentStorageType } from "@prisma/client";
+import { DocumentStorageType, Prisma } from "@prisma/client";
import { getServerSession } from "next-auth/next";
import { parsePageId } from "notion-utils";
@@ -29,35 +29,81 @@ export default async function handle(
}
const { teamId } = req.query as { teamId: string };
-
+ const { query, sort } = req.query as { query?: string; sort?: string };
const userId = (session.user as CustomUser).id;
try {
- const { team } = await getTeamWithUsersAndDocument({
- teamId,
- userId,
- options: {
- where: {
- folderId: null,
- },
- orderBy: {
- createdAt: "desc",
- },
- include: {
- _count: {
- select: { links: true, views: true, versions: true },
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
},
- links: {
- take: 1,
- select: { id: true },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(404).end("Team not found");
+ }
+
+ let orderBy: Prisma.DocumentOrderByWithRelationInput;
+ switch (sort) {
+ case "createdAt":
+ orderBy = { createdAt: "desc" };
+ break;
+ case "views":
+ orderBy = { views: { _count: "desc" } };
+ break;
+ default:
+ orderBy = { createdAt: "desc" };
+ }
+
+ const documents = await prisma.document.findMany({
+ where: {
+ teamId: teamId,
+ ...(query && {
+ name: {
+ contains: query,
+ mode: "insensitive",
},
+ }),
+ ...(!(query || sort) && {
+ folderId: null,
+ }),
+ },
+ orderBy,
+ include: {
+ ...(sort &&
+ sort === "lastViewed" && {
+ views: {
+ select: { viewedAt: true },
+ orderBy: { viewedAt: "desc" },
+ take: 1,
+ },
+ }),
+ _count: {
+ select: { links: true, views: true, versions: true },
},
},
});
- const documents = team.documents;
+ let sortedDocuments = documents;
+
+ if (sort === "lastViewed") {
+ sortedDocuments = documents.sort((a, b) => {
+ const aLastView = a.views[0]?.viewedAt;
+ const bLastView = b.views[0]?.viewedAt;
+
+ if (!aLastView) return 1;
+ if (!bLastView) return -1;
+
+ return bLastView.getTime() - aLastView.getTime();
+ });
+ }
- return res.status(200).json(documents);
+ return res.status(200).json(sortedDocuments);
} catch (error) {
errorhandler(error, res);
}
diff --git a/pages/documents/index.tsx b/pages/documents/index.tsx
index 97b9f9b9..338bec54 100644
--- a/pages/documents/index.tsx
+++ b/pages/documents/index.tsx
@@ -3,6 +3,7 @@ import { FolderPlusIcon, PlusIcon } from "lucide-react";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { DocumentsList } from "@/components/documents/documents-list";
+import SortButton from "@/components/documents/filters/sort-button";
import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
@@ -15,7 +16,7 @@ export default function Documents() {
const teamInfo = useTeam();
const { folders } = useRootFolders();
- const { documents, isValidating, isSearchResult } = useDocuments();
+ const { documents, isValidating, isFiltered } = useDocuments();
return (
<AppLayout>
@@ -54,10 +55,11 @@ export default function Documents() {
</div>
</section>
- <div className="flex justify-end mb-2">
+ <div className="mb-2 flex justify-end gap-x-2">
<div className="relative w-full sm:max-w-xs">
<SearchBoxPersisted loading={isValidating} inputClassName="h-10" />
</div>
+ <SortButton />
</div>
<section id="documents-header-count" />
@@ -66,7 +68,7 @@ export default function Documents() {
<DocumentsList
documents={documents}
- folders={isSearchResult ? [] : folders}
+ folders={isFiltered ? [] : folders}
teamInfo={teamInfo}
/>
</div>