Skip to content

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

feat: add delete folder

Marc Seitzefa87ceb1814
diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsx
index 70257305..67ca8a71 100644
--- a/components/documents/folder-card.tsx
+++ b/components/documents/folder-card.tsx
@@ -10,11 +10,13 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { MoreVertical, FolderIcon } from "lucide-react";
-import { useRef, useState } from "react";
+import { MoreVertical, FolderIcon, TrashIcon } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
import { FolderWithCount } from "@/lib/swr/use-documents";
import { DataroomFolderWithCount } from "@/lib/swr/use-dataroom";
import { EditFolderModal } from "../folders/edit-folder-modal";
+import { toast } from "sonner";
+import { mutate } from "swr";
type FolderCardProps = {
folder: FolderWithCount | DataroomFolderWithCount;
@@ -29,12 +31,96 @@ export default function FolderCard({
dataroomId,
}: FolderCardProps) {
const [openFolder, setOpenFolder] = useState<boolean>(false);
+ const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
+ const [menuOpen, setMenuOpen] = useState<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
const folderPath =
isDataroom && dataroomId
? `/datarooms/${dataroomId}/documents${folder.path}`
: `/documents/tree${folder.path}`;
+ const parentFolderPath = folder.path.substring(
+ 0,
+ folder.path.lastIndexOf("/"),
+ );
+
+ useEffect(() => {
+ function handleClickOutside(event: { target: any }) {
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
+ setMenuOpen(false);
+ setIsFirstClick(false);
+ }
+ }
+
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => {
+ document.removeEventListener("mousedown", handleClickOutside);
+ };
+ }, []);
+
+ const handleButtonClick = (event: any, documentId: string) => {
+ event.stopPropagation();
+ event.preventDefault();
+
+ if (isFirstClick) {
+ handleDeleteFolder(documentId);
+ setIsFirstClick(false);
+ setMenuOpen(false); // Close the dropdown after deleting
+ } else {
+ setIsFirstClick(true);
+ }
+ };
+
+ const handleDeleteFolder = async (folderId: string) => {
+ // Prevent the first click from deleting the document
+ if (!isFirstClick) {
+ setIsFirstClick(true);
+ return;
+ }
+
+ const endpointTargetType =
+ isDataroom && dataroomId ? `datarooms/${dataroomId}/folders` : "folders";
+
+ toast.promise(
+ fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/manage/${folderId}`,
+ {
+ method: "DELETE",
+ },
+ ),
+ {
+ loading: "Deleting folder...",
+ success: () => {
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,
+ );
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`,
+ );
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}${parentFolderPath}`,
+ );
+ return "Folder deleted successfully.";
+ },
+ error: "Failed to delete folder. Move documents first.",
+ },
+ );
+ };
+
+ const handleMenuStateChange = (open: boolean) => {
+ if (isFirstClick) {
+ setMenuOpen(true); // Keep the dropdown open on the first click
+ return;
+ }
+
+ // If the menu is closed, reset the isFirstClick state
+ if (!open) {
+ setIsFirstClick(false);
+ setMenuOpen(false); // Ensure the dropdown is closed
+ } else {
+ setMenuOpen(true); // Open the dropdown
+ }
+ };
return (
<>
@@ -84,7 +170,7 @@ export default function FolderCard({
</p>
</Link> */}
- <DropdownMenu>
+ <DropdownMenu open={menuOpen} onOpenChange={handleMenuStateChange}>
<DropdownMenuTrigger asChild>
<Button
// size="icon"
@@ -102,18 +188,18 @@ export default function FolderCard({
</DropdownMenuItem>
<DropdownMenuSeparator />
- {/* <DropdownMenuItem
- onClick={(event) => handleButtonClick(event, prismaDocument.id)}
- className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
- >
- {isFirstClick ? (
- "Really delete?"
- ) : (
- <>
- <TrashIcon className="w-4 h-4 mr-2" /> Delete document
- </>
- )}
- </DropdownMenuItem> */}
+ <DropdownMenuItem
+ onClick={(event) => handleButtonClick(event, folder.id)}
+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
+ >
+ {isFirstClick ? (
+ "Really delete?"
+ ) : (
+ <>
+ <TrashIcon className="w-4 h-4 mr-2" /> Delete Folder
+ </>
+ )}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/components/folders/add-folder-modal.tsx b/components/folders/add-folder-modal.tsx
index 4c194366..6a6a35d7 100644
--- a/components/folders/add-folder-modal.tsx
+++ b/components/folders/add-folder-modal.tsx
@@ -84,6 +84,9 @@ export function AddFolderModal({
analytics.capture("Folder Added", { folderName: folderName });
toast.success("Folder added successfully! 🎉");
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,
+ );
mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`);
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}${parentFolderPath}`,
diff --git a/components/folders/edit-folder-modal.tsx b/components/folders/edit-folder-modal.tsx
index b8f893a1..44cd3f6e 100644
--- a/components/folders/edit-folder-modal.tsx
+++ b/components/folders/edit-folder-modal.tsx
@@ -81,6 +81,9 @@ export function EditFolderModal({
toast.success("Folder updated successfully! 🎉");
mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`);
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,
+ );
mutate(
`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}${parentFolderPath}`,
);
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/index.ts
new file mode 100644
index 00000000..0a5d7957
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/index.ts
@@ -0,0 +1,97 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { errorhandler } from "@/lib/errorHandler";
+import slugify from "@sindresorhus/slugify";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "DELETE") {
+ // DELETE /api/teams/:teamId/datarooms/[:id]/folders/manage
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const {
+ teamId,
+ id: dataroomId,
+ folderId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ folderId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const dataroom = await prisma.dataroom.findUnique({
+ where: {
+ id: dataroomId,
+ teamId: team.id,
+ },
+ });
+
+ if (!dataroom) {
+ return res.status(401).end("Dataroom not found");
+ }
+
+ const folder = await prisma.dataroomFolder.findUnique({
+ where: {
+ id: folderId,
+ dataroomId: dataroomId,
+ },
+ select: {
+ _count: {
+ select: {
+ documents: true,
+ childFolders: true,
+ },
+ },
+ },
+ });
+
+ if (folder?._count.documents! > 0 || folder?._count.childFolders! > 0) {
+ return res.status(401).json({
+ message: "Folder contains documents or folders. Move them first",
+ });
+ }
+
+ await prisma.dataroomFolder.delete({
+ where: {
+ id: folderId,
+ dataroomId: dataroomId,
+ },
+ });
+
+ return res.status(204).end(); // 204 No Content response for successful deletes
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow DELETE requests
+ res.setHeader("Allow", ["DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/manage.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/index.ts
similarity index 58%
rename from pages/api/teams/[teamId]/datarooms/[id]/folders/manage.ts
rename to pages/api/teams/[teamId]/datarooms/[id]/folders/manage/index.ts
index 6e55a7a2..7edb4465 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/folders/manage.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/index.ts
@@ -55,15 +55,11 @@ export default async function handle(
return res.status(404).json({ message: "Folder not found" });
}
- console.log("Folder old path", folder.path);
-
// take the old path and replace the last part with the new name
const newPath = folder.path.split("/");
newPath.pop();
newPath.push(slugify(name));
- console.log("Folder new path", newPath.join("/"));
-
await prisma.dataroomFolder.update({
where: {
id: folderId,
@@ -80,64 +76,9 @@ export default async function handle(
} catch (error) {
errorhandler(error, res);
}
- } else if (req.method === "DELETE") {
- // DELETE /api/teams/:teamId/folders/manage
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).end("Unauthorized");
- return;
- }
-
- const { teamId } = req.query as { teamId: string };
- const { folderId } = req.body as { folderId: string };
-
- const userId = (session.user as CustomUser).id;
-
- try {
- const team = await prisma.team.findUnique({
- where: {
- id: teamId,
- users: {
- some: {
- userId: userId,
- },
- },
- },
- });
-
- if (!team) {
- return res.status(401).end("Unauthorized");
- }
-
- const documents = await prisma.document.findMany({
- where: {
- folderId: folderId,
- teamId: teamId,
- },
- select: {
- id: true,
- },
- });
-
- if (documents.length > 0) {
- return res
- .status(400)
- .json({ message: "Folder contains documents. Move them first" });
- }
-
- await prisma.folder.delete({
- where: {
- id: folderId,
- },
- });
-
- return res.status(204).end(); // 204 No Content response for successful deletes
- } catch (error) {
- errorhandler(error, res);
- }
} else {
- // We only allow GET, PUT and DELETE requests
- res.setHeader("Allow", ["PUT", "DELETE"]);
+ // We only allow PUT requests
+ res.setHeader("Allow", ["PUT"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/api/teams/[teamId]/folders/[...name].ts b/pages/api/teams/[teamId]/folders/[...name].ts
index f715c773..82fd39fb 100644
--- a/pages/api/teams/[teamId]/folders/[...name].ts
+++ b/pages/api/teams/[teamId]/folders/[...name].ts
@@ -76,7 +76,7 @@ export default async function handle(
}
} else {
// We only allow POST requests
- res.setHeader("Allow", ["GET", "POST"]);
+ res.setHeader("Allow", ["GET"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/api/teams/[teamId]/folders/manage/[folderId]/index.ts b/pages/api/teams/[teamId]/folders/manage/[folderId]/index.ts
new file mode 100644
index 00000000..a2be006b
--- /dev/null
+++ b/pages/api/teams/[teamId]/folders/manage/[folderId]/index.ts
@@ -0,0 +1,79 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { errorhandler } from "@/lib/errorHandler";
+import slugify from "@sindresorhus/slugify";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "DELETE") {
+ // DELETE /api/teams/:teamId/folders/manage/:folderId
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const { teamId, folderId } = req.query as {
+ teamId: string;
+ folderId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const folder = await prisma.folder.findUnique({
+ where: {
+ id: folderId,
+ },
+ select: {
+ _count: {
+ select: {
+ documents: true,
+ childFolders: true,
+ },
+ },
+ },
+ });
+
+ if (folder?._count.documents! > 0 || folder?._count.childFolders! > 0) {
+ return res.status(401).json({
+ message: "Folder contains documents or folders. Move them first",
+ });
+ }
+
+ await prisma.folder.delete({
+ where: {
+ id: folderId,
+ },
+ });
+
+ return res.status(204).end(); // 204 No Content response for successful deletes
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow GET, PUT and DELETE requests
+ res.setHeader("Allow", ["DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/folders/manage.ts b/pages/api/teams/[teamId]/folders/manage/index.ts
similarity index 57%
rename from pages/api/teams/[teamId]/folders/manage.ts
rename to pages/api/teams/[teamId]/folders/manage/index.ts
index 1019414a..54e6cca7 100644
--- a/pages/api/teams/[teamId]/folders/manage.ts
+++ b/pages/api/teams/[teamId]/folders/manage/index.ts
@@ -51,15 +51,11 @@ export default async function handle(
return res.status(404).json({ message: "Folder not found" });
}
- console.log("Folder old path", folder.path);
-
// take the old path and replace the last part with the new name
const newPath = folder.path.split("/");
newPath.pop();
newPath.push(slugify(name));
- console.log("Folder new path", newPath.join("/"));
-
await prisma.folder.update({
where: {
id: folderId,
@@ -76,64 +72,9 @@ export default async function handle(
} catch (error) {
errorhandler(error, res);
}
- } else if (req.method === "DELETE") {
- // DELETE /api/teams/:teamId/folders/manage
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).end("Unauthorized");
- return;
- }
-
- const { teamId } = req.query as { teamId: string };
- const { folderId } = req.body as { folderId: string };
-
- const userId = (session.user as CustomUser).id;
-
- try {
- const team = await prisma.team.findUnique({
- where: {
- id: teamId,
- users: {
- some: {
- userId: userId,
- },
- },
- },
- });
-
- if (!team) {
- return res.status(401).end("Unauthorized");
- }
-
- const documents = await prisma.document.findMany({
- where: {
- folderId: folderId,
- teamId: teamId,
- },
- select: {
- id: true,
- },
- });
-
- if (documents.length > 0) {
- return res
- .status(400)
- .json({ message: "Folder contains documents. Move them first" });
- }
-
- await prisma.folder.delete({
- where: {
- id: folderId,
- },
- });
-
- return res.status(204).end(); // 204 No Content response for successful deletes
- } catch (error) {
- errorhandler(error, res);
- }
} else {
- // We only allow GET, PUT and DELETE requests
- res.setHeader("Allow", ["PUT", "DELETE"]);
+ // We only allow PUT requests
+ res.setHeader("Allow", ["PUT"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}