Skip to content

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

feat: add admin dataroom search

Marc Seitzc800bdc9e49c
diff --git a/components/datarooms/dataroom-search-results.tsx b/components/datarooms/dataroom-search-results.tsx
new file mode 100644
index 00000000..87320996
--- /dev/null
+++ b/components/datarooms/dataroom-search-results.tsx
@@ -0,0 +1,160 @@
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { TeamContextType } from "@/context/team-context";
+import { ChevronRight, FileIcon, FolderIcon } from "lucide-react";
+
+import {
+ DataroomFolderDocumentWithPath,
+ DataroomFolderWithCountAndPath,
+} from "@/lib/swr/use-dataroom";
+import { safeSlugify } from "@/lib/utils";
+
+import DataroomDocumentCard from "@/components/datarooms/dataroom-document-card";
+import FolderCard from "@/components/documents/folder-card";
+
+function FolderPathBreadcrumb({
+ folderPath,
+ dataroomId,
+}: {
+ folderPath: string[];
+ dataroomId: string;
+}) {
+ const router = useRouter();
+ const { id } = router.query as { id: string };
+
+ const buildLink = (index: number) => {
+ if (index < 0) return `/datarooms/${id}/documents`;
+ const slugs = folderPath.slice(0, index + 1).map(safeSlugify);
+ return `/datarooms/${id}/documents/${slugs.join("/")}`;
+ };
+
+ return (
+ <div className="mt-1 flex flex-wrap items-center gap-x-1 text-xs leading-5 text-muted-foreground">
+ <p className="flex items-center gap-x-1">
+ <FolderIcon className="h-3 w-3" />
+ <Link
+ href={`/datarooms/${id}/documents`}
+ onClick={(e) => e.stopPropagation()}
+ className="relative z-10 hover:underline"
+ >
+ Root
+ </Link>
+ </p>
+ {folderPath.map((name, index) => (
+ <p key={index} className="flex items-center gap-x-1">
+ <ChevronRight className="h-3 w-3" />
+ <FolderIcon className="h-3 w-3" />
+ <Link
+ href={buildLink(index)}
+ onClick={(e) => e.stopPropagation()}
+ className="relative z-10 hover:underline"
+ >
+ {name}
+ </Link>
+ </p>
+ ))}
+ </div>
+ );
+}
+
+export function DataroomSearchResults({
+ documents,
+ folders,
+ teamInfo,
+ dataroomId,
+ searchQuery,
+}: {
+ documents: DataroomFolderDocumentWithPath[];
+ folders: DataroomFolderWithCountAndPath[];
+ teamInfo: TeamContextType | null;
+ dataroomId: string;
+ searchQuery: string;
+}) {
+ const totalResults = documents.length + folders.length;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-x-2 text-sm text-muted-foreground">
+ <span>
+ Search results for &quot;{searchQuery}&quot;
+ </span>
+ <span className="text-xs">
+ ({totalResults} result{totalResults !== 1 ? "s" : ""})
+ </span>
+ </div>
+
+ {totalResults === 0 ? (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
+ <p className="text-sm text-muted-foreground">
+ No documents or folders found matching &quot;{searchQuery}&quot;
+ </p>
+ </div>
+ ) : (
+ <ul role="list" className="space-y-4">
+ {folders.length > 0 && (
+ <>
+ <li className="flex items-center gap-x-1 text-sm text-muted-foreground">
+ <FolderIcon className="h-4 w-4" />
+ <span>
+ {folders.length} folder{folders.length !== 1 ? "s" : ""}
+ </span>
+ </li>
+ {folders.map((folder) => (
+ <li key={`folder-${folder.id}`}>
+ <div>
+ <FolderCard
+ folder={folder}
+ teamInfo={teamInfo}
+ isDataroom={true}
+ dataroomId={dataroomId}
+ />
+ {folder.folderPath.length > 0 && (
+ <div className="ml-4 mt-1">
+ <FolderPathBreadcrumb
+ folderPath={folder.folderPath}
+ dataroomId={dataroomId}
+ />
+ </div>
+ )}
+ </div>
+ </li>
+ ))}
+ </>
+ )}
+
+ {documents.length > 0 && (
+ <>
+ <li className="flex items-center gap-x-1 text-sm text-muted-foreground">
+ <FileIcon className="h-4 w-4" />
+ <span>
+ {documents.length} document
+ {documents.length !== 1 ? "s" : ""}
+ </span>
+ </li>
+ {documents.map((doc) => (
+ <li key={`document-${doc.id}`}>
+ <div>
+ <DataroomDocumentCard
+ document={doc}
+ teamInfo={teamInfo}
+ dataroomId={dataroomId}
+ />
+ {doc.folderPath.length > 0 && (
+ <div className="ml-4 mt-1">
+ <FolderPathBreadcrumb
+ folderPath={doc.folderPath}
+ dataroomId={dataroomId}
+ />
+ </div>
+ )}
+ </div>
+ </li>
+ ))}
+ </>
+ )}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/lib/swr/use-dataroom.ts b/lib/swr/use-dataroom.ts
index 728b9ce5..429a6982 100644
--- a/lib/swr/use-dataroom.ts
+++ b/lib/swr/use-dataroom.ts
@@ -447,3 +447,43 @@ export function useDataroomVisitHistory({
error,
};
}
+
+export type DataroomFolderWithCountAndPath = DataroomFolderWithCount & {
+ folderPath: string[];
+};
+
+export type DataroomFolderDocumentWithPath = DataroomFolderDocument & {
+ folderPath: string[];
+};
+
+export function useDataroomSearch({ query }: { query: string }) {
+ const router = useRouter();
+ const { id } = router.query as { id: string };
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data, error } = useSWR<{
+ documents: DataroomFolderDocumentWithPath[];
+ folders: DataroomFolderWithCountAndPath[];
+ }>(
+ teamId &&
+ id &&
+ query &&
+ query.trim().length > 0 &&
+ `/api/teams/${teamId}/datarooms/${id}/search?query=${encodeURIComponent(query.trim())}`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 10000,
+ },
+ );
+
+ const isLoading = query.trim().length > 0 && !data && !error;
+
+ return {
+ documents: data?.documents || [],
+ folders: data?.folders || [],
+ isLoading,
+ error,
+ };
+}
diff --git a/next.config.mjs b/next.config.mjs
index c3250e71..5e95f32c 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -26,12 +26,6 @@ const nextConfig = {
},
],
},
- {
- // temporary redirect set on 2025-10-22
- source: "/view/cmdn06aw00001ju04jgsf8h4f",
- destination: "/view/cmh0uiv6t001mjm04sk10ecc8",
- permanent: false,
- },
{
source: "/settings",
destination: "/settings/general",
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/search.ts b/pages/api/teams/[teamId]/datarooms/[id]/search.ts
new file mode 100644
index 00000000..5719789e
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/search.ts
@@ -0,0 +1,193 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const {
+ teamId,
+ id: dataroomId,
+ query,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ query?: string;
+ };
+
+ if (!query || query.trim().length === 0) {
+ return res.status(200).json({ documents: [], folders: [] });
+ }
+
+ try {
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const dataroom = await prisma.dataroom.findUnique({
+ where: {
+ id: dataroomId,
+ teamId,
+ },
+ select: { id: true },
+ });
+
+ if (!dataroom) {
+ return res.status(404).json({
+ error: "Not Found",
+ message: "The requested dataroom does not exist",
+ });
+ }
+
+ const [documents, folders] = await Promise.all([
+ prisma.dataroomDocument.findMany({
+ where: {
+ dataroomId,
+ document: {
+ name: {
+ contains: query.trim(),
+ mode: "insensitive",
+ },
+ },
+ },
+ orderBy: [
+ { orderIndex: "asc" },
+ { document: { name: "asc" } },
+ ],
+ select: {
+ id: true,
+ dataroomId: true,
+ folderId: true,
+ orderIndex: true,
+ hierarchicalIndex: true,
+ createdAt: true,
+ updatedAt: true,
+ document: {
+ select: {
+ id: true,
+ name: true,
+ type: true,
+ advancedExcelEnabled: true,
+ versions: {
+ select: { id: true, hasPages: true },
+ },
+ isExternalUpload: true,
+ _count: {
+ select: {
+ views: { where: { dataroomId } },
+ versions: true,
+ },
+ },
+ },
+ },
+ },
+ }),
+
+ prisma.dataroomFolder.findMany({
+ where: {
+ dataroomId,
+ name: {
+ contains: query.trim(),
+ mode: "insensitive",
+ },
+ },
+ orderBy: [{ orderIndex: "asc" }, { name: "asc" }],
+ select: {
+ id: true,
+ name: true,
+ path: true,
+ parentId: true,
+ dataroomId: true,
+ orderIndex: true,
+ hierarchicalIndex: true,
+ icon: true,
+ color: true,
+ createdAt: true,
+ updatedAt: true,
+ _count: {
+ select: { documents: true, childFolders: true },
+ },
+ },
+ }),
+ ]);
+
+ // Build breadcrumb paths for documents that are in folders
+ // and for folders that have a parent
+ const folderIds = new Set<string>();
+ for (const d of documents) {
+ if (d.folderId) folderIds.add(d.folderId);
+ }
+ for (const f of folders) {
+ if (f.parentId) folderIds.add(f.parentId);
+ }
+
+ const allFoldersInDataroom =
+ folderIds.size > 0
+ ? await prisma.dataroomFolder.findMany({
+ where: { dataroomId },
+ select: { id: true, name: true, path: true, parentId: true },
+ })
+ : [];
+
+ const folderMap = new Map(
+ allFoldersInDataroom.map((f) => [f.id, f]),
+ );
+
+ const buildBreadcrumb = (folderId: string): string[] => {
+ const names: string[] = [];
+ let currentId: string | null = folderId;
+ while (currentId) {
+ const folder = folderMap.get(currentId);
+ if (!folder) break;
+ names.unshift(folder.name);
+ currentId = folder.parentId;
+ }
+ return names;
+ };
+
+ const documentsWithPath = documents.map((doc) => ({
+ ...doc,
+ folderPath: doc.folderId ? buildBreadcrumb(doc.folderId) : [],
+ }));
+
+ const foldersWithPath = folders.map((folder) => ({
+ ...folder,
+ folderPath: folder.parentId ? buildBreadcrumb(folder.parentId) : [],
+ }));
+
+ return res.status(200).json({
+ documents: documentsWithPath,
+ folders: foldersWithPath,
+ });
+ } catch (error) {
+ console.error("Request error", error);
+ return res
+ .status(500)
+ .json({ error: "Error searching dataroom" });
+ }
+}
diff --git a/pages/datarooms/[id]/documents/[...name].tsx b/pages/datarooms/[id]/documents/[...name].tsx
index a83a0ff4..260e911c 100644
--- a/pages/datarooms/[id]/documents/[...name].tsx
+++ b/pages/datarooms/[id]/documents/[...name].tsx
@@ -5,34 +5,48 @@ import { useState } from "react";
import { useTeam } from "@/context/team-context";
import { ArrowUpDownIcon, FolderPlusIcon, PlusIcon } from "lucide-react";
-import { useDataroom, useDataroomItems } from "@/lib/swr/use-dataroom";
+import {
+ useDataroom,
+ useDataroomItems,
+ useDataroomSearch,
+} from "@/lib/swr/use-dataroom";
import DownloadDataroomButton from "@/components/datarooms/actions/download-dataroom";
import GenerateIndexButton from "@/components/datarooms/actions/generate-index-button";
import RebuildIndexButton from "@/components/datarooms/actions/rebuild-index-button";
import { BreadcrumbComponent } from "@/components/datarooms/dataroom-breadcrumb";
import { DataroomItemsList } from "@/components/datarooms/dataroom-items-list";
+import { DataroomSearchResults } from "@/components/datarooms/dataroom-search-results";
import { SidebarFolderTree } from "@/components/datarooms/folders";
import { DataroomSortableList } from "@/components/datarooms/sortable/sortable-list";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { LoadingDocuments } from "@/components/documents/loading-document";
import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
+import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
export default function Documents() {
const router = useRouter();
const { name } = router.query as { name: string[] };
+ const searchQuery = (router.query.search as string) || "";
const { dataroom } = useDataroom();
const { items, folderCount, documentCount, isLoading } = useDataroomItems({
name,
});
+ const {
+ documents: searchDocuments,
+ folders: searchFolders,
+ isLoading: isSearching,
+ error: searchError,
+ } = useDataroomSearch({ query: searchQuery });
const teamInfo = useTeam();
const [isReordering, setIsReordering] = useState<boolean>(false);
+ const isSearchActive = searchQuery.trim().length > 0;
return (
<AppLayout>
@@ -123,32 +137,63 @@ export default function Documents() {
<div className="grid h-full gap-4 pb-2 md:grid-cols-4">
<div className="hidden h-full min-h-0 truncate md:col-span-1 md:block">
<ScrollArea showScrollbar>
- <SidebarFolderTree dataroomId={dataroom?.id!} />
+ {dataroom?.id ? (
+ <SidebarFolderTree dataroomId={dataroom.id} />
+ ) : null}
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
<div className="min-w-0 space-y-4 md:col-span-3">
- <section id="documents-header-count" className="min-h-8" />
+ <SearchBoxPersisted
+ inputClassName="h-9"
+ placeholder="Search documents and folders..."
+ />
- {isLoading ? <LoadingDocuments count={3} /> : null}
-
- {isReordering ? (
- <DataroomSortableList
- mixedItems={items}
- folderPathName={name}
- teamInfo={teamInfo}
- dataroomId={dataroom?.id!}
- setIsReordering={setIsReordering}
- />
+ {isSearchActive ? (
+ <>
+ {isSearching || !dataroom?.id ? (
+ <LoadingDocuments count={3} />
+ ) : searchError ? (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
+ <p className="text-sm text-muted-foreground">
+ Something went wrong while searching. Please try again.
+ </p>
+ </div>
+ ) : (
+ <DataroomSearchResults
+ documents={searchDocuments}
+ folders={searchFolders}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ searchQuery={searchQuery}
+ />
+ )}
+ </>
) : (
- <DataroomItemsList
- mixedItems={items}
- teamInfo={teamInfo}
- dataroomId={dataroom?.id!}
- folderPathName={name}
- folderCount={folderCount}
- documentCount={documentCount}
- />
+ <>
+ <section id="documents-header-count" className="min-h-8" />
+
+ {isLoading || !dataroom?.id ? (
+ <LoadingDocuments count={3} />
+ ) : isReordering ? (
+ <DataroomSortableList
+ mixedItems={items}
+ folderPathName={name}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ setIsReordering={setIsReordering}
+ />
+ ) : (
+ <DataroomItemsList
+ mixedItems={items}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ folderPathName={name}
+ folderCount={folderCount}
+ documentCount={documentCount}
+ />
+ )}
+ </>
)}
</div>
</div>
diff --git a/pages/datarooms/[id]/documents/index.tsx b/pages/datarooms/[id]/documents/index.tsx
index 01ec772d..e656fbd4 100644
--- a/pages/datarooms/[id]/documents/index.tsx
+++ b/pages/datarooms/[id]/documents/index.tsx
@@ -1,3 +1,5 @@
+import { useRouter } from "next/router";
+
import { useState } from "react";
import { useTeam } from "@/context/team-context";
@@ -8,31 +10,48 @@ import {
PlusIcon,
} from "lucide-react";
-import { useDataroom, useDataroomItems } from "@/lib/swr/use-dataroom";
+import {
+ useDataroom,
+ useDataroomItems,
+ useDataroomSearch,
+} from "@/lib/swr/use-dataroom";
import DownloadDataroomButton from "@/components/datarooms/actions/download-dataroom";
import GenerateIndexButton from "@/components/datarooms/actions/generate-index-button";
import RebuildIndexButton from "@/components/datarooms/actions/rebuild-index-button";
import { DataroomItemsList } from "@/components/datarooms/dataroom-items-list";
+import { DataroomSearchResults } from "@/components/datarooms/dataroom-search-results";
import { SidebarFolderTree } from "@/components/datarooms/folders";
import { DataroomSortableList } from "@/components/datarooms/sortable/sortable-list";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { LoadingDocuments } from "@/components/documents/loading-document";
import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
+import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
import { ResponsiveButton } from "@/components/ui/responsive-button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { BadgeTooltip } from "@/components/ui/tooltip";
export default function Documents() {
+ const router = useRouter();
+ const searchQuery = (router.query.search as string) || "";
+
const { dataroom } = useDataroom();
const { items, folderCount, documentCount, isLoading } = useDataroomItems({
root: true,
});
+ const {
+ documents: searchDocuments,
+ folders: searchFolders,
+ isLoading: isSearching,
+ error: searchError,
+ } = useDataroomSearch({ query: searchQuery });
+
const teamInfo = useTeam();
const [isReordering, setIsReordering] = useState<boolean>(false);
+ const isSearchActive = searchQuery.trim().length > 0;
return (
<AppLayout>
@@ -134,30 +153,61 @@ export default function Documents() {
<div className="grid h-full gap-4 pb-2 md:grid-cols-4">
<div className="hidden h-full min-h-0 truncate md:col-span-1 md:block">
<ScrollArea showScrollbar>
- <SidebarFolderTree dataroomId={dataroom?.id!} />
+ {dataroom?.id ? (
+ <SidebarFolderTree dataroomId={dataroom.id} />
+ ) : null}
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
<div className="min-w-0 space-y-4 md:col-span-3">
- <section id="documents-header-count" className="min-h-8" />
+ <SearchBoxPersisted
+ inputClassName="h-9"
+ placeholder="Search documents and folders..."
+ />
- {isLoading ? <LoadingDocuments count={3} /> : null}
-
- {isReordering ? (
- <DataroomSortableList
- mixedItems={items}
- teamInfo={teamInfo}
- dataroomId={dataroom?.id!}
- setIsReordering={setIsReordering}
- />
+ {isSearchActive ? (
+ <>
+ {isSearching || !dataroom?.id ? (
+ <LoadingDocuments count={3} />
+ ) : searchError ? (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
+ <p className="text-sm text-muted-foreground">
+ Something went wrong while searching. Please try again.
+ </p>
+ </div>
+ ) : (
+ <DataroomSearchResults
+ documents={searchDocuments}
+ folders={searchFolders}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ searchQuery={searchQuery}
+ />
+ )}
+ </>
) : (
- <DataroomItemsList
- mixedItems={items}
- teamInfo={teamInfo}
- dataroomId={dataroom?.id!}
- folderCount={folderCount}
- documentCount={documentCount}
- />
+ <>
+ <section id="documents-header-count" className="min-h-8" />
+
+ {isLoading || !dataroom?.id ? (
+ <LoadingDocuments count={3} />
+ ) : isReordering ? (
+ <DataroomSortableList
+ mixedItems={items}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ setIsReordering={setIsReordering}
+ />
+ ) : (
+ <DataroomItemsList
+ mixedItems={items}
+ teamInfo={teamInfo}
+ dataroomId={dataroom.id}
+ folderCount={folderCount}
+ documentCount={documentCount}
+ />
+ )}
+ </>
)}
</div>
</div>