Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: remove documents from dataroom
Marc Seitz0ff039aa0e41
diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsxindex b9932a67..96b703bd 100644--- a/components/datarooms/dataroom-document-card.tsx+++ b/components/datarooms/dataroom-document-card.tsx@@ -1,5 +1,6 @@import Image from "next/image";import Link from "next/link";+import { useRouter } from "next/router";import { useEffect, useRef, useState } from "react";@@ -34,21 +35,26 @@ import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";type DocumentsCardProps = {document: DataroomFolderDocument;teamInfo: TeamContextType | null;+ dataroomId: string;};export default function DataroomDocumentCard({document: dataroomDocument,teamInfo,+ dataroomId,}: DocumentsCardProps) {const { theme, systemTheme } = useTheme();const isLight =theme === "light" || (theme === "system" && systemTheme === "light");+ const router = useRouter();- const { isCopied, copyToClipboard } = useCopyToClipboard({});const [isFirstClick, setIsFirstClick] = useState<boolean>(false);const [menuOpen, setMenuOpen] = useState<boolean>(false);const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);const dropdownRef = useRef<HTMLDivElement | null>(null);+ /** current folder name */+ const currentFolderPath = router.query.name as string[] | undefined;+// https://github.com/radix-ui/primitives/issues/1241#issuecomment-1888232392useEffect(() => {if (!moveFolderOpen) {@@ -58,6 +64,89 @@ export default function DataroomDocumentCard({}}, [moveFolderOpen]);+ 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();++ console.log("isFirstClick", isFirstClick);+ if (isFirstClick) {+ handleRemoveDocument(documentId);+ setIsFirstClick(false);+ setMenuOpen(false); // Close the dropdown after deleting+ } else {+ setIsFirstClick(true);+ }+ };++ const handleRemoveDocument = async (documentId: string) => {+ // Prevent the first click from deleting the document+ if (!isFirstClick) {+ setIsFirstClick(true);+ return;+ }++ const endpoint = currentFolderPath+ ? `/folders/documents/${currentFolderPath.join("/")}`+ : "/documents";++ toast.promise(+ fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents/${documentId}`,+ {+ method: "DELETE",+ },+ ).then(() => {+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}${endpoint}`,+ null,+ {+ populateCache: (_, docs) => {+ return docs.filter(+ (doc: DocumentWithLinksAndLinkCountAndViewCount) =>+ doc.id !== documentId,+ );+ },+ revalidate: false,+ },+ );+ }),+ {+ loading: "Removing document...",+ success: "Document removed successfully.",+ error: "Failed to remove document. Try again.",+ },+ );+ };++ 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 (<><li className="group/row relative flex items-center justify-between rounded-lg border-0 p-3 ring-1 ring-gray-200 transition-all hover:bg-secondary hover:ring-gray-300 dark:bg-secondary dark:ring-gray-700 hover:dark:ring-gray-500 sm:p-4">@@ -114,7 +203,7 @@ export default function DataroomDocumentCard({</p></Link>- <DropdownMenu>+ <DropdownMenu open={menuOpen} onOpenChange={handleMenuStateChange}><DropdownMenuTrigger asChild><Button// size="icon"@@ -133,18 +222,20 @@ export default function DataroomDocumentCard({</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, dataroomDocument.id)+ }+ className="text-destructive duration-200 focus:bg-destructive focus:text-destructive-foreground"+ >+ {isFirstClick ? (+ "Really remove?"+ ) : (+ <>+ <TrashIcon className="mr-2 h-4 w-4" /> Remove document+ </>+ )}+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu></div>diff --git a/components/documents/documents-list.tsx b/components/documents/documents-list.tsxindex b7c4b40a..b8c85625 100644--- a/components/documents/documents-list.tsx+++ b/components/documents/documents-list.tsx@@ -114,6 +114,7 @@ export function DocumentsList({key={document.id}document={document as DataroomFolderDocument}teamInfo={teamInfo}+ dataroomId={dataroomId}/>);} else {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.tsindex 17289f6e..e9d8a784 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts@@ -72,6 +72,61 @@ export default async function handle(oldPath: currentPathName,});} catch (error) {}+ } else if (req.method === "DELETE") {+ /// DELETE /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 };++ 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 document = await prisma.dataroomDocument.delete({+ where: {+ id: documentId,+ dataroomId: dataroomId,+ },+ });++ if (!document) {+ return res.status(404).end("Document not found");+ }++ return res.status(204).end(); // No Content+ } catch (error) {}} else {// We only allow GET, PUT and DELETE requestsres.setHeader("Allow", ["GET", "PUT", "DELETE"]);