Skip to content

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

feat: update document name

Marc Seitz85db473d6d4a
diff --git a/pages/api/documents/[id]/update-name.ts b/pages/api/documents/[id]/update-name.ts
new file mode 100644
index 00000000..fa165cab
--- /dev/null
+++ b/pages/api/documents/[id]/update-name.ts
@@ -0,0 +1,56 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { authOptions } from "../../auth/[...nextauth]";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method === "POST") {
+ // GET /api/documents/:id/update-name
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { id } = req.query as { id: string };
+
+ try {
+ const document = await prisma.document.findUnique({
+ where: {
+ id: id,
+ },
+ select: {
+ ownerId: true,
+ }
+ });
+
+ // Check if the user is the owner of the document
+ if (document?.ownerId !== (session.user as CustomUser).id) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ await prisma.document.update({
+ where: {
+ id: id,
+ },
+ data: {
+ name: req.body.name,
+ }
+ });
+
+ res.status(200).json({ message: "Document name updated!"});
+ } catch (error) {
+ return res.status(500).json({
+ message: "Internal Server Error",
+ error: (error as Error).message,
+ });
+ }
+ } else {
+ // We only allow GET and POST requests
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/documents/[id].tsx b/pages/documents/[id].tsx
index 36b907b2..9eea885f 100644
--- a/pages/documents/[id].tsx
+++ b/pages/documents/[id].tsx
@@ -8,15 +8,68 @@ import LinkSheet from "@/components/links/link-sheet";
import Image from "next/image";
import LinksTable from "@/components/links/links-table";
import VisitorsTable from "@/components/visitors/visitors-table";
-import { useState } from "react";
+import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import LoadingSpinner from "@/components/ui/loading-spinner";
+import { toast } from "sonner";
export default function DocumentPage() {
const { document, primaryVersion, error } = useDocument();
const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);
+ const [isEditingName, setIsEditingName] = useState<boolean>(false);
+ const nameRef = useRef<HTMLHeadingElement>(null);
+ const enterPressedRef = useRef<boolean>(false);
+
+ const handleNameSubmit = async () => {
+ if (enterPressedRef.current) {
+ enterPressedRef.current = false;
+ return;
+ }
+ if (nameRef.current && isEditingName) {
+ const newName = nameRef.current.innerText;
+
+ if (newName !== document!.name) {
+ const response = await fetch(
+ `/api/documents/${document!.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);
+ }
+ }
+ setIsEditingName(false);
+ }
+ };
+
+ const preventEnterAndSubmit = (
+ event: React.KeyboardEvent<HTMLHeadingElement>
+ ) => {
+ 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 (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
}
@@ -39,9 +92,23 @@ export default function DocumentPage() {
className=""
/>
</div>
- <h2 className="leading-7 text-2xl text-foreground font-semibold tracking-tight">
- {document.name}
- </h2>
+ <div className="flex flex-col">
+ <h2
+ className="leading-7 text-2xl text-foreground font-semibold tracking-tight hover:cursor-text"
+ ref={nameRef}
+ contentEditable={true}
+ onFocus={() => setIsEditingName(true)}
+ onBlur={handleNameSubmit}
+ onKeyDown={preventEnterAndSubmit}
+ title="Click to edit"
+ dangerouslySetInnerHTML={{ __html: document.name }}
+ />
+ {isEditingName && (
+ <p className="text-sm text-muted-foreground mt-1">
+ {`You are editing the document name. Press <Enter> to save.`}
+ </p>
+ )}
+ </div>
</div>
</div>
<Button onClick={() => setIsLinkSheetOpen(true)}>