Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add multi-select and drag to move to folder
Marc Seitza3a57a8a6ece
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsxindex a508fe2b..9d7b75c2 100644--- a/components/documents/document-card.tsx+++ b/components/documents/document-card.tsx@@ -32,19 +32,26 @@ import {} from "@/components/ui/dropdown-menu";import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";-import { nFormatter, timeAgo } from "@/lib/utils";+import { cn, nFormatter, timeAgo } from "@/lib/utils";import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";+import { Checkbox } from "../ui/checkbox";import { AddToDataroomModal } from "./add-document-to-dataroom-modal";import { MoveToFolderModal } from "./move-folder-modal";type DocumentsCardProps = {document: DocumentWithLinksAndLinkCountAndViewCount;teamInfo: TeamContextType | null;+ isDragging?: boolean;+ isSelected?: boolean;+ isHovered?: boolean;};export default function DocumentsCard({document: prismaDocument,teamInfo,+ isDragging,+ isSelected,+ isHovered,}: DocumentsCardProps) {const router = useRouter();const { theme, systemTheme } = useTheme();@@ -176,20 +183,29 @@ export default function DocumentsCard({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">+ <div+ 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",+ 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">- {prismaDocument.type === "notion" ? (- <NotionIcon className="h-8 w-8" />- ) : (- <Image- src={`/_icons/${prismaDocument.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">+ {prismaDocument.type === "notion" ? (+ <NotionIcon className="h-8 w-8" />+ ) : (+ <Image+ src={`/_icons/${prismaDocument.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">@@ -241,7 +257,7 @@ export default function DocumentsCard({e.stopPropagation();}}href={`/documents/${prismaDocument.id}`}- className="z-10 flex items-center space-x-1 rounded-md bg-gray-200 px-1.5 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100 dark:bg-gray-700 sm:px-2"+ className="z-20 flex items-center space-x-1 rounded-md bg-gray-200 px-1.5 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100 dark:bg-gray-700 sm:px-2"><BarChart className="h-3 w-3 text-muted-foreground sm:h-4 sm:w-4" /><p className="whitespace-nowrap text-xs text-muted-foreground sm:text-sm">@@ -255,7 +271,7 @@ export default function DocumentsCard({<Button// size="icon"variant="outline"- className="z-10 h-8 w-8 border-gray-200 bg-transparent p-0 hover:bg-gray-200 dark:border-gray-700 hover:dark:bg-gray-700 lg:h-9 lg:w-9"+ className="z-20 h-8 w-8 border-gray-200 bg-transparent p-0 hover:bg-gray-200 dark:border-gray-700 hover:dark:bg-gray-700 lg:h-9 lg:w-9"><span className="sr-only">Open menu</span><MoreVertical className="h-4 w-4" />@@ -291,7 +307,7 @@ export default function DocumentsCard({</DropdownMenuContent></DropdownMenu></div>- </li>+ </div>{moveFolderOpen ? (<MoveToFolderModalopen={moveFolderOpen}diff --git a/components/documents/documents-list.tsx b/components/documents/documents-list.tsxindex 89d493a2..042b78d4 100644--- a/components/documents/documents-list.tsx+++ b/components/documents/documents-list.tsx@@ -1,20 +1,38 @@-import { useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";+import React 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 { Skeleton } from "@/components/ui/skeleton";import { UploadNotificationDrawer } from "@/components/upload-notification";import UploadZone from "@/components/upload-zone";-import {- DataroomFolderDocument,- DataroomFolderWithCount,-} from "@/lib/swr/use-dataroom";import { FolderWithCount } from "@/lib/swr/use-documents";import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";+import { cn } from "@/lib/utils";-import DataroomDocumentCard from "../datarooms/dataroom-document-card";+import { Button } from "../ui/button";+import Portal from "../ui/portal";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";@@ -23,16 +41,11 @@ export function DocumentsList({documents,teamInfo,folderPathName,- dataroomId,}: {- folders: FolderWithCount[] | DataroomFolderWithCount[] | undefined;- documents:- | DocumentWithLinksAndLinkCountAndViewCount[]- | DataroomFolderDocument[]- | undefined;+ folders: FolderWithCount[] | undefined;+ documents: DocumentWithLinksAndLinkCountAndViewCount[] | undefined;teamInfo: TeamContextType | null;folderPathName?: string[];- dataroomId?: string;}) {const [uploads, setUploads] = useState<{ fileName: string; progress: number; documentId?: string }[]@@ -43,6 +56,194 @@ export function DocumentsList({const [showDrawer, setShowDrawer] = useState(false);+ const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });+ 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 = documents?.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}${folderPathName ? `/folders/documents/${folderPathName.join("/")}` : "/documents"}`;+ // Optimistically update the UI by removing the documents from current folder+ mutate(+ key,+ (documents: DocumentWithLinksAndLinkCountAndViewCount[] | 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}/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 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">+ {folders && folders.length > 0 && (+ <p className="flex items-center gap-x-1 text-sm text-gray-400">+ <FolderIcon className="h-4 w-4" />+ <span>+ {folders.length} folder{folders.length > 1 ? "s" : ""}+ </span>+ </p>+ )}+ {documents && documents.length > 0 && (+ <p className="flex items-center gap-x-1 text-sm text-gray-400">+ <FileIcon className="h-4 w-4" />+ <span>+ {documents.length} document{documents.length > 1 ? "s" : ""}+ </span>+ </p>+ )}+ </div>+ );+ }+ });+return (<><UploadZone@@ -64,90 +265,139 @@ export function DocumentsList({}}setUploads={setUploads}setRejectedFiles={setRejectedFiles}- dataroomId={dataroomId}>- <div className="space-y-4">- {/* Folders list */}- <ul role="list" className="space-y-4">- {folders- ? folders.map((folder) => {- return (- <FolderCard- key={folder.id}- folder={folder}- teamInfo={teamInfo}- isDataroom={dataroomId ? true : false}- dataroomId={dataroomId}- />- );- })- : Array.from({ length: 3 }).map((_, i) => (- <li- key={i}- className="relative flex w-full items-center space-x-3 rounded-lg border px-4 py-5 sm:px-6 lg:px-6"- >- <Skeleton key={i} className="h-9 w-9" />- <div>- <Skeleton key={i} className="h-4 w-32" />- <Skeleton key={i + 1} className="mt-2 h-3 w-12" />- </div>- <Skeleton- key={i + 1}- className="absolute right-5 top-[50%] h-5 w-20 -translate-y-[50%] transform"- />- </li>- ))}- </ul>-- {/* Documents list */}- <ul role="list" className="space-y-4">- {documents- ? documents.map((document) => {- if (dataroomId) {+ <DndContext+ sensors={sensors}+ onDragStart={handleDragStart}+ onDragOver={handleDragOver}+ onDragEnd={handleDragEnd}+ onDragCancel={() => setIsOverFolder(false)}+ measuring={{+ droppable: {+ strategy: MeasuringStrategy.Always,+ },+ }}+ >+ <div className="space-y-4">+ {/* Folders list */}+ <ul role="list" className="space-y-4">+ {folders+ ? folders.map((folder) => {return (- <DataroomDocumentCard- key={document.id}- document={document as DataroomFolderDocument}- teamInfo={teamInfo}- dataroomId={dataroomId}- />+ <DroppableFolder key={folder.id} id={folder.id}>+ <FolderCard+ key={folder.id}+ folder={folder}+ teamInfo={teamInfo}+ />+ </DroppableFolder>);- } else {+ })+ : Array.from({ length: 3 }).map((_, i) => (+ <li+ key={i}+ className="relative flex w-full items-center space-x-3 rounded-lg border px-4 py-5 sm:px-6 lg:px-6"+ >+ <Skeleton key={i} className="h-9 w-9" />+ <div>+ <Skeleton key={i} className="h-4 w-32" />+ <Skeleton key={i + 1} className="mt-2 h-3 w-12" />+ </div>+ <Skeleton+ key={i + 1}+ className="absolute right-5 top-[50%] h-5 w-20 -translate-y-[50%] transform"+ />+ </li>+ ))}+ </ul>++ {/* Documents list */}+ <ul role="list" className="space-y-4">+ {documents+ ? documents.map((document) => {return (- <DocumentCard+ <DraggableItemkey={document.id}- document={- document as DocumentWithLinksAndLinkCountAndViewCount- }- teamInfo={teamInfo}- />+ id={document.id}+ isSelected={selectedDocuments.includes(document.id)}+ onSelect={handleSelect}+ isDraggingSelected={isDragging}+ >+ <DocumentCard+ key={document.id}+ document={document}+ teamInfo={teamInfo}+ isDragging={+ isDragging &&+ selectedDocuments.includes(document.id)+ }+ />+ </DraggableItem>);- }- })- : Array.from({ length: 3 }).map((_, i) => (- <li- key={i}- className="relative flex w-full items-center space-x-3 rounded-lg border px-4 py-5 sm:px-6 lg:px-6"- >- <Skeleton key={i} className="h-9 w-9" />- <div>- <Skeleton key={i} className="h-4 w-32" />- <Skeleton key={i + 1} className="mt-2 h-3 w-12" />+ })+ : Array.from({ length: 3 }).map((_, i) => (+ <li+ key={i}+ className="relative flex w-full items-center space-x-3 rounded-lg border px-4 py-5 sm:px-6 lg:px-6"+ >+ <Skeleton key={i} className="h-9 w-9" />+ <div>+ <Skeleton key={i} className="h-4 w-32" />+ <Skeleton key={i + 1} className="mt-2 h-3 w-12" />+ </div>+ <Skeleton+ key={i + 1}+ className="absolute right-5 top-[50%] h-5 w-20 -translate-y-[50%] transform"+ />+ </li>+ ))}+ </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>- <Skeleton- key={i + 1}- className="absolute right-5 top-[50%] h-5 w-20 -translate-y-[50%] transform"- />- </li>- ))}- </ul>-- {documents && documents.length === 0 && (- <div className="flex items-center justify-center">- <EmptyDocuments />- </div>- )}- </div>+ ) : null}+ </motion.div>+ </DragOverlay>+ </Portal>++ <Portal containerId={"documents-header-count"}>+ <HeaderContent />+ </Portal>++ {/* {selectedDocuments.length > 0 ? (+ <Portal+ container={document.getElementById("documents-header-count")}+ >+ <p className="flex items-center gap-x-1 text-sm text-gray-400">+ <XIcon className="h-4 w-4" />+ <span>{selectedDocuments.length} documents selected</span>+ </p>+ </Portal>+ ) : null} */}++ {documents && documents.length === 0 && (+ <div className="flex items-center justify-center">+ <EmptyDocuments />+ </div>+ )}+ </div>+ </DndContext></UploadZone>{showDrawer ? (<UploadNotificationDrawerdiff --git a/components/documents/drag-and-drop/draggable-item.tsx b/components/documents/drag-and-drop/draggable-item.tsxnew file mode 100644index 00000000..e22047f7--- /dev/null+++ b/components/documents/drag-and-drop/draggable-item.tsx@@ -0,0 +1,81 @@+import React, { useCallback, useRef, useState } from "react";++import { useDraggable } from "@dnd-kit/core";++import { Checkbox } from "@/components/ui/checkbox";++import { cn } from "@/lib/utils";++interface DraggableItemProps {+ id: string;+ isSelected: boolean;+ onSelect: (id: string) => void;+ isDraggingSelected: boolean;+ children: React.ReactElement;+}++export function DraggableItem({+ id,+ isSelected,+ onSelect,+ isDraggingSelected,+ children,+}: DraggableItemProps) {+ const { attributes, listeners, setNodeRef, isDragging } = useDraggable({+ id: id,+ data: {+ type: "document",+ id: id,+ name: children.props.document.name,+ contentType: children.props.document.type,+ },+ });++ const [isHovered, setIsHovered] = useState(false);++ const handleClick = useCallback(() => {+ onSelect(id);+ }, [id, onSelect]);++ const style = {+ opacity: isSelected && isDraggingSelected ? 0.5 : 1,+ // transform: CSS.Transform.toString(transform),+ };++ const childWithProps = React.cloneElement(children, {+ isDragging,+ isSelected,+ isHovered,+ });++ return (+ <li+ ref={setNodeRef}+ style={style}+ {...attributes}+ {...listeners}+ // onClick={handleClick}+ onMouseEnter={() => setIsHovered(true)}+ onMouseLeave={() => setIsHovered(false)}+ className={cn(+ "group relative transition-all duration-100",+ isSelected ? "rounded-lg ring-2 ring-black dark:ring-gray-100" : "",+ )}+ >+ {/* <div className="absolute left-2 top-3 z-50 hidden h-14 w-14 items-center justify-center bg-secondary group-hover:flex"> */}+ <div+ className={cn(+ "absolute left-4 top-6 z-50 hidden items-center justify-center group-hover:flex sm:left-6 sm:top-7",+ isSelected ? "flex" : "",+ )}+ >+ <Checkbox+ className="h-6 w-6"+ checked={isSelected}+ onCheckedChange={handleClick}+ />+ </div>+ {childWithProps}+ </li>+ );+}diff --git a/components/documents/drag-and-drop/droppable-folder.tsx b/components/documents/drag-and-drop/droppable-folder.tsxnew file mode 100644index 00000000..d5561439--- /dev/null+++ b/components/documents/drag-and-drop/droppable-folder.tsx@@ -0,0 +1,32 @@+import React from "react";++import { useDroppable } from "@dnd-kit/core";++import { cn } from "@/lib/utils";++interface DroppableFolderProps {+ id: string;+ children: React.ReactElement;+}++export function DroppableFolder({ id, children }: DroppableFolderProps) {+ const { isOver, setNodeRef } = useDroppable({+ id: id,+ data: { type: "folder", id: id },+ });++ const childWithProps = React.cloneElement(children, {+ isOver,+ });++ return (+ <div+ ref={setNodeRef}+ className={cn(+ isOver && "rounded-lg ring-2 ring-black dark:ring-gray-100",+ )}+ >+ {childWithProps}+ </div>+ );+}diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsxindex a984ae1c..4b612d33 100644--- a/components/documents/folder-card.tsx+++ b/components/documents/folder-card.tsx@@ -1,4 +1,4 @@-import Link from "next/link";+import { useRouter } from "next/router";import { useEffect, useRef, useState } from "react";@@ -34,13 +34,18 @@ type FolderCardProps = {teamInfo: TeamContextType | null;isDataroom?: boolean;dataroomId?: string;+ isDragging?: boolean;+ isOver?: boolean;};export default function FolderCard({folder,teamInfo,isDataroom,dataroomId,+ isDragging,+ isOver,}: FolderCardProps) {+ const router = useRouter();const [openFolder, setOpenFolder] = useState<boolean>(false);const [isFirstClick, setIsFirstClick] = useState<boolean>(false);const [menuOpen, setMenuOpen] = useState<boolean>(false);@@ -176,9 +181,19 @@ export default function FolderCard({);};+ const handleCardClick = (e: React.MouseEvent) => {+ if (isDragging) {+ e.preventDefault();+ e.stopPropagation();+ return;+ }+ router.push(folderPath);+ };+return (<><div+ onClick={handleCardClick}className="group/row relative flex items-center justify-between rounded-lg border-0 bg-white p-3 ring-1 ring-gray-400 transition-all hover:bg-secondary hover:ring-gray-500 dark:bg-secondary dark:ring-gray-500 hover:dark:ring-gray-400 sm:p-4"><div className="flex min-w-0 shrink items-center space-x-2 sm:space-x-4">@@ -189,10 +204,7 @@ export default function FolderCard({<div className="flex-col"><div className="flex items-center"><h2 className="min-w-0 max-w-[150px] truncate text-sm font-semibold leading-6 text-foreground sm:max-w-md">- <Link href={`${folderPath}`} className="w-full truncate">- <span>{folder.name}</span>- <span className="absolute inset-0" />- </Link>+ {folder.name}</h2></div><div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">@@ -273,7 +285,16 @@ export default function FolderCard({</DropdownMenuContent></DropdownMenu></div>+ {/* only used for drag and drop */}+ {isOver && !isDragging && (+ <div className="absolute inset-0 flex items-center justify-center rounded-lg bg-black bg-opacity-20 dark:bg-white dark:bg-opacity-20">+ <span className="font-semibold text-black dark:text-gray-100">+ Drop to move+ </span>+ </div>+ )}</div>+{openFolder ? (<EditFolderModalopen={openFolder}diff --git a/pages/api/teams/[teamId]/documents/move.ts b/pages/api/teams/[teamId]/documents/move.tsnew file mode 100644index 00000000..7affcee0--- /dev/null+++ b/pages/api/teams/[teamId]/documents/move.ts@@ -0,0 +1,73 @@+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(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PATCH") {+ // PATCH /api/teams/:teamId/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 } = req.query as { teamId: 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: {+ users: {+ where: {+ role: "ADMIN",+ userId: userId,+ },+ },+ },+ });++ if (!team || team.users.length === 0) {+ return res.status(403).end("Forbidden");+ }++ // Update the folderId for the specified documents+ const updatedDocuments = await prisma.document.updateMany({+ where: {+ id: { in: documentIds },+ teamId: teamId,+ },+ 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/documents/index.tsx b/pages/documents/index.tsxindex 530281e9..cae09c6b 100644--- a/pages/documents/index.tsx+++ b/pages/documents/index.tsx@@ -17,7 +17,7 @@ export default function Documents() {return (<AppLayout>- <div className="sticky top-0 z-50 bg-white p-4 pb-0 sm:mx-4 sm:pt-8">+ <div className="sticky top-0 z-[100] bg-white p-4 pb-0 dark:bg-gray-900 sm:mx-4 sm:pt-8"><section className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12"><div className="space-y-1"><h2 className="text-xl font-semibold tracking-tight text-foreground sm:text-2xl">@@ -50,23 +50,10 @@ export default function Documents() {</Button></AddFolderModal></div>- {/* </div> */}</section>- <section className="mb-2 flex items-center gap-x-2">- {folders && folders.length > 0 ? (- <p className="flex items-center gap-x-1 text-sm text-gray-400">- <FolderIcon className="h-4 w-4" />- <span>{folders.length} folders</span>- </p>- ) : null}- {documents && documents.length > 0 ? (- <p className="flex items-center gap-x-1 text-sm text-gray-400">- <FileIcon className="h-4 w-4" />- <span>{documents.length} documents</span>- </p>- ) : null}- </section>+ {/* Portaled in from DocumentsList component */}+ <section id="documents-header-count" /><Separator className="mb-5 bg-gray-200 dark:bg-gray-800" /></div>diff --git a/pages/documents/tree/[...name].tsx b/pages/documents/tree/[...name].tsxindex 937fc3a8..507c0e44 100644--- a/pages/documents/tree/[...name].tsx+++ b/pages/documents/tree/[...name].tsx@@ -73,20 +73,8 @@ export default function DocumentTreePage() {</div></section>- <section className="mb-2 flex items-center gap-x-2">- {folders && folders.length > 0 ? (- <p className="flex items-center gap-x-1 text-sm text-gray-400">- <FolderIcon className="h-4 w-4" />- <span>{folders.length} folders</span>- </p>- ) : null}- {documents && documents.length > 0 ? (- <p className="flex items-center gap-x-1 text-sm text-gray-400">- <FileIcon className="h-4 w-4" />- <span>{documents.length} documents</span>- </p>- ) : null}- </section>+ {/* Portaled in from DocumentsList component */}+ <section id="documents-header-count" /><Separator className="mb-5 bg-gray-200 dark:bg-gray-800" />