Skip to content

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

feat(dataroom): add drag to move documents

Marc Seitz3f45d04bd55c
diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsx
index 091c6296..2640072a 100644
--- a/components/datarooms/dataroom-document-card.tsx
+++ b/components/datarooms/dataroom-document-card.tsx
@@ -33,12 +33,16 @@ type DocumentsCardProps = {
teamInfo: TeamContextType | null;
dataroomId: string;
isDragging?: boolean;
+ isSelected?: boolean;
+ isHovered?: boolean;
};
export default function DataroomDocumentCard({
document: dataroomDocument,
teamInfo,
dataroomId,
isDragging,
+ isSelected,
+ isHovered,
}: DocumentsCardProps) {
const { theme, systemTheme } = useTheme();
const isLight =
@@ -161,21 +165,26 @@ export default function DataroomDocumentCard({
className={cn(
"group/row relative flex items-center justify-between rounded-lg border-0 bg-white 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",
isDragging ? "cursor-grabbing" : "cursor-pointer",
+ isHovered && "bg-secondary ring-gray-300 dark:ring-gray-500",
)}
>
<div className="flex min-w-0 shrink items-center space-x-2 sm:space-x-4">
- <div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">
- {dataroomDocument.document.type === "notion" ? (
- <NotionIcon className="h-8 w-8" />
- ) : (
- <Image
- src={`/_icons/${dataroomDocument.document.type}${isLight ? "-light" : ""}.svg`}
- alt="File icon"
- width={50}
- height={50}
- />
- )}
- </div>
+ {!isSelected && !isHovered ? (
+ <div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">
+ {dataroomDocument.document.type === "notion" ? (
+ <NotionIcon className="h-8 w-8" />
+ ) : (
+ <Image
+ src={`/_icons/${dataroomDocument.document.type}${isLight ? "-light" : ""}.svg`}
+ alt="File icon"
+ width={50}
+ height={50}
+ />
+ )}
+ </div>
+ ) : (
+ <div className="mx-0.5 w-8 sm:mx-1"></div>
+ )}
<div className="flex-col">
<div className="flex items-center">
diff --git a/components/datarooms/dataroom-items-list.tsx b/components/datarooms/dataroom-items-list.tsx
index 23d8cad2..e7bbb532 100644
--- a/components/datarooms/dataroom-items-list.tsx
+++ b/components/datarooms/dataroom-items-list.tsx
@@ -1,6 +1,23 @@
-import { useState } from "react";
+import { memo, useCallback, useState } from "react";
import { TeamContextType } from "@/context/team-context";
+import {
+ DndContext,
+ DragEndEvent,
+ DragOverEvent,
+ DragOverlay,
+ DragStartEvent,
+ MeasuringStrategy,
+ MouseSensor,
+ PointerSensor,
+ TouchSensor,
+ useSensor,
+ 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 { EmptyDocuments } from "@/components/documents/empty-document";
import FolderCard from "@/components/documents/folder-card";
@@ -12,6 +29,10 @@ import {
DataroomFolderWithCount,
} from "@/lib/swr/use-dataroom";
+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 DataroomDocumentCard from "./dataroom-document-card";
type FolderOrDocument =
@@ -23,11 +44,15 @@ export function DataroomItemsList({
teamInfo,
folderPathName,
dataroomId,
+ folderCount,
+ documentCount,
}: {
mixedItems: FolderOrDocument[] | [];
teamInfo: TeamContextType | null;
folderPathName?: string[];
dataroomId: string;
+ folderCount: number;
+ documentCount: number;
}) {
const [uploads, setUploads] = useState<
{ fileName: string; progress: number; documentId?: string }[]
@@ -38,31 +63,225 @@ export function DataroomItemsList({
const [showDrawer, setShowDrawer] = useState(false);
+ const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);
+ const [draggedDocumentName, setDraggedDocumentName] = useState<string | null>(
+ null,
+ );
+ const [isOverFolder, setIsOverFolder] = useState<boolean>(false);
+ const [isDragging, setIsDragging] = useState<boolean>(false);
+
+ const sensors = useSensors(
+ useSensor(MouseSensor),
+ useSensor(TouchSensor),
+ useSensor(PointerSensor, {
+ activationConstraint: {
+ distance: 10,
+ },
+ }),
+ );
+
+ const handleSelect = useCallback((id: string) => {
+ setSelectedDocuments((prev) =>
+ prev.includes(id) ? prev.filter((docId) => docId !== id) : [...prev, id],
+ );
+ }, []);
+
+ const handleDragStart = (event: DragStartEvent) => {
+ setIsDragging(true);
+ // Set draggedDocumentName for DragOverlay
+ if (event.active.data.current?.type === "document") {
+ setDraggedDocumentName(event.active.data.current.name);
+ }
+ const documentId = event.active.id as string;
+ // Find the index of the document that's being dragged
+ const documentIndex = mixedItems
+ .filter((item) => item.itemType === "document")
+ .findIndex((doc) => doc.id === documentId);
+
+ // Determine if the document is already selected
+ const isSelected = selectedDocuments.includes(documentId);
+
+ // Calculate yOffset only if the task is already selected
+ // let yOffset = 0;
+ // if (isSelected) {
+ // const firstSelectedIndex = documents?.findIndex((document) =>
+ // selectedDocuments.includes(document.id.toString()),
+ // );
+ // yOffset = (documentIndex - firstSelectedIndex) * 80; // Example task height, adjust accordingly
+ // }
+
+ // setDragOffset({ x: 0, y: yOffset });
+
+ // Select the document if it's not already selected
+ if (!isSelected) {
+ setSelectedDocuments([documentId]);
+ }
+ };
+
+ const handleDragOver = (event: DragOverEvent) => {
+ const { over } = event;
+
+ if (!over) return;
+
+ const overType = over.data.current?.type;
+ if (overType === "folder") {
+ setIsOverFolder(true);
+ } else {
+ setIsOverFolder(false);
+ }
+ };
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ setIsDragging(false);
+ const { active, over } = event;
+
+ setDraggedDocumentName(null);
+
+ if (!over) return;
+
+ const activeId = active.id;
+ const overId = over.id;
+ const isActiveADocument = active.data.current?.type === "document";
+ const isOverAFolder = over.data.current?.type === "folder";
+
+ if (activeId === overId) return;
+ if (!isActiveADocument || !isOverAFolder) return;
+
+ // Move the document(s) to the new folder
+ const documentsToMove =
+ selectedDocuments.length > 0 ? selectedDocuments : [activeId.toString()];
+ moveDocumentToFolder(documentsToMove, overId.toString());
+
+ 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 } = await response.json();
+
+ // Update local data using SWR's mutate
+ mutate(key);
+ 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}`;
return (
<>
{item.itemType === "folder" ? (
- <FolderCard
- key={itemId}
- folder={item}
- teamInfo={teamInfo}
- isDataroom={!!dataroomId}
- dataroomId={dataroomId}
- />
+ <DroppableFolder key={itemId} id={item.id}>
+ <FolderCard
+ folder={item}
+ teamInfo={teamInfo}
+ isDataroom={!!dataroomId}
+ dataroomId={dataroomId}
+ />
+ </DroppableFolder>
) : (
- <DataroomDocumentCard
+ <DraggableItem
key={itemId}
- document={item as DataroomFolderDocument}
- teamInfo={teamInfo}
- dataroomId={dataroomId}
- />
+ id={item.id}
+ isSelected={selectedDocuments.includes(item.id)}
+ onSelect={handleSelect}
+ isDraggingSelected={isDragging}
+ >
+ <DataroomDocumentCard
+ document={item as DataroomFolderDocument}
+ teamInfo={teamInfo}
+ dataroomId={dataroomId}
+ />
+ </DraggableItem>
)}
</>
);
};
+ 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">
+ <Button
+ onClick={() => setSelectedDocuments([])}
+ className="size-5 rounded-full p-0.5"
+ variant="ghost"
+ size="icon"
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ <span>
+ {selectedDocuments.length} document
+ {selectedDocuments.length > 1 ? "s" : ""} selected
+ </span>
+ </p>
+ </div>
+ );
+ } else {
+ return (
+ <div className="mb-2 flex items-center gap-x-2">
+ {folderCount > 0 ? (
+ <p className="flex items-center gap-x-1 text-sm text-gray-400">
+ <FolderIcon className="h-4 w-4" />
+ <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" />
+ <span>{documentCount} documents</span>
+ </p>
+ ) : null}
+ </div>
+ );
+ }
+ });
+ HeaderContent.displayName = "HeaderContent";
+
return (
<>
<UploadZone
@@ -86,15 +305,55 @@ export function DataroomItemsList({
setRejectedFiles={setRejectedFiles}
dataroomId={dataroomId}
>
- <ul role="list" className="space-y-4">
- {mixedItems.map(renderItem)}
- </ul>
-
- {mixedItems.length === 0 && (
- <div className="flex h-full justify-center">
- <EmptyDocuments />
- </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>
+ </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>
</UploadZone>
{showDrawer ? (
<UploadNotificationDrawer
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts
new file mode 100644
index 00000000..b59ad770
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts
@@ -0,0 +1,76 @@
+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 === "PATCH") {
+ // PATCH /api/teams/:teamId/datarooms/:id/documents/move
+ 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 } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const { documentIds, folderId } = req.body as {
+ documentIds: string[];
+ folderId: string;
+ };
+
+ // Ensure the user is an admin of the team
+ const team = await prisma.team.findUnique({
+ where: { id: teamId },
+ include: {
+ datarooms: {
+ where: { id: dataroomId },
+ },
+ users: {
+ where: {
+ role: { in: ["ADMIN", "MANAGER"] },
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team || team.users.length === 0 || team.datarooms.length === 0) {
+ return res.status(403).end("Forbidden");
+ }
+
+ // Update the folderId for the specified documents
+ const updatedDocuments = await prisma.dataroomDocument.updateMany({
+ where: {
+ id: { in: documentIds },
+ dataroomId: dataroomId,
+ },
+ data: {
+ folderId: folderId,
+ },
+ });
+
+ if (updatedDocuments.count === 0) {
+ return res.status(404).end("No documents were updated");
+ }
+
+ console.log("Documents moved successfully", updatedDocuments.count);
+
+ return res.status(200).json({
+ message: "Document moved successfully",
+ updatedCount: updatedDocuments.count,
+ });
+ } else {
+ // We only allow PATCH requests
+ res.setHeader("Allow", ["PATCH"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/documents/move.ts b/pages/api/teams/[teamId]/documents/move.ts
index 05a2b870..e5bbc742 100644
--- a/pages/api/teams/[teamId]/documents/move.ts
+++ b/pages/api/teams/[teamId]/documents/move.ts
@@ -3,10 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
-import { errorhandler } from "@/lib/errorHandler";
-import { deleteFile } from "@/lib/files/delete-file-server";
import prisma from "@/lib/prisma";
-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
export default async function handle(
diff --git a/pages/datarooms/[id]/documents/[...name].tsx b/pages/datarooms/[id]/documents/[...name].tsx
index f6a11107..e89f8bb8 100644
--- a/pages/datarooms/[id]/documents/[...name].tsx
+++ b/pages/datarooms/[id]/documents/[...name].tsx
@@ -121,20 +121,7 @@ export default function Documents() {
<div className="flex justify-between">
<div className="space-y-2">
<BreadcrumbComponent />
- <section className="mb-2 flex items-center gap-x-2">
- {folderCount > 0 ? (
- <p className="flex items-center gap-x-1 text-sm text-gray-400">
- <FolderIcon className="h-4 w-4" />
- <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" />
- <span>{documentCount} documents</span>
- </p>
- ) : null}
- </section>
+ <section id="documents-header-count" />
</div>
<div>
{items.length > 0 && !isReordering ? (
@@ -167,6 +154,8 @@ export default function Documents() {
teamInfo={teamInfo}
dataroomId={dataroom?.id!}
folderPathName={name}
+ folderCount={folderCount}
+ documentCount={documentCount}
/>
)}
</div>
diff --git a/pages/datarooms/[id]/documents/index.tsx b/pages/datarooms/[id]/documents/index.tsx
index 19ace494..a229a83e 100644
--- a/pages/datarooms/[id]/documents/index.tsx
+++ b/pages/datarooms/[id]/documents/index.tsx
@@ -115,20 +115,7 @@ export default function Documents() {
<div className="flex justify-between">
<div className="space-y-2">
<BreadcrumbComponent />
- <section className="mb-2 flex items-center gap-x-2">
- {folderCount > 0 ? (
- <p className="flex items-center gap-x-1 text-sm text-gray-400">
- <FolderIcon className="h-4 w-4" />
- <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" />
- <span>{documentCount} documents</span>
- </p>
- ) : null}
- </section>
+ <section id="documents-header-count" />
</div>
<div>
{!isReordering ? (
@@ -159,6 +146,8 @@ export default function Documents() {
mixedItems={items}
teamInfo={teamInfo}
dataroomId={dataroom?.id!}
+ folderCount={folderCount}
+ documentCount={documentCount}
/>
)}
</div>