Skip to content

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

feat: add bulk delete documents

Marc Seitz6415f85905e2
diff --git a/components/documents/documents-list.tsx b/components/documents/documents-list.tsx
index 8fa53ab0..bf9feca8 100644
--- a/components/documents/documents-list.tsx
+++ b/components/documents/documents-list.tsx
@@ -16,25 +16,33 @@ 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 {
+ FileIcon,
+ FolderIcon,
+ FolderInputIcon,
+ Trash2Icon,
+ XIcon,
+} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { UploadNotificationDrawer } from "@/components/upload-notification";
import UploadZone from "@/components/upload-zone";
+import { moveDocumentToFolder } from "@/lib/documents/move-documents";
import { FolderWithCount } from "@/lib/swr/use-documents";
import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";
import { useMediaQuery } from "@/lib/utils/use-media-query";
import { Button } from "../ui/button";
import { Portal } from "../ui/portal";
+import { ButtonTooltip } from "../ui/tooltip";
import DocumentCard from "./document-card";
import { DraggableItem } from "./drag-and-drop/draggable-item";
import { DroppableFolder } from "./drag-and-drop/droppable-folder";
import { EmptyDocuments } from "./empty-document";
import FolderCard from "./folder-card";
+import { MoveToFolderModal } from "./move-folder-modal";
+import { useDeleteDocumentsModal } from "./settings/delete-documents-modal";
export function DocumentsList({
folders,
@@ -56,17 +64,23 @@ export function DocumentsList({
{ fileName: string; message: string }[]
>([]);
- const [showDrawer, setShowDrawer] = useState(false);
+ const [showDrawer, setShowDrawer] = useState<boolean>(false);
const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);
- const [draggedDocumentName, setDraggedDocumentName] = useState<string | null>(
- null,
- );
+
+ const [draggedDocument, setDraggedDocument] =
+ useState<DocumentWithLinksAndLinkCountAndViewCount | null>(null);
const [isOverFolder, setIsOverFolder] = useState<boolean>(false);
const [isDragging, setIsDragging] = useState<boolean>(false);
+ const { setShowDeleteDocumentsModal, DeleteDocumentsModal } =
+ useDeleteDocumentsModal({
+ documentIds: selectedDocuments,
+ setSelectedDocuments: setSelectedDocuments,
+ });
+
const sensors = useSensors(
useSensor(MouseSensor),
useSensor(TouchSensor),
@@ -87,7 +101,9 @@ export function DocumentsList({
setIsDragging(true);
// Set draggedDocumentName for DragOverlay
if (event.active.data.current?.type === "document") {
- setDraggedDocumentName(event.active.data.current.name);
+ setDraggedDocument(
+ documents?.find((doc) => doc.id === event.active.id) ?? null,
+ );
}
const documentId = event.active.id as string;
// Find the index of the document that's being dragged
@@ -97,15 +113,15 @@ export function DocumentsList({
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
- // }
+ 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 });
+ setDragOffset({ x: 0, y: yOffset });
// Select the document if it's not already selected
if (!isSelected) {
@@ -130,7 +146,7 @@ export function DocumentsList({
setIsDragging(false);
const { active, over } = event;
- setDraggedDocumentName(null);
+ setDraggedDocument(null);
if (!over) return;
@@ -183,11 +199,16 @@ export function DocumentsList({
<FolderInputIcon className="h-5 w-5" />
</Button>
</ButtonTooltip>
+ <ButtonTooltip content="Delete">
+ <Button
+ onClick={() => setShowDeleteDocumentsModal(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" />
+ <Trash2Icon className="h-5 w-5" />
</Button>
+ </ButtonTooltip>
</div>
);
} else {
diff --git a/components/documents/settings/delete-documents-modal.tsx b/components/documents/settings/delete-documents-modal.tsx
new file mode 100644
index 00000000..6d85630b
--- /dev/null
+++ b/components/documents/settings/delete-documents-modal.tsx
@@ -0,0 +1,211 @@
+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 { Input } from "@/components/ui/input";
+import { Modal } from "@/components/ui/modal";
+
+import { useAnalytics } from "@/lib/analytics";
+
+function DeleteDocumentsModal({
+ showDeleteDocumentsModal,
+ setShowDeleteDocumentsModal,
+ documentIds,
+ setSelectedDocuments,
+}: {
+ showDeleteDocumentsModal: boolean;
+ setShowDeleteDocumentsModal: Dispatch<SetStateAction<boolean>>;
+ documentIds: 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);
+ const [isValid, setIsValid] = useState(false);
+
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const { value } = e.target;
+ // Check if the input matches the pattern
+ if (value === "permanently delete") {
+ setIsValid(true);
+ } else {
+ setIsValid(false);
+ }
+ };
+
+ async function deleteDocuments(documentIds: string[]) {
+ return new Promise(async (resolve, reject) => {
+ setDeleting(true);
+
+ try {
+ const deletePromises = documentIds.map((documentId) =>
+ fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/documents/${documentId}`,
+ {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ ).then(async (res) => {
+ if (!res.ok) {
+ const error = await res.json();
+ throw new Error(
+ `Failed to delete document ${documentId}: ${error.message}`,
+ );
+ }
+ analytics.capture("Document Deleted", {
+ team: teamInfo?.currentTeam?.id,
+ documentId,
+ });
+ return documentId; // Return the ID of the successfully deleted 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}/${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 {
+ setShowDeleteDocumentsModal(false);
+ }
+ });
+ }
+
+ return (
+ <Modal
+ showModal={showDeleteDocumentsModal}
+ setShowModal={setShowDeleteDocumentsModal}
+ noBackdropBlur
+ >
+ <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">
+ Delete {documentIds.length} Document{documentIds.length > 1 && "s"}
+ </DialogTitle>
+ <DialogDescription>
+ Warning: This will permanently delete your selected documents, all
+ associated links and their respective views.
+ </DialogDescription>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ toast.promise(deleteDocuments(documentIds), {
+ loading: "Deleting documents...",
+ success: "Documents deleted 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"
+ >
+ <div>
+ <label
+ htmlFor="verification"
+ className="block text-sm text-muted-foreground"
+ >
+ To confirm deletion, type{" "}
+ <span className="font-semibold text-foreground">
+ permanently delete
+ </span>{" "}
+ below
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <Input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern="permanently delete"
+ required
+ autoComplete="off"
+ className="bg-white dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent"
+ onInput={handleInputChange}
+ />
+ </div>
+ </div>
+
+ <Button variant="destructive" loading={deleting} disabled={!isValid}>
+ Confirm delete documents
+ </Button>
+ </form>
+ </Modal>
+ );
+}
+
+export function useDeleteDocumentsModal({
+ documentIds,
+ setSelectedDocuments,
+}: {
+ documentIds: string[];
+ setSelectedDocuments: Dispatch<SetStateAction<string[]>>;
+}) {
+ const [showDeleteDocumentsModal, setShowDeleteDocumentsModal] =
+ useState(false);
+
+ const DeleteDocumentsModalCallback = useCallback(() => {
+ return (
+ <DeleteDocumentsModal
+ showDeleteDocumentsModal={showDeleteDocumentsModal}
+ setShowDeleteDocumentsModal={setShowDeleteDocumentsModal}
+ documentIds={documentIds}
+ setSelectedDocuments={setSelectedDocuments}
+ />
+ );
+ }, [
+ showDeleteDocumentsModal,
+ setShowDeleteDocumentsModal,
+ documentIds,
+ setSelectedDocuments,
+ ]);
+
+ return useMemo(
+ () => ({
+ setShowDeleteDocumentsModal,
+ DeleteDocumentsModal: DeleteDocumentsModalCallback,
+ }),
+ [setShowDeleteDocumentsModal, DeleteDocumentsModalCallback],
+ );
+}
diff --git a/components/ui/modal.tsx b/components/ui/modal.tsx
index ddc4debb..0aee9e18 100644
--- a/components/ui/modal.tsx
+++ b/components/ui/modal.tsx
@@ -18,6 +18,7 @@ export function Modal({
onClose,
desktopOnly,
preventDefaultClose,
+ noBackdropBlur = false,
}: {
children: React.ReactNode;
className?: string;
@@ -26,6 +27,7 @@ export function Modal({
onClose?: () => void;
desktopOnly?: boolean;
preventDefaultClose?: boolean;
+ noBackdropBlur?: boolean;
}) {
const router = useRouter();
@@ -88,13 +90,16 @@ export function Modal({
<Dialog.Overlay
// for detecting when there's an active opened modal
id="modal-backdrop"
- className="animate-fade-in fixed inset-0 z-50 bg-background/80 backdrop-blur-md"
+ className={cn(
+ "fixed inset-0 z-50 animate-fade-in bg-background/80",
+ !noBackdropBlur && "backdrop-blur-md",
+ )} // backdrop-blur-md
/>
<Dialog.Content
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
className={cn(
- "animate-scale-in fixed inset-0 z-50 m-auto max-h-fit w-full max-w-md overflow-hidden border border-gray-200 bg-background p-0 shadow-xl dark:border-gray-800 dark:bg-gray-900 sm:rounded-lg",
+ "fixed inset-0 z-50 m-auto max-h-fit w-full max-w-md animate-scale-in overflow-hidden border border-gray-200 bg-background p-0 shadow-xl dark:border-gray-800 dark:bg-gray-900 sm:rounded-lg",
className,
)}
>