Skip to content

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

feat: memoize breadcrumbs

Marc Seitzabec4f6f85da
diff --git a/components/documents/breadcrumb.tsx b/components/documents/breadcrumb.tsx
new file mode 100644
index 00000000..5d56daf9
--- /dev/null
+++ b/components/documents/breadcrumb.tsx
@@ -0,0 +1,69 @@
+import React, { useMemo } from "react";
+import Link from "next/link";
+import {
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+} from "../ui/breadcrumb";
+import { useRouter } from "next/router";
+import { useFolderWithParents } from "@/lib/swr/use-folders";
+
+function BreadcrumbComponentBase({ name }: { name: string[] }) {
+ const { folders: folderNames } = useFolderWithParents({ name });
+
+ return (
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem key={"root"}>
+ <BreadcrumbLink asChild>
+ <Link href="/documents">Documents</Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {folderNames &&
+ folderNames.map((item, index: number, array) => {
+ return (
+ <React.Fragment key={index}>
+ <BreadcrumbSeparator />
+ {index === array.length - 1 ? (
+ <BreadcrumbItem>
+ <BreadcrumbPage className="capitalize">
+ {item.name}
+ </BreadcrumbPage>
+ </BreadcrumbItem>
+ ) : (
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <Link
+ href={`/documents/tree${item.path}`}
+ className="capitalize"
+ >
+ {item.name}
+ </Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ )}
+ </React.Fragment>
+ );
+ })}
+ </BreadcrumbList>
+ </Breadcrumb>
+ );
+}
+
+const BreadcrumbComponent = () => {
+ const router = useRouter();
+ const name = router.query.name as string[];
+
+ // Use useMemo to memoize the base component with the current name value.
+ // This way, BreadcrumbComponentBase is only re-rendered when name changes.
+ const MemoizedBreadcrumbComponent = useMemo(() => {
+ return <BreadcrumbComponentBase name={name} />;
+ }, [name]);
+
+ return MemoizedBreadcrumbComponent;
+};
+
+export { BreadcrumbComponent };
diff --git a/lib/swr/use-folders.ts b/lib/swr/use-folders.ts
new file mode 100644
index 00000000..efa8e75a
--- /dev/null
+++ b/lib/swr/use-folders.ts
@@ -0,0 +1,36 @@
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+import { fetcher } from "../utils";
+
+type FolderWithParents = {
+ id: string;
+ name: string;
+ parentId: string | null;
+ teamId: string;
+ _count: {
+ documents: number;
+ childFolders: number;
+ };
+ parent: FolderWithParents | null;
+};
+
+export function useFolderWithParents({ name }: { name: string[] }) {
+ const teamInfo = useTeam();
+
+ const { data: folders, error } = useSWR<{ name: string; path: string }[]>(
+ teamInfo?.currentTeam?.id &&
+ name &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/parents/${name.join("/")}`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ folders,
+ loading: !folders && !error,
+ error,
+ };
+}
diff --git a/pages/api/teams/[teamId]/folders/parents/[...name].ts b/pages/api/teams/[teamId]/folders/parents/[...name].ts
new file mode 100644
index 00000000..37ad3644
--- /dev/null
+++ b/pages/api/teams/[teamId]/folders/parents/[...name].ts
@@ -0,0 +1,74 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+import prisma from "@/lib/prisma";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/folders/:name
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId, name } = req.query as { teamId: string; name: string[] };
+
+ let folderNames = [];
+
+ try {
+ // Check if the user is part of the team
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ for (let i = 0; i < name.length; i++) {
+ const path = "/" + name.slice(0, i + 1).join("/"); // construct the materialized path
+
+ const folder = await prisma.folder.findUnique({
+ where: {
+ teamId_path: {
+ teamId: teamId,
+ path: path,
+ },
+ },
+ select: {
+ id: true,
+ parentId: true,
+ name: true,
+ },
+ });
+
+ if (!folder) {
+ return res.status(404).end("Parent Folder not found");
+ }
+
+ folderNames.push({ name: folder.name, path: path });
+ }
+
+ return res.status(200).json(folderNames);
+ } catch (error) {
+ console.error("Request error", error);
+ return res.status(500).json({ error: "Error fetching folders" });
+ }
+ } else {
+ // We only allow POST requests
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/documents/tree/[...name].tsx b/pages/documents/tree/[...name].tsx
index 67a7b1c6..22e79e23 100644
--- a/pages/documents/tree/[...name].tsx
+++ b/pages/documents/tree/[...name].tsx
@@ -1,24 +1,16 @@
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { AddFolderModal } from "@/components/documents/add-folder-modal";
+import { BreadcrumbComponent } from "@/components/documents/breadcrumb";
import DocumentCard from "@/components/documents/document-card";
import { EmptyDocuments } from "@/components/documents/empty-document";
import FolderCard from "@/components/documents/folder-card";
import AppLayout from "@/components/layouts/app";
-import {
- Breadcrumb,
- BreadcrumbItem,
- BreadcrumbLink,
- BreadcrumbList,
- BreadcrumbPage,
- BreadcrumbSeparator,
-} from "@/components/ui/breadcrumb";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { useTeam } from "@/context/team-context";
import { useFolderDocuments, useFolder } from "@/lib/swr/use-documents";
import { FileIcon, FolderIcon, FolderPlusIcon, PlusIcon } from "lucide-react";
-import Link from "next/link";
import { useRouter } from "next/router";
export default function DocumentTreePage() {
@@ -32,41 +24,7 @@ export default function DocumentTreePage() {
return (
<AppLayout>
<main className="p-4 sm:py-4 sm:px-4 sm:m-4">
- <Breadcrumb>
- <BreadcrumbList>
- <BreadcrumbItem key={"root"}>
- <BreadcrumbLink asChild>
- <Link href="/documents">Documents</Link>
- </BreadcrumbLink>
- </BreadcrumbItem>
- {name &&
- name.map((item: string, index: number, array: string[]) => {
- return (
- <>
- <BreadcrumbSeparator />
- {index === array.length - 1 ? (
- <BreadcrumbItem key={index}>
- <BreadcrumbPage className="capitalize">
- {item}
- </BreadcrumbPage>
- </BreadcrumbItem>
- ) : (
- <BreadcrumbItem key={index}>
- <BreadcrumbLink asChild>
- <Link
- href={`/documents/tree/${array.slice(0, index + 1).join("/")}`}
- className="capitalize"
- >
- {item}
- </Link>
- </BreadcrumbLink>
- </BreadcrumbItem>
- )}
- </>
- );
- })}
- </BreadcrumbList>
- </Breadcrumb>
+ <BreadcrumbComponent />
<section className="flex items-center justify-between mb-4 md:mb-8 lg:mb-12 mt-4">
<div className="space-y-1">