Skip to content

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

feat: add dataroom tree and move to folder

Marc Seitzb91a21f9d374
diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsx
index a9c68e47..a465169d 100644
--- a/components/datarooms/dataroom-document-card.tsx
+++ b/components/datarooms/dataroom-document-card.tsx
@@ -24,6 +24,7 @@ import { useEffect, useRef, useState } from "react";
import { useTheme } from "next-themes";
import { MoveToFolderModal } from "@/components/documents/move-folder-modal";
import { type DataroomFolderDocument } from "@/lib/swr/use-dataroom";
+import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";
type DocumentsCardProps = {
document: DataroomFolderDocument;
@@ -135,9 +136,10 @@ export default function DataroomDocumentCard({
</div>
</li>
{moveFolderOpen ? (
- <MoveToFolderModal
+ <MoveToDataroomFolderModal
open={moveFolderOpen}
setOpen={setMoveFolderOpen}
+ dataroomId={document.dataroomId}
documentId={document.id}
documentName={document.document.name}
/>
diff --git a/components/datarooms/folders/index.tsx b/components/datarooms/folders/index.tsx
new file mode 100644
index 00000000..d196f1eb
--- /dev/null
+++ b/components/datarooms/folders/index.tsx
@@ -0,0 +1,4 @@
+import { SidebarFolderTree } from "./sidebar-tree";
+import { SidebarFolderTreeSelection } from "./selection-tree";
+
+export { SidebarFolderTree, SidebarFolderTreeSelection };
diff --git a/components/datarooms/folders/selection-tree.tsx b/components/datarooms/folders/selection-tree.tsx
new file mode 100644
index 00000000..bfbe4811
--- /dev/null
+++ b/components/datarooms/folders/selection-tree.tsx
@@ -0,0 +1,104 @@
+import { FileTree } from "@/components/ui/nextra-filetree";
+import { memo, useMemo } from "react";
+import { buildNestedFolderStructure } from "./utils";
+import {
+ DataroomFolderWithDocuments,
+ useDataroomFoldersTree,
+} from "@/lib/swr/use-dataroom";
+
+const FolderComponentSelection = memo(
+ ({
+ folder,
+ selectedFolderId,
+ setFolderId,
+ }: {
+ folder: DataroomFolderWithDocuments;
+ selectedFolderId: string;
+ setFolderId: React.Dispatch<React.SetStateAction<string>>;
+ }) => {
+ // Recursively render child folders if they exist
+ const childFolders = useMemo(
+ () =>
+ folder.childFolders.map((childFolder) => (
+ <FolderComponentSelection
+ key={childFolder.id}
+ folder={childFolder}
+ selectedFolderId={selectedFolderId}
+ setFolderId={setFolderId}
+ />
+ )),
+ [folder.childFolders, selectedFolderId, setFolderId],
+ );
+
+ return (
+ <div
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setFolderId(folder.id);
+ }}
+ >
+ <FileTree.Folder
+ name={folder.name}
+ key={folder.id}
+ active={folder.id === selectedFolderId}
+ >
+ {childFolders}
+ </FileTree.Folder>
+ </div>
+ );
+ },
+);
+FolderComponentSelection.displayName = "FolderComponentSelection";
+
+const SidebarFoldersSelectipon = ({
+ folders,
+ selectedFolderId,
+ setFolderId,
+}: {
+ folders: DataroomFolderWithDocuments[];
+ selectedFolderId: string;
+ setFolderId: React.Dispatch<React.SetStateAction<string>>;
+}) => {
+ const nestedFolders = useMemo(() => {
+ if (folders) {
+ return buildNestedFolderStructure(folders);
+ }
+ return [];
+ }, [folders]);
+
+ return (
+ <FileTree>
+ {nestedFolders.map((folder) => (
+ <FolderComponentSelection
+ key={folder.id}
+ folder={folder}
+ selectedFolderId={selectedFolderId}
+ setFolderId={setFolderId}
+ />
+ ))}
+ </FileTree>
+ );
+};
+
+export function SidebarFolderTreeSelection({
+ dataroomId,
+ selectedFolderId,
+ setFolderId,
+}: {
+ dataroomId: string;
+ selectedFolderId: string;
+ setFolderId: React.Dispatch<React.SetStateAction<string>>;
+}) {
+ const { folders, error } = useDataroomFoldersTree({ dataroomId });
+
+ if (!folders || error) return null;
+
+ return (
+ <SidebarFoldersSelectipon
+ folders={folders}
+ selectedFolderId={selectedFolderId}
+ setFolderId={setFolderId}
+ />
+ );
+}
diff --git a/components/datarooms/folders/sidebar-tree.tsx b/components/datarooms/folders/sidebar-tree.tsx
new file mode 100644
index 00000000..686f3793
--- /dev/null
+++ b/components/datarooms/folders/sidebar-tree.tsx
@@ -0,0 +1,99 @@
+import { useRouter } from "next/router";
+import { FileTree } from "@/components/ui/nextra-filetree";
+import { memo, useMemo } from "react";
+import { buildNestedFolderStructure } from "./utils";
+import {
+ DataroomFolderWithDocuments,
+ useDataroomFoldersTree,
+} from "@/lib/swr/use-dataroom";
+
+const FolderComponent = memo(
+ ({
+ dataroomId,
+ folder,
+ }: {
+ dataroomId: string;
+ folder: DataroomFolderWithDocuments;
+ }) => {
+ const router = useRouter();
+
+ // Memoize the rendering of the current folder's documents
+ const documents = useMemo(
+ () =>
+ folder.documents.map((doc) => (
+ <FileTree.File
+ key={doc.id}
+ name={doc.document.name}
+ onToggle={() => router.push(`/documents/${doc.document.id}`)}
+ />
+ )),
+ [folder.documents, dataroomId, router.query.name],
+ );
+
+ // Recursively render child folders if they exist
+ const childFolders = useMemo(
+ () =>
+ folder.childFolders.map((childFolder) => (
+ <FolderComponent
+ key={childFolder.id}
+ dataroomId={dataroomId}
+ folder={childFolder}
+ />
+ )),
+ [folder.childFolders, dataroomId],
+ );
+
+ return (
+ <FileTree.Folder
+ name={folder.name}
+ key={folder.id}
+ active={
+ folder.path === "/" + (router.query.name as string[])?.join("/")
+ }
+ childActive={router.query.name?.includes(folder.name)}
+ onToggle={() =>
+ router.push(`/datarooms/${dataroomId}/documents${folder.path}`)
+ }
+ >
+ {childFolders}
+ {documents}
+ </FileTree.Folder>
+ );
+ },
+);
+FolderComponent.displayName = "FolderComponent";
+
+const SidebarFolders = ({
+ dataroomId,
+ folders,
+}: {
+ dataroomId: string;
+ folders: DataroomFolderWithDocuments[];
+}) => {
+ const nestedFolders = useMemo(() => {
+ if (folders) {
+ return buildNestedFolderStructure(folders);
+ }
+ return [];
+ }, [folders, dataroomId]);
+
+ return (
+ <FileTree>
+ {nestedFolders.map((folder) => (
+ <FolderComponent
+ key={folder.id}
+ dataroomId={dataroomId}
+ folder={folder}
+ />
+ ))}
+ </FileTree>
+ );
+};
+
+export function SidebarFolderTree({ dataroomId }: { dataroomId: string }) {
+ const { folders, error } = useDataroomFoldersTree({ dataroomId });
+
+ if (!folders || error) return null;
+
+ return <SidebarFolders dataroomId={dataroomId} folders={folders} />;
+}
diff --git a/components/datarooms/folders/utils.ts b/components/datarooms/folders/utils.ts
new file mode 100644
index 00000000..08f19b5d
--- /dev/null
+++ b/components/datarooms/folders/utils.ts
@@ -0,0 +1,26 @@
+import { DataroomFolderWithDocuments } from "@/lib/swr/use-dataroom";
+
+// Helper function to build nested folder structure
+export const buildNestedFolderStructure = (
+ folders: DataroomFolderWithDocuments[],
+) => {
+ const folderMap = new Map();
+
+ // Initialize every folder with an additional childFolders property
+ folders.forEach((folder) => {
+ folderMap.set(folder.id, { ...folder, childFolders: [] });
+ });
+
+ const rootFolders: DataroomFolderWithDocuments[] = [];
+
+ folderMap.forEach((folder, id) => {
+ if (folder.parentId) {
+ const parent = folderMap.get(folder.parentId);
+ parent.childFolders.push(folder);
+ } else {
+ rootFolders.push(folder);
+ }
+ });
+
+ return rootFolders;
+};
diff --git a/components/datarooms/move-dataroom-folder-modal.tsx b/components/datarooms/move-dataroom-folder-modal.tsx
new file mode 100644
index 00000000..5e08000d
--- /dev/null
+++ b/components/datarooms/move-dataroom-folder-modal.tsx
@@ -0,0 +1,123 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { useTeam } from "@/context/team-context";
+import { useState } from "react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { SidebarFolderTreeSelection } from "@/components/datarooms/folders";
+import { useRouter } from "next/router";
+
+export function MoveToDataroomFolderModal({
+ open,
+ setOpen,
+ dataroomId,
+ documentId,
+ documentName,
+}: {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ dataroomId: string;
+ documentId?: string;
+ documentName?: string;
+}) {
+ const router = useRouter();
+ const [folderId, setFolderId] = useState<string>("");
+ const [loading, setLoading] = useState<boolean>(false);
+
+ const teamInfo = useTeam();
+
+ const currentPath = router.query.name
+ ? (router.query.name as string[]).join("/")
+ : "";
+
+ const handleSubmit = async (event: any) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (folderId === "") return;
+
+ setLoading(true);
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents/${documentId}`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ folderId: folderId,
+ currentPathName: "/" + currentPath,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const { message } = await response.json();
+ setLoading(false);
+ toast.error(message);
+ return;
+ }
+
+ const { newPath, oldPath } = (await response.json()) as {
+ newPath: string;
+ oldPath: string;
+ };
+
+ toast.success("Document moved successfully!");
+
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders`,
+ );
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders${oldPath}`,
+ );
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders${newPath}`,
+ ).then(() => {
+ router.push(`/datarooms/${dataroomId}/documents${newPath}`);
+ });
+ } catch (error) {
+ console.error("Error moving document", error);
+ toast.error("Failed to move document. Try again.");
+ } finally {
+ setLoading(false);
+ setOpen(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>
+ Move <span className="font-bold">{documentName}</span>
+ </DialogTitle>
+ <DialogDescription>Move your document to a folder.</DialogDescription>
+ </DialogHeader>
+ <form>
+ <div className="mb-2">
+ <SidebarFolderTreeSelection
+ dataroomId={dataroomId}
+ selectedFolderId={folderId}
+ setFolderId={setFolderId}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button onClick={handleSubmit} className="w-full h-9">
+ Move to folder
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/lib/swr/use-dataroom.ts b/lib/swr/use-dataroom.ts
index c3580b0b..42ea76f7 100644
--- a/lib/swr/use-dataroom.ts
+++ b/lib/swr/use-dataroom.ts
@@ -118,8 +118,8 @@ export function useDataroomFolders({
};
}
-export type DRFolderWithDocuments = DataroomFolder & {
- childFolders: DRFolderWithDocuments[];
+export type DataroomFolderWithDocuments = DataroomFolder & {
+ childFolders: DataroomFolderWithDocuments[];
documents: {
id: string;
folderId: string;
@@ -135,7 +135,7 @@ export function useDataroomFoldersTree({ dataroomId }: { dataroomId: string }) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
- const { data: folders, error } = useSWR<DRFolderWithDocuments[]>(
+ const { data: folders, error } = useSWR<DataroomFolderWithDocuments[]>(
teamId && `/api/teams/${teamId}/datarooms/${dataroomId}/folders`,
fetcher,
{
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts
new file mode 100644
index 00000000..825ba9da
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts
@@ -0,0 +1,78 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/datarooms/:id/documents/:documentId
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+ const userId = (session.user as CustomUser).id;
+ const {
+ teamId,
+ id: dataroomId,
+ documentId,
+ } = req.query as { teamId: string; id: string; documentId: string };
+ const { folderId, currentPathName } = req.body as {
+ folderId: string;
+ currentPathName: string;
+ };
+
+ try {
+ // Check if the user is part of the team
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const document = await prisma.dataroomDocument.update({
+ where: {
+ id: documentId,
+ dataroomId: dataroomId,
+ },
+ data: {
+ folderId: folderId,
+ },
+ select: {
+ folder: {
+ select: {
+ path: true,
+ },
+ },
+ },
+ });
+
+ if (!document) {
+ return res.status(404).end("Document not found");
+ }
+
+ return res.status(200).json({
+ message: "Document moved successfully",
+ newPath: document.folder?.path,
+ oldPath: currentPathName,
+ });
+ } catch (error) {}
+ } else {
+ // We only allow GET, PUT and DELETE requests
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
similarity index 99%
rename from pages/api/teams/[teamId]/datarooms/[id]/documents.ts
rename to pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
index 34843640..7c8cb417 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/documents.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
@@ -45,6 +45,7 @@ export default async function handle(
const documents = await prisma.dataroomDocument.findMany({
where: {
dataroomId: dataroomId,
+ folderId: null,
},
orderBy: {
createdAt: "desc",
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/documents/[...name].ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/documents/[...name].ts
index 950d1e8a..7c4b575b 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/folders/documents/[...name].ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/documents/[...name].ts
@@ -68,6 +68,7 @@ export default async function handle(
},
select: {
id: true,
+ dataroomId: true,
folderId: true,
createdAt: true,
updatedAt: true,
diff --git a/pages/datarooms/[id]/documents/[...name].tsx b/pages/datarooms/[id]/documents/[...name].tsx
index 25da0283..79281c1b 100644
--- a/pages/datarooms/[id]/documents/[...name].tsx
+++ b/pages/datarooms/[id]/documents/[...name].tsx
@@ -21,6 +21,8 @@ import { NavMenu } from "@/components/navigation-menu";
import { BreadcrumbComponent } from "@/components/datarooms/dataroom-breadcrumb";
import { useRouter } from "next/router";
import DataroomDocumentCard from "@/components/datarooms/dataroom-document-card";
+import { SidebarFolderTree } from "@/components/datarooms/folders";
+import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
export default function Documents() {
const router = useRouter();
@@ -98,8 +100,13 @@ export default function Documents() {
/>
</header>
- <div className="grid md:grid-cols-4 gap-2">
- <div className="md:col-span-1">Tree</div>
+ <div className="grid md:grid-cols-4 gap-4 h-full">
+ <div className="md:col-span-1 truncate h-full">
+ <ScrollArea showScrollbar>
+ <SidebarFolderTree dataroomId={dataroom?.id!} />
+ <ScrollBar orientation="horizontal" />
+ </ScrollArea>
+ </div>
<div className="md:col-span-3 space-y-4">
<BreadcrumbComponent />
<section className="flex items-center gap-x-2 mb-2">
diff --git a/pages/datarooms/[id]/documents/index.tsx b/pages/datarooms/[id]/documents/index.tsx
index 3c664f70..33cf4df8 100644
--- a/pages/datarooms/[id]/documents/index.tsx
+++ b/pages/datarooms/[id]/documents/index.tsx
@@ -20,6 +20,7 @@ import { DataroomHeader } from "@/components/datarooms/dataroom-header";
import { NavMenu } from "@/components/navigation-menu";
import { BreadcrumbComponent } from "@/components/datarooms/dataroom-breadcrumb";
import DataroomDocumentCard from "@/components/datarooms/dataroom-document-card";
+import { SidebarFolderTree } from "@/components/datarooms/folders";
export default function Documents() {
const { dataroom } = useDataroom();
@@ -94,7 +95,9 @@ export default function Documents() {
</header>
<div className="grid md:grid-cols-4 gap-2">
- <div className="md:col-span-1">Tree</div>
+ <div className="md:col-span-1">
+ <SidebarFolderTree dataroomId={dataroom?.id!} />
+ </div>
<div className="md:col-span-3 space-y-4">
<BreadcrumbComponent />
<section className="flex items-center gap-x-2 mb-2">