Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(dataroom): add bulk move and remove documents
Marc Seitz58574379225f
diff --git a/components/datarooms/actions/remove-document-modal.tsx b/components/datarooms/actions/remove-document-modal.tsxnew file mode 100644index 00000000..a2bd518a--- /dev/null+++ b/components/datarooms/actions/remove-document-modal.tsx@@ -0,0 +1,178 @@+import { useRouter } from "next/router";++import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";++import { useTeam } from "@/context/team-context";+import { toast } from "sonner";+import { mutate } from "swr";++import { Button } from "@/components/ui/button";+import { DialogDescription, DialogTitle } from "@/components/ui/dialog";+import { Modal } from "@/components/ui/modal";++import { useAnalytics } from "@/lib/analytics";++function RemoveDataroomDocumentsModal({+ showRemoveDataroomDocumentsModal,+ setShowRemoveDataroomDocumentsModal,+ documentIds,+ dataroomId,+ setSelectedDocuments,+}: {+ showRemoveDataroomDocumentsModal: boolean;+ setShowRemoveDataroomDocumentsModal: Dispatch<SetStateAction<boolean>>;+ documentIds: string[];+ dataroomId: string;+ setSelectedDocuments: Dispatch<SetStateAction<string[]>>;+}) {+ const router = useRouter();+ const folderPathName = router.query.name as string[] | undefined;+ const teamInfo = useTeam();+ const analytics = useAnalytics();++ const [deleting, setDeleting] = useState(false);++ async function removeDocuments(documentIds: string[]) {+ return new Promise(async (resolve, reject) => {+ setDeleting(true);++ try {+ const deletePromises = documentIds.map((documentId) =>+ fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents/${documentId}`,+ { method: "DELETE" },+ ).then(async (res) => {+ if (!res.ok) {+ const error = await res.json();+ throw new Error(+ `Failed to remove dataroom document ${documentId}: ${error.message}`,+ );+ }+ analytics.capture("Dataroom Document Removed", {+ team: teamInfo?.currentTeam?.id,+ documentId,+ });+ return documentId; // Return the ID of the successfully removed document+ }),+ );++ const results = await Promise.allSettled(deletePromises);++ const successfullyDeletedDocuments = results+ .filter((result) => result.status === "fulfilled")+ .map((result) => (result as PromiseFulfilledResult<string>).value);++ const errors = results+ .filter((result) => result.status === "rejected")+ .map((result) => result.reason);++ // Deselect only the successfully deleted documents+ setSelectedDocuments((prevSelected) =>+ prevSelected.filter(+ (id) => !successfullyDeletedDocuments.includes(id),+ ),+ );++ // Call mutate only once, after all deletions+ await mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}${folderPathName ? `/folders/documents/${folderPathName.join("/")}` : "/documents"}`,+ );++ setDeleting(false);++ if (errors.length) {+ reject(errors);+ } else {+ resolve(null);+ }+ } catch (error) {+ setDeleting(false);+ reject((error as Error).message);+ } finally {+ setShowRemoveDataroomDocumentsModal(false);+ }+ });+ }++ return (+ <Modal+ showModal={showRemoveDataroomDocumentsModal}+ setShowModal={setShowRemoveDataroomDocumentsModal}+ >+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">+ <DialogTitle className="text-2xl">+ Remove {documentIds.length} Document{documentIds.length > 1 && "s"}+ </DialogTitle>+ <DialogDescription>+ Existing views will not be affected. You can always add removed+ documents back to the dataroom.+ </DialogDescription>+ </div>++ <form+ onSubmit={async (e) => {+ e.preventDefault();+ toast.promise(removeDocuments(documentIds), {+ loading: "Removing documents...",+ success: "Documents removed successfully!",+ error: (err) => err,+ });+ }}+ className="flex flex-col space-y-6 bg-muted px-4 py-8 text-left dark:bg-gray-900 sm:px-8"+ >+ <Button variant="destructive" loading={deleting}>+ Remove documents+ </Button>+ </form>+ </Modal>+ );+}++export function useRemoveDataroomDocumentsModal({+ documentIds,+ dataroomId,+ setSelectedDocuments,+}: {+ documentIds: string[];+ dataroomId: string;+ setSelectedDocuments: Dispatch<SetStateAction<string[]>>;+}) {+ const [+ showRemoveDataroomDocumentsModal,+ setShowRemoveDataroomDocumentsModal,+ ] = useState(false);++ const RemoveDataroomDocumentsModalCallback = useCallback(() => {+ return (+ <RemoveDataroomDocumentsModal+ showRemoveDataroomDocumentsModal={showRemoveDataroomDocumentsModal}+ setShowRemoveDataroomDocumentsModal={+ setShowRemoveDataroomDocumentsModal+ }+ documentIds={documentIds}+ dataroomId={dataroomId}+ setSelectedDocuments={setSelectedDocuments}+ />+ );+ }, [+ showRemoveDataroomDocumentsModal,+ setShowRemoveDataroomDocumentsModal,+ documentIds,+ dataroomId,+ setSelectedDocuments,+ ]);++ return useMemo(+ () => ({+ setShowRemoveDataroomDocumentsModal,+ RemoveDataroomDocumentsModal: RemoveDataroomDocumentsModalCallback,+ }),+ [setShowRemoveDataroomDocumentsModal, RemoveDataroomDocumentsModalCallback],+ );+}diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsxindex 2640072a..5d40d91a 100644--- a/components/datarooms/dataroom-document-card.tsx+++ b/components/datarooms/dataroom-document-card.tsx@@ -5,7 +5,7 @@ import { useRouter } from "next/router";import { useEffect, useRef, useState } from "react";import { TeamContextType } from "@/context/team-context";-import { FolderInputIcon, MoreVertical, TrashIcon } from "lucide-react";+import { ArchiveXIcon, FolderInputIcon, MoreVertical } from "lucide-react";import { useTheme } from "next-themes";import { toast } from "sonner";import { mutate } from "swr";@@ -253,7 +253,7 @@ export default function DataroomDocumentCard({"Really remove?") : (<>- <TrashIcon className="mr-2 h-4 w-4" /> Remove document+ <ArchiveXIcon className="mr-2 h-4 w-4" /> Remove document</>)}</DropdownMenuItem>@@ -266,7 +266,7 @@ export default function DataroomDocumentCard({open={moveFolderOpen}setOpen={setMoveFolderOpen}dataroomId={dataroomDocument.dataroomId}- documentId={dataroomDocument.id}+ documentIds={[dataroomDocument.id]}documentName={dataroomDocument.document.name}/>) : null}diff --git a/components/datarooms/dataroom-items-list.tsx b/components/datarooms/dataroom-items-list.tsxindex a7198584..cd09cf90 100644--- a/components/datarooms/dataroom-items-list.tsx+++ b/components/datarooms/dataroom-items-list.tsx@@ -15,15 +15,20 @@ import {useSensors,} from "@dnd-kit/core";import { motion } from "framer-motion";-import { FileIcon, FolderIcon, XIcon } from "lucide-react";-import { toast } from "sonner";-import { mutate } from "swr";+import {+ ArchiveXIcon,+ FileIcon,+ FolderIcon,+ FolderInputIcon,+ XIcon,+} from "lucide-react";import { EmptyDocuments } from "@/components/documents/empty-document";import FolderCard from "@/components/documents/folder-card";import { UploadNotificationDrawer } from "@/components/upload-notification";import UploadZone from "@/components/upload-zone";+import { moveDataroomDocumentToFolder } from "@/lib/documents/move-dataroom-documents";import {DataroomFolderDocument,DataroomFolderWithCount,@@ -34,7 +39,10 @@ import { DraggableItem } from "../documents/drag-and-drop/draggable-item";import { DroppableFolder } from "../documents/drag-and-drop/droppable-folder";import { Button } from "../ui/button";import { Portal } from "../ui/portal";+import { ButtonTooltip } from "../ui/tooltip";+import { useRemoveDataroomDocumentsModal } from "./actions/remove-document-modal";import DataroomDocumentCard from "./dataroom-document-card";+import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";type FolderOrDocument =| (DataroomFolderWithCount & { itemType: "folder" })@@ -65,6 +73,7 @@ export function DataroomItemsList({>([]);const [showDrawer, setShowDrawer] = useState(false);+ const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);const [draggedDocumentName, setDraggedDocumentName] = useState<string | null>(@@ -73,6 +82,13 @@ export function DataroomItemsList({const [isOverFolder, setIsOverFolder] = useState<boolean>(false);const [isDragging, setIsDragging] = useState<boolean>(false);+ const { setShowRemoveDataroomDocumentsModal, RemoveDataroomDocumentsModal } =+ useRemoveDataroomDocumentsModal({+ documentIds: selectedDocuments,+ setSelectedDocuments: setSelectedDocuments,+ dataroomId,+ });+const sensors = useSensors(useSensor(MouseSensor),useSensor(TouchSensor),@@ -153,74 +169,18 @@ export function DataroomItemsList({// Move the document(s) to the new folderconst documentsToMove =selectedDocuments.length > 0 ? selectedDocuments : [activeId.toString()];- moveDocumentToFolder(documentsToMove, overId.toString());+ moveDataroomDocumentToFolder({+ documentIds: documentsToMove,+ folderId: overId.toString(),+ folderPathName,+ dataroomId,+ teamId: teamInfo?.currentTeam?.id,+ });setSelectedDocuments([]);setIsOverFolder(false);};- const moveDocumentToFolder = async (- documentIds: string[],- folderId: string,- ) => {- console.log("moving documents to folder", documentIds, folderId);- const key = `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}${folderPathName ? `/folders/documents/${folderPathName.join("/")}` : "/documents"}`;- // Optimistically update the UI by removing the documents from current folder- mutate(- key,- (documents: any[] | undefined) => {- if (!documents) return documents;-- // Filter out the documents that are being moved- const updatedDocuments = documents.filter(- (doc) => !documentIds.includes(doc.id),- );-- // Return the updated list of documents- return updatedDocuments;- },- false,- );-- try {- // Make the API call to move the document- const response = await fetch(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents/move`,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ documentIds, folderId }),- },- );-- if (!response.ok) {- throw new Error("Failed to move document");- }-- const { updatedCount, newPath } = await response.json();-- // Update local data using SWR's mutate- mutate(key);- // update folder document counts in current path- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders${folderPathName ? `/${folderPathName.join("/")}` : "?root=true"}`,- );- // update documents in new folder (or home)- newPath &&- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents${newPath}`,- );-- toast.success(- `${updatedCount} document${updatedCount > 1 ? "s" : ""} moved successfully`,- );- } catch (error) {- toast.error("Failed to move documents");- // Revert the UI back to the previous state- mutate(key);- }- };-const renderItem = (item: FolderOrDocument) => {const itemId = `${item.itemType}-${item.id}`;@@ -280,35 +240,54 @@ export function DataroomItemsList({const HeaderContent = memo(() => {if (selectedDocuments.length > 0) {return (- <div className="mb-2 flex items-center gap-x-2">- <p className="flex items-center gap-x-1 text-sm text-gray-400">+ <div className="mb-2 flex items-center gap-x-1 rounded-3xl bg-gray-100 text-sm text-foreground dark:bg-gray-800">+ <ButtonTooltip content="Clear selection"><ButtononClick={() => setSelectedDocuments([])}- className="size-5 rounded-full p-0.5"+ className="mx-1.5 my-1 size-8 rounded-full hover:bg-gray-200 hover:dark:bg-gray-700"+ variant="ghost"+ size="icon"+ >+ <XIcon className="h-5 w-5" />+ </Button>+ </ButtonTooltip>+ <div className="mr-2 tabular-nums">+ {selectedDocuments.length} selected+ </div>+ <ButtonTooltip content="Move">+ <Button+ onClick={() => setMoveFolderOpen(true)}+ className="mx-1.5 my-1 size-8 rounded-full hover:bg-gray-200 hover:dark:bg-gray-700"+ variant="ghost"+ size="icon"+ >+ <FolderInputIcon className="h-5 w-5" />+ </Button>+ </ButtonTooltip>+ <ButtonTooltip content="Remove">+ <Button+ onClick={() => setShowRemoveDataroomDocumentsModal(true)}+ className="mx-1.5 my-1 size-8 rounded-full hover:bg-destructive hover:text-destructive-foreground"variant="ghost"size="icon">- <XIcon className="h-4 w-4" />+ <ArchiveXIcon className="h-5 w-5" /></Button>- <span>- {selectedDocuments.length} document- {selectedDocuments.length > 1 ? "s" : ""} selected- </span>- </p>+ </ButtonTooltip></div>);} else {return (- <div className="mb-2 flex items-center gap-x-2">+ <div className="mb-2 flex items-center gap-x-2 pt-5">{folderCount > 0 ? (<p className="flex items-center gap-x-1 text-sm text-gray-400">- <FolderIcon className="h-4 w-4" />+ <FolderIcon className="h-5 w-5" /><span>{folderCount} folders</span></p>) : null}{documentCount > 0 ? (<p className="flex items-center gap-x-1 text-sm text-gray-400">- <FileIcon className="h-4 w-4" />+ <FileIcon className="h-5 w-5" /><span>{documentCount} documents</span></p>) : null}@@ -356,55 +335,67 @@ export function DataroomItemsList({)}</div>) : (- <DndContext- sensors={sensors}- onDragStart={handleDragStart}- onDragOver={handleDragOver}- onDragEnd={handleDragEnd}- onDragCancel={() => setIsOverFolder(false)}- measuring={{- droppable: {- strategy: MeasuringStrategy.Always,- },- }}- >- <ul role="list" className="space-y-4">- {mixedItems.map(renderItem)}- </ul>-- <Portal>- <DragOverlay className="cursor-default">- <motion.div- initial={{ scale: 1, opacity: 1 }}- animate={{ scale: 0.5, opacity: 1 }}- exit={{ scale: 1, opacity: 1 }}- transition={{ duration: 0.2 }}- className="relative flex h-20 w-40 items-center justify-center rounded-lg bg-gray-200"- >- <div className="h-20 w-40 rounded-lg bg-white text-foreground dark:bg-secondary">- {draggedDocumentName}- </div>- {selectedDocuments.length > 1 ? (- <div className="absolute right-0 top-0 rounded-full bg-white p-1 ring ring-gray-500">- <span className="text-xs font-semibold text-gray-500">- {selectedDocuments.length}- </span>+ <>+ <DndContext+ sensors={sensors}+ onDragStart={handleDragStart}+ onDragOver={handleDragOver}+ onDragEnd={handleDragEnd}+ onDragCancel={() => setIsOverFolder(false)}+ measuring={{+ droppable: {+ strategy: MeasuringStrategy.Always,+ },+ }}+ >+ <ul role="list" className="space-y-4">+ {mixedItems.map(renderItem)}+ </ul>++ <Portal>+ <DragOverlay className="cursor-default">+ <motion.div+ initial={{ scale: 1, opacity: 1 }}+ animate={{ scale: 0.5, opacity: 1 }}+ exit={{ scale: 1, opacity: 1 }}+ transition={{ duration: 0.2 }}+ className="relative flex h-20 w-40 items-center justify-center rounded-lg bg-gray-200"+ >+ <div className="h-20 w-40 rounded-lg bg-white text-foreground dark:bg-secondary">+ {draggedDocumentName}</div>- ) : null}- </motion.div>- </DragOverlay>- </Portal>-- <Portal containerId={"documents-header-count"}>- <HeaderContent />- </Portal>-- {mixedItems.length === 0 && (- <div className="flex h-full justify-center">- <EmptyDocuments />- </div>- )}- </DndContext>+ {selectedDocuments.length > 1 ? (+ <div className="absolute right-0 top-0 rounded-full bg-white p-1 ring ring-gray-500">+ <span className="text-xs font-semibold text-gray-500">+ {selectedDocuments.length}+ </span>+ </div>+ ) : null}+ </motion.div>+ </DragOverlay>+ </Portal>++ <Portal containerId={"documents-header-count"}>+ <HeaderContent />+ </Portal>++ {mixedItems.length === 0 && (+ <div className="flex h-full justify-center">+ <EmptyDocuments />+ </div>+ )}+ </DndContext>+ {moveFolderOpen ? (+ <MoveToDataroomFolderModal+ open={moveFolderOpen}+ setOpen={setMoveFolderOpen}+ setSelectedDocuments={setSelectedDocuments}+ documentIds={selectedDocuments}+ dataroomId={dataroomId}+ />+ ) : null}+ <RemoveDataroomDocumentsModal />+ </>)}</UploadZone>{showDrawer ? (diff --git a/components/datarooms/move-dataroom-folder-modal.tsx b/components/datarooms/move-dataroom-folder-modal.tsxindex 708c1689..6093e65d 100644--- a/components/datarooms/move-dataroom-folder-modal.tsx+++ b/components/datarooms/move-dataroom-folder-modal.tsx@@ -3,8 +3,6 @@ import { useRouter } from "next/router";import { useState } from "react";import { useTeam } from "@/context/team-context";-import { toast } from "sonner";-import { mutate } from "swr";import { SidebarFolderTreeSelection } from "@/components/datarooms/folders";import { Button } from "@/components/ui/button";@@ -17,19 +15,23 @@ import {DialogTitle,} from "@/components/ui/dialog";+import { moveDataroomDocumentToFolder } from "@/lib/documents/move-dataroom-documents";+import { TSelectedFolder } from "../documents/move-folder-modal";export function MoveToDataroomFolderModal({open,setOpen,dataroomId,- documentId,+ setSelectedDocuments,+ documentIds,documentName,}: {open: boolean;setOpen: React.Dispatch<React.SetStateAction<boolean>>;dataroomId: string;- documentId?: string;+ setSelectedDocuments?: React.Dispatch<React.SetStateAction<string[]>>;+ documentIds: string[];documentName?: string;}) {const router = useRouter();@@ -51,75 +53,17 @@ export function MoveToDataroomFolderModal({setLoading(true);- const key = `/api/teams/${teamId}/datarooms/${dataroomId}${currentPath !== "" ? `/folders/documents/${currentPath}` : "/documents"}`;-- mutate(- key,- (documents: any[] | undefined) => {- if (!documents) return documents;-- // Filter out the document that are being moved- const updatedDocuments = documents.filter(- (doc) => doc.id !== documentId,- );-- // Return the updated list of documents- return updatedDocuments;- },- false,- );-- try {- const response = await fetch(- `/api/teams/${teamId}/datarooms/${dataroomId}/documents/${documentId}`,- {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- folderId: selectedFolder.id,- currentPathName: "/" + currentPath,- }),- },- );-- if (!response.ok) {- const { message } = await response.json();- setLoading(false);- toast.error(message);- return;- }-- const { newPath } = (await response.json()) as {- newPath: string;- };-- // update current folder- mutate(key);- // update documents in new folder (or home)- mutate(- `/api/teams/${teamId}/datarooms/${dataroomId}${newPath ? `/folders/documents${newPath}` : "/documents"}`,- );- // update folder document counts in new path- mutate(- `/api/teams/${teamId}/datarooms/${dataroomId}/folders${newPath ? `${newPath}` : "?root=true"}`,- );- // update folder document counts in current path- mutate(- `/api/teams/${teamId}/datarooms/${dataroomId}/folders${currentPath !== "" ? `/${currentPath}` : "?root=true"}`,- );-- toast.success("Document moved successfully!");- } catch (error) {- console.error("Error moving document", error);- toast.error("Failed to move document");- // Revert the UI back to the previous state- mutate(key);- } finally {- setLoading(false);- setOpen(false);- }+ await moveDataroomDocumentToFolder({+ documentIds,+ folderId: selectedFolder.id!,+ folderPathName: currentPath ? currentPath.split("/") : undefined,+ dataroomId,+ teamId,+ });++ setLoading(false);+ setOpen(false); // Close the modal+ setSelectedDocuments?.([]); // Clear the selected documents};return (@@ -127,7 +71,10 @@ export function MoveToDataroomFolderModal({<DialogContent className="sm:max-w-[425px]"><DialogHeader className="text-start"><DialogTitle>- Move <span className="font-bold">{documentName}</span>+ Move{" "}+ <span className="font-bold">+ {documentName ? documentName : `${documentIds.length} items`}+ </span></DialogTitle><DialogDescription>Move your document to a folder.</DialogDescription></DialogHeader>diff --git a/lib/documents/move-dataroom-documents.ts b/lib/documents/move-dataroom-documents.tsnew file mode 100644index 00000000..2aa5e10e--- /dev/null+++ b/lib/documents/move-dataroom-documents.ts@@ -0,0 +1,80 @@+import { toast } from "sonner";+import { mutate } from "swr";++export const moveDataroomDocumentToFolder = async ({+ documentIds,+ folderId,+ folderPathName,+ dataroomId,+ teamId,+}: {+ documentIds: string[];+ folderId: string;+ folderPathName: string[] | undefined;+ dataroomId: string;+ teamId?: string;+}) => {+ if (!teamId) {+ toast.error("Team is required to move documents");+ return;+ }++ console.log("moving documents to folder", documentIds, folderId);+ const key = `/api/teams/${teamId}/datarooms/${dataroomId}${folderPathName ? `/folders/documents/${folderPathName.join("/")}` : "/documents"}`;+ // Optimistically update the UI by removing the documents from current folder+ mutate(+ key,+ (documents: any[] | undefined) => {+ if (!documents) return documents;++ // Filter out the documents that are being moved+ const updatedDocuments = documents.filter(+ (doc) => !documentIds.includes(doc.id),+ );++ // Return the updated list of documents+ return updatedDocuments;+ },+ false,+ );++ try {+ // Make the API call to move the document+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/documents/move`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ documentIds, folderId }),+ },+ );++ if (!response.ok) {+ throw new Error("Failed to move document");+ }++ const { updatedCount, newPath } = await response.json();++ // Update local data using SWR's mutate+ mutate(key);+ // update folder document counts in current path+ mutate(+ `/api/teams/${teamId}/datarooms/${dataroomId}/folders${folderPathName ? `/${folderPathName.join("/")}` : "?root=true"}`,+ );+ // update folder document counts in home+ !newPath &&+ mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/folders?root=true`);+ // update documents in new folder (`newPath` or home)+ mutate(+ `/api/teams/${teamId}/datarooms/${dataroomId}${newPath ? `/folders/documents/${newPath}` : "/documents"}`,+ );++ toast.success(+ `${updatedCount} document${updatedCount > 1 ? "s" : ""} moved successfully`,+ );+ } catch (error) {+ toast.error("Failed to move documents");+ // Revert the UI back to the previous state+ mutate(key);+ }+};