Skip to content

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

fix: restore document rename in header and document cards

Marc Seitzebf8224a39f4
diff --git a/components/datarooms/edit-dataroom-document-modal.tsx b/components/datarooms/edit-dataroom-document-modal.tsx
index 85c1c266..5646ebe6 100644
--- a/components/datarooms/edit-dataroom-document-modal.tsx
+++ b/components/datarooms/edit-dataroom-document-modal.tsx
@@ -1,253 +1 @@
-import { useRouter } from "next/router";
-
-import { useState } from "react";
-
-import { useTeam } from "@/context/team-context";
-import { toast } from "sonner";
-import { mutate } from "swr";
-import { z } from "zod";
-
-import {
- type DataroomFolderDocument,
- type DataroomFolderWithDocuments,
-} from "@/lib/swr/use-dataroom";
-
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-
-type DataroomIncludeDocumentsItem =
- | DataroomFolderWithDocuments
- | {
- id: string;
- folderId: string | null;
- hierarchicalIndex: string | null;
- document:
- | {
- id: string;
- name: string;
- type: string;
- }
- | null
- | undefined;
- };
-
-function updateDocNameInDocuments(
- _: null,
- docs: DataroomFolderDocument[] | undefined,
- docId: string,
- newName: string,
-): DataroomFolderDocument[] | undefined {
- if (!docs) return docs;
- return docs.map((doc) =>
- doc.document.id === docId
- ? { ...doc, document: { ...doc.document, name: newName } }
- : doc,
- );
-}
-
-function updateDocNameInFolderTree(
- _: null,
- folders: DataroomFolderWithDocuments[] | undefined,
- docId: string,
- newName: string,
-): DataroomFolderWithDocuments[] | undefined {
- if (!folders) return folders;
- const updateFolder = (
- folder: DataroomFolderWithDocuments,
- ): DataroomFolderWithDocuments => ({
- ...folder,
- documents: (folder.documents ?? []).map((doc) =>
- doc.document.id === docId
- ? { ...doc, document: { ...doc.document, name: newName } }
- : doc,
- ),
- childFolders: (folder.childFolders ?? []).map(updateFolder),
- });
- return folders.map(updateFolder);
-}
-
-function updateDocNameInIncludeDocumentsTree(
- _: null,
- items: DataroomIncludeDocumentsItem[] | undefined,
- docId: string,
- newName: string,
-): DataroomIncludeDocumentsItem[] | undefined {
- if (!items) return items;
- const updateFolder = (
- folder: DataroomFolderWithDocuments,
- ): DataroomFolderWithDocuments => ({
- ...folder,
- documents: (folder.documents ?? []).map((doc) =>
- doc.document.id === docId
- ? { ...doc, document: { ...doc.document, name: newName } }
- : doc,
- ),
- childFolders: (folder.childFolders ?? []).map(updateFolder),
- });
-
- return items.map((item) => {
- if ("document" in item) {
- const { document } = item;
-
- if (!document) {
- return item;
- }
-
- return document.id === docId
- ? { ...item, document: { ...document, name: newName } }
- : item;
- }
-
- return updateFolder(item);
- });
-}
-
-export function EditDataroomDocumentModal({
- open,
- setOpen,
- documentId,
- documentName,
- dataroomId,
-}: {
- open: boolean;
- setOpen: React.Dispatch<React.SetStateAction<boolean>>;
- documentId: string;
- documentName: string;
- dataroomId: string;
-}) {
- const [name, setName] = useState<string>(documentName);
- const [loading, setLoading] = useState<boolean>(false);
-
- const teamInfo = useTeam();
- const router = useRouter();
- const currentFolderPath = router.query.name as string[] | undefined;
-
- const editDocumentNameSchema = z.object({
- name: z
- .string()
- .min(1, {
- message: "Please provide a document name.",
- })
- .max(255, {
- message: "Document name is too long.",
- }),
- });
-
- const handleSubmit = async (event: React.FormEvent) => {
- event.preventDefault();
- event.stopPropagation();
-
- const trimmedName = name.trim();
- const validation = editDocumentNameSchema.safeParse({ name: trimmedName });
- if (!validation.success) {
- return toast.error(validation.error.errors[0].message);
- }
-
- setLoading(true);
-
- const teamId = teamInfo?.currentTeam?.id;
- const baseKey = `/api/teams/${teamId}/datarooms/${dataroomId}`;
-
- try {
- const response = await fetch(
- `/api/teams/${teamId}/documents/${documentId}/update-name`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- name: trimmedName,
- }),
- },
- );
-
- if (!response.ok) {
- const { error, message } = await response.json();
- setLoading(false);
- toast.error(error || message || "Failed to update document name");
- return;
- }
-
- toast.success("Document name updated successfully!");
-
- mutate(`${baseKey}/documents`, null, {
- populateCache: (_, docs) =>
- updateDocNameInDocuments(_, docs, documentId, trimmedName),
- revalidate: false,
- });
-
- if (currentFolderPath) {
- mutate(
- `${baseKey}/folder-documents/${currentFolderPath.join("/")}`,
- null,
- {
- populateCache: (_, docs) =>
- updateDocNameInDocuments(_, docs, documentId, trimmedName),
- revalidate: false,
- },
- );
- }
-
- mutate(`${baseKey}/folders`, null, {
- populateCache: (_, folders) =>
- updateDocNameInFolderTree(_, folders, documentId, trimmedName),
- revalidate: false,
- });
- mutate(`${baseKey}/folders?include_documents=true`, null, {
- populateCache: (_, items) =>
- updateDocNameInIncludeDocumentsTree(
- _,
- items,
- documentId,
- trimmedName,
- ),
- revalidate: false,
- });
- } catch (error) {
- setLoading(false);
- toast.error("Error updating document name. Please try again.");
- return;
- } finally {
- setLoading(false);
- setOpen(false);
- }
- };
-
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader className="text-start">
- <DialogTitle>Rename Document</DialogTitle>
- <DialogDescription>Enter a new document name.</DialogDescription>
- </DialogHeader>
- <form onSubmit={handleSubmit}>
- <Label htmlFor="document-name-update" className="opacity-80">
- Document Name
- </Label>
- <Input
- id="document-name-update"
- value={name}
- placeholder="document-name"
- className="mb-4 mt-1 w-full"
- onChange={(e) => setName(e.target.value)}
- />
- <DialogFooter>
- <Button type="submit" className="h-9 w-full" loading={loading}>
- Update name
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- );
-}
+export { EditDocumentNameModal as EditDataroomDocumentModal } from "@/components/documents/edit-document-name-modal";
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsx
index 473d65a1..13949c73 100644
--- a/components/documents/document-card.tsx
+++ b/components/documents/document-card.tsx
@@ -11,6 +11,7 @@ import {
EyeIcon,
EyeOffIcon,
FileIcon,
+ FilePenIcon,
FolderIcon,
FolderInputIcon,
MoreVertical,
@@ -32,6 +33,7 @@ import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
import { DataroomTrialModal } from "@/components/datarooms/dataroom-trial-modal";
import { AddToDataroomModal } from "@/components/documents/add-document-to-dataroom-modal";
import { DocumentPreviewModal } from "@/components/documents/document-preview-modal";
+import { EditDocumentNameModal } from "@/components/documents/edit-document-name-modal";
import { MoveToFolderModal } from "@/components/documents/move-folder-modal";
import BarChart from "@/components/shared/icons/bar-chart";
import { Button } from "@/components/ui/button";
@@ -71,6 +73,7 @@ export default function DocumentsCard({
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
const [menuOpen, setMenuOpen] = useState<boolean>(false);
const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
+ const [renameOpen, setRenameOpen] = useState<boolean>(false);
const [addDataroomOpen, setAddDataroomOpen] = useState<boolean>(false);
const [trialModalOpen, setTrialModalOpen] = useState<boolean>(false);
const [planModalOpen, setPlanModalOpen] = useState<boolean>(false);
@@ -93,12 +96,12 @@ export default function DocumentsCard({
// https://github.com/radix-ui/primitives/issues/1241#issuecomment-1888232392
useEffect(() => {
- if (!moveFolderOpen || !addDataroomOpen) {
+ if (!moveFolderOpen && !addDataroomOpen && !renameOpen) {
setTimeout(() => {
document.body.style.pointerEvents = "";
});
}
- }, [moveFolderOpen, addDataroomOpen]);
+ }, [moveFolderOpen, addDataroomOpen, renameOpen]);
useEffect(() => {
function handleClickOutside(event: { target: any }) {
@@ -435,6 +438,15 @@ export default function DocumentsCard({
Quick preview
</DropdownMenuItem>
<DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ setRenameOpen(true);
+ }}
+ >
+ <FilePenIcon className="mr-2 h-4 w-4" />
+ Rename
+ </DropdownMenuItem>
<DropdownMenuItem onClick={() => setMoveFolderOpen(true)}>
<FolderInputIcon className="mr-2 h-4 w-4" />
Move to folder
@@ -484,6 +496,15 @@ export default function DocumentsCard({
/>
) : null}
+ {renameOpen ? (
+ <EditDocumentNameModal
+ open={renameOpen}
+ setOpen={setRenameOpen}
+ documentId={prismaDocument.id}
+ documentName={prismaDocument.name}
+ />
+ ) : null}
+
{addDataroomOpen ? (
<AddToDataroomModal
open={addDataroomOpen}
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsx
index 00fc8905..af1afb02 100644
--- a/components/documents/document-header.tsx
+++ b/components/documents/document-header.tsx
@@ -66,6 +66,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
import PlanBadge from "../billing/plan-badge";
import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
@@ -135,6 +136,7 @@ export default function DocumentHeader({
const { isFeatureEnabled } = useFeatureFlags();
const isRedactionEnabled = isFeatureEnabled("redaction");
const [isEditingName, setIsEditingName] = useState<boolean>(false);
+ const [nameDraft, setNameDraft] = useState<string>("");
const [menuOpen, setMenuOpen] = useState<boolean>(false);
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
const [orientationLoading, setOrientationLoading] = useState<boolean>(false);
@@ -149,8 +151,8 @@ export default function DocumentHeader({
const [selectedPlan, setSelectedPlan] = useState<PlanEnum>(PlanEnum.Pro);
const [exportModalOpen, setExportModalOpen] = useState<boolean>(false);
const [aiDialogOpen, setAiDialogOpen] = useState<boolean>(false);
- const nameRef = useRef<HTMLHeadingElement>(null);
- const enterPressedRef = useRef<boolean>(false);
+ const skipNameSubmitRef = useRef<boolean>(false);
+ const savingNameRef = useRef<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
const actionRows: React.ReactNode[][] = [];
@@ -199,51 +201,146 @@ export default function DocumentHeader({
}
}, [addDataRoomOpen, addDocumentVersion]);
+ const startEditingName = () => {
+ skipNameSubmitRef.current = false;
+ setNameDraft(prismaDocument.name);
+ setIsEditingName(true);
+ };
+
+ const refreshDocumentNameCaches = (newName: string) => {
+ const encodedDocumentId = encodeURIComponent(prismaDocument.id);
+
+ mutate(
+ `/api/teams/${teamId}/documents/${encodedDocumentId}`,
+ (current: DocumentWithVersion | undefined) =>
+ current ? { ...current, name: newName } : current,
+ { revalidate: true },
+ );
+ mutate(
+ `/api/teams/${teamId}/documents/${encodedDocumentId}/overview`,
+ (current: { document?: DocumentWithVersion } | undefined) =>
+ current?.document
+ ? {
+ ...current,
+ document: { ...current.document, name: newName },
+ }
+ : current,
+ { revalidate: true },
+ );
+
+ if (dataroomId && dataroomDocumentId) {
+ mutate(
+ `/api/teams/${teamId}/datarooms/${dataroomId}/documents/${encodeURIComponent(
+ dataroomDocumentId,
+ )}/overview`,
+ (
+ current:
+ | {
+ document?: DocumentWithVersion;
+ }
+ | undefined,
+ ) =>
+ current?.document
+ ? {
+ ...current,
+ document: { ...current.document, name: newName },
+ }
+ : current,
+ { revalidate: true },
+ );
+ }
+ };
+
+ const parseErrorMessage = async (response: Response) => {
+ const fallback = "Failed to update document name";
+ const raw = await response.text();
+ if (!raw) return fallback;
+
+ try {
+ const data = JSON.parse(raw) as { error?: string; message?: string };
+ return data.error || data.message || fallback;
+ } catch {
+ return raw;
+ }
+ };
+
const handleNameSubmit = async () => {
- if (enterPressedRef.current) {
- enterPressedRef.current = false;
+ if (!isEditingName || savingNameRef.current) return;
+
+ const newName = nameDraft.trim();
+ if (!newName) {
+ setNameDraft(prismaDocument.name);
+ setIsEditingName(false);
+ toast.error("Document name is required");
+ return;
+ }
+
+ if (newName === prismaDocument.name) {
+ setIsEditingName(false);
return;
}
- if (nameRef.current && isEditingName) {
- const newName = nameRef.current.innerText;
-
- if (newName !== prismaDocument!.name) {
- const response = await fetch(
- `/api/teams/${teamId}/documents/${prismaDocument!.id}/update-name`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- name: newName,
- }),
+
+ savingNameRef.current = true;
+ setIsEditingName(false);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/documents/${prismaDocument.id}/update-name`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
},
- );
+ body: JSON.stringify({
+ name: newName,
+ }),
+ },
+ );
- if (response.ok) {
- const { message } = await response.json();
- toast.success(message);
- } else {
- const { message } = await response.json();
- toast.error(message);
+ if (response.ok) {
+ let message = "Document name updated!";
+ try {
+ const data = (await response.json()) as { message?: string };
+ if (data.message) message = data.message;
+ } catch {
+ // keep fallback success message
}
+ toast.success(message);
+ refreshDocumentNameCaches(newName);
+ } else {
+ toast.error(await parseErrorMessage(response));
+ setNameDraft(prismaDocument.name);
}
- setIsEditingName(false);
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to update document name",
+ );
+ setNameDraft(prismaDocument.name);
+ } finally {
+ savingNameRef.current = false;
}
};
- const preventEnterAndSubmit = (
- event: React.KeyboardEvent<HTMLHeadingElement>,
- ) => {
+ const handleNameBlur = () => {
+ if (skipNameSubmitRef.current) {
+ skipNameSubmitRef.current = false;
+ return;
+ }
+ void handleNameSubmit();
+ };
+
+ const handleNameKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
- event.preventDefault(); // Prevent the default line break
- setIsEditingName(true);
- enterPressedRef.current = true;
- handleNameSubmit(); // Handle the submit
- if (nameRef.current) {
- nameRef.current.blur(); // Remove focus from the h2 element
- }
+ if (event.nativeEvent.isComposing) return;
+ event.preventDefault();
+ void handleNameSubmit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ skipNameSubmitRef.current = true;
+ setNameDraft(prismaDocument.name);
+ setIsEditingName(false);
}
};
@@ -621,20 +718,34 @@ export default function DocumentHeader({
})}
<div className="mt-1 flex min-w-0 flex-col lg:mt-0">
- <h2
- className="truncate rounded-md border border-transparent px-1 py-0.5 text-base font-semibold tracking-tight text-foreground duration-200 hover:cursor-text hover:border hover:border-border focus-visible:text-base sm:text-lg sm:focus-visible:text-lg lg:px-3 lg:py-1 lg:text-xl lg:focus-visible:text-xl xl:text-2xl"
- ref={nameRef}
- contentEditable={true}
- onFocus={() => setIsEditingName(true)}
- onBlur={handleNameSubmit}
- onKeyDown={preventEnterAndSubmit}
- title="Click to edit"
- dangerouslySetInnerHTML={{ __html: prismaDocument.name }}
- />
- {isEditingName && (
- <span className="mt-1 text-xs text-muted-foreground">
- {`Press <Enter> to save the name.`}
- </span>
+ {isEditingName ? (
+ <>
+ <Input
+ autoFocus
+ value={nameDraft}
+ onChange={(event) => setNameDraft(event.target.value)}
+ onFocus={(event) => event.currentTarget.select()}
+ onBlur={handleNameBlur}
+ onKeyDown={handleNameKeyDown}
+ aria-label="Document name"
+ className="h-auto truncate rounded-md border border-border px-1 py-0.5 text-base font-semibold tracking-tight text-foreground sm:text-lg lg:px-3 lg:py-1 lg:text-xl xl:text-2xl"
+ />
+ <span className="mt-1 text-xs text-muted-foreground">
+ Press Enter to save, Esc to cancel.
+ </span>
+ </>
+ ) : (
+ <h2 className="min-w-0">
+ <button
+ type="button"
+ onClick={startEditingName}
+ title="Click to edit"
+ aria-label={`Rename ${prismaDocument.name}`}
+ className="w-full truncate rounded-md border border-transparent px-1 py-0.5 text-left text-base font-semibold tracking-tight text-foreground duration-200 hover:cursor-text hover:border hover:border-border sm:text-lg lg:px-3 lg:py-1 lg:text-xl xl:text-2xl"
+ >
+ {prismaDocument.name}
+ </button>
+ </h2>
)}
</div>
diff --git a/components/documents/edit-document-name-modal.tsx b/components/documents/edit-document-name-modal.tsx
new file mode 100644
index 00000000..2c019237
--- /dev/null
+++ b/components/documents/edit-document-name-modal.tsx
@@ -0,0 +1,333 @@
+import { useRouter } from "next/router";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { z } from "zod";
+
+import {
+ type DataroomFolderDocument,
+ type DataroomFolderWithDocuments,
+} from "@/lib/swr/use-dataroom";
+import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+type DataroomIncludeDocumentsItem =
+ | DataroomFolderWithDocuments
+ | {
+ id: string;
+ folderId: string | null;
+ hierarchicalIndex: string | null;
+ document:
+ | {
+ id: string;
+ name: string;
+ type: string;
+ }
+ | null
+ | undefined;
+ };
+
+function updateFolderDocumentsName(
+ folder: DataroomFolderWithDocuments,
+ docId: string,
+ newName: string,
+): DataroomFolderWithDocuments {
+ return {
+ ...folder,
+ documents: (folder.documents ?? []).map((doc) =>
+ doc.document.id === docId
+ ? { ...doc, document: { ...doc.document, name: newName } }
+ : doc,
+ ),
+ childFolders: (folder.childFolders ?? []).map((child) =>
+ updateFolderDocumentsName(child, docId, newName),
+ ),
+ };
+}
+
+function updateDocNameInDocuments(
+ docs: DataroomFolderDocument[] | undefined,
+ docId: string,
+ newName: string,
+): DataroomFolderDocument[] | undefined {
+ if (!docs) return docs;
+ return docs.map((doc) =>
+ doc.document.id === docId
+ ? { ...doc, document: { ...doc.document, name: newName } }
+ : doc,
+ );
+}
+
+function updateDocNameInFolderTree(
+ folders: DataroomFolderWithDocuments[] | undefined,
+ docId: string,
+ newName: string,
+): DataroomFolderWithDocuments[] | undefined {
+ if (!folders) return folders;
+ return folders.map((folder) =>
+ updateFolderDocumentsName(folder, docId, newName),
+ );
+}
+
+function updateDocNameInIncludeDocumentsTree(
+ items: DataroomIncludeDocumentsItem[] | undefined,
+ docId: string,
+ newName: string,
+): DataroomIncludeDocumentsItem[] | undefined {
+ if (!items) return items;
+
+ return items.map((item) => {
+ if ("document" in item) {
+ const { document } = item;
+
+ if (!document) {
+ return item;
+ }
+
+ return document.id === docId
+ ? { ...item, document: { ...document, name: newName } }
+ : item;
+ }
+
+ return updateFolderDocumentsName(item, docId, newName);
+ });
+}
+
+function updateDocNameInTeamDocuments(
+ data:
+ | DocumentWithLinksAndLinkCountAndViewCount[]
+ | {
+ documents: DocumentWithLinksAndLinkCountAndViewCount[];
+ [key: string]: unknown;
+ }
+ | undefined,
+ docId: string,
+ newName: string,
+) {
+ if (!data) return data;
+
+ if (Array.isArray(data)) {
+ return data.map((doc) =>
+ doc.id === docId ? { ...doc, name: newName } : doc,
+ );
+ }
+
+ if (data.documents) {
+ return {
+ ...data,
+ documents: data.documents.map((doc) =>
+ doc.id === docId ? { ...doc, name: newName } : doc,
+ ),
+ };
+ }
+
+ return data;
+}
+
+async function parseRenameErrorMessage(response: Response) {
+ const fallback = "Failed to update document name";
+ const raw = await response.text();
+ if (!raw) return fallback;
+
+ try {
+ const data = JSON.parse(raw) as { error?: string; message?: string };
+ return data.error || data.message || fallback;
+ } catch {
+ return raw;
+ }
+}
+
+const editDocumentNameSchema = z.object({
+ name: z
+ .string()
+ .min(1, {
+ message: "Please provide a document name.",
+ })
+ .max(255, {
+ message: "Document name is too long.",
+ }),
+});
+
+export function EditDocumentNameModal({
+ open,
+ setOpen,
+ documentId,
+ documentName,
+ dataroomId,
+}: {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ documentId: string;
+ documentName: string;
+ dataroomId?: string;
+}) {
+ const [name, setName] = useState<string>(documentName);
+ const [loading, setLoading] = useState<boolean>(false);
+
+ const teamInfo = useTeam();
+ const router = useRouter();
+ const currentFolderPath = router.query.name as string[] | undefined;
+ const searchQuery = router.query.search;
+ const sortQuery = router.query.sort;
+
+ const handleSubmit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ const trimmedName = name.trim();
+ const validation = editDocumentNameSchema.safeParse({ name: trimmedName });
+ if (!validation.success) {
+ return toast.error(validation.error.errors[0].message);
+ }
+
+ setLoading(true);
+
+ const teamId = teamInfo?.currentTeam?.id;
+ if (!teamId) {
+ setLoading(false);
+ toast.error("Team not found");
+ return;
+ }
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/documents/${documentId}/update-name`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: trimmedName,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ toast.error(await parseRenameErrorMessage(response));
+ return;
+ }
+
+ toast.success("Document name updated successfully!");
+
+ const encodedDocumentId = encodeURIComponent(documentId);
+
+ mutate(`/api/teams/${teamId}/documents/${encodedDocumentId}`);
+ mutate(`/api/teams/${teamId}/documents/${encodedDocumentId}/overview`);
+
+ const page = Number(router.query.page) || 1;
+ const pageSize = Number(router.query.limit) || 10;
+ const queryParts: string[] = [];
+ if (searchQuery) queryParts.push(`query=${searchQuery}`);
+ if (sortQuery) queryParts.push(`sort=${sortQuery}`);
+ if (searchQuery || sortQuery) {
+ queryParts.push(`page=${page}&limit=${pageSize}`);
+ }
+ const queryString =
+ queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
+
+ if (currentFolderPath?.length) {
+ mutate(
+ `/api/teams/${teamId}/folder-documents/${currentFolderPath.join("/")}`,
+ null,
+ {
+ populateCache: (_result, data) =>
+ updateDocNameInTeamDocuments(data, documentId, trimmedName),
+ revalidate: false,
+ },
+ );
+ } else {
+ mutate(`/api/teams/${teamId}/documents${queryString}`, null, {
+ populateCache: (_result, data) =>
+ updateDocNameInTeamDocuments(data, documentId, trimmedName),
+ revalidate: false,
+ });
+ }
+
+ if (dataroomId) {
+ const baseKey = `/api/teams/${teamId}/datarooms/${dataroomId}`;
+
+ mutate(`${baseKey}/documents`, null, {
+ populateCache: (_result, docs) =>
+ updateDocNameInDocuments(docs, documentId, trimmedName),
+ revalidate: false,
+ });
+
+ if (currentFolderPath?.length) {
+ mutate(
+ `${baseKey}/folder-documents/${currentFolderPath.join("/")}`,
+ null,
+ {
+ populateCache: (_result, docs) =>
+ updateDocNameInDocuments(docs, documentId, trimmedName),
+ revalidate: false,
+ },
+ );
+ }
+
+ mutate(`${baseKey}/folders`, null, {
+ populateCache: (_result, folders) =>
+ updateDocNameInFolderTree(folders, documentId, trimmedName),
+ revalidate: false,
+ });
+ mutate(`${baseKey}/folders?include_documents=true`, null, {
+ populateCache: (_result, items) =>
+ updateDocNameInIncludeDocumentsTree(
+ items,
+ documentId,
+ trimmedName,
+ ),
+ revalidate: false,
+ });
+ }
+
+ setOpen(false);
+ } catch {
+ toast.error("Error updating document name. Please try again.");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>Rename Document</DialogTitle>
+ <DialogDescription>Enter a new document name.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <Label htmlFor="document-name-update" className="opacity-80">
+ Document Name
+ </Label>
+ <Input
+ id="document-name-update"
+ value={name}
+ placeholder="document-name"
+ className="mb-4 mt-1 w-full"
+ onChange={(e) => setName(e.target.value)}
+ />
+ <DialogFooter>
+ <Button type="submit" className="h-9 w-full" loading={loading}>
+ Update name
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}