Skip to content

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

feat: add folder card, breadcrumbs and data for folders and files

Marc Seitz7bb0a068b559
diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsx
new file mode 100644
index 00000000..6f89f53a
--- /dev/null
+++ b/components/documents/folder-card.tsx
@@ -0,0 +1,106 @@
+import { timeAgo } from "@/lib/utils";
+import Link from "next/link";
+import { TeamContextType } from "@/context/team-context";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { MoreVertical, FolderIcon } from "lucide-react";
+import { useRef } from "react";
+import { FolderWithCount } from "@/lib/swr/use-documents";
+
+type FolderCardProps = {
+ folder: FolderWithCount;
+ teamInfo: TeamContextType | null;
+};
+export default function FolderCard({ folder, teamInfo }: FolderCardProps) {
+ const dropdownRef = useRef<HTMLDivElement | null>(null);
+
+ return (
+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-2 ring-gray-400 dark:ring-gray-500 transition-all hover:ring-gray-500 hover:dark:ring-gray-400 hover:bg-secondary sm:p-4 flex justify-between items-center">
+ <div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">
+ <div className="w-8 mx-0.5 sm:mx-1 text-center flex justify-center items-center">
+ <FolderIcon className="w-8 h-8" />
+ </div>
+
+ <div className="flex-col">
+ <div className="flex items-center">
+ <h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">
+ <Link
+ href={`/documents/tree${folder.path}`}
+ className="truncate w-full"
+ >
+ <span>{folder.name}</span>
+ <span className="absolute inset-0" />
+ </Link>
+ </h2>
+ </div>
+ <div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">
+ <p className="truncate">{timeAgo(folder.createdAt)}</p>
+ <p>•</p>
+ <p className="truncate">
+ {folder._count.documents}{" "}
+ {folder._count.documents === 1 ? "Document" : "Documents"}
+ </p>
+ <p>•</p>
+ <p className="truncate">
+ {folder._count.childFolders}{" "}
+ {folder._count.childFolders === 1 ? "Folder" : "Folders"}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-row space-x-2">
+ {/* <Link
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ href={`/documents/${prismaDocument.id}`}
+ className="flex items-center z-10 space-x-1 rounded-md bg-gray-200 dark:bg-gray-700 px-1.5 sm:px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"
+ >
+ <BarChart className="h-3 sm:h-4 w-3 sm:w-4 text-muted-foreground" />
+ <p className="whitespace-nowrap text-xs sm:text-sm text-muted-foreground">
+ {nFormatter(prismaDocument._count.views)}
+ <span className="ml-1 hidden sm:inline-block">views</span>
+ </p>
+ </Link> */}
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ // size="icon"
+ variant="outline"
+ className="h-8 lg:h-9 w-8 lg:w-9 p-0 z-10 bg-transparent border-gray-200 dark:border-gray-700 hover:bg-gray-200 hover:dark:bg-gray-700"
+ >
+ <span className="sr-only">Open menu</span>
+ <MoreVertical className="w-4 h-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" ref={dropdownRef}>
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+
+ {/* <DropdownMenuItem
+ onClick={(event) => handleButtonClick(event, prismaDocument.id)}
+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
+ >
+ {isFirstClick ? (
+ "Really delete?"
+ ) : (
+ <>
+ <TrashIcon className="w-4 h-4 mr-2" /> Delete document
+ </>
+ )}
+ </DropdownMenuItem> */}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </li>
+ );
+}
diff --git a/components/ui/breadcrumb.tsx b/components/ui/breadcrumb.tsx
new file mode 100644
index 00000000..71a5c325
--- /dev/null
+++ b/components/ui/breadcrumb.tsx
@@ -0,0 +1,115 @@
+import * as React from "react"
+import { Slot } from "@radix-ui/react-slot"
+import { ChevronRight, MoreHorizontal } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+const Breadcrumb = React.forwardRef<
+ HTMLElement,
+ React.ComponentPropsWithoutRef<"nav"> & {
+ separator?: React.ReactNode
+ }
+>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
+Breadcrumb.displayName = "Breadcrumb"
+
+const BreadcrumbList = React.forwardRef<
+ HTMLOListElement,
+ React.ComponentPropsWithoutRef<"ol">
+>(({ className, ...props }, ref) => (
+ <ol
+ ref={ref}
+ className={cn(
+ "flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
+ className
+ )}
+ {...props}
+ />
+))
+BreadcrumbList.displayName = "BreadcrumbList"
+
+const BreadcrumbItem = React.forwardRef<
+ HTMLLIElement,
+ React.ComponentPropsWithoutRef<"li">
+>(({ className, ...props }, ref) => (
+ <li
+ ref={ref}
+ className={cn("inline-flex items-center gap-1.5", className)}
+ {...props}
+ />
+))
+BreadcrumbItem.displayName = "BreadcrumbItem"
+
+const BreadcrumbLink = React.forwardRef<
+ HTMLAnchorElement,
+ React.ComponentPropsWithoutRef<"a"> & {
+ asChild?: boolean
+ }
+>(({ asChild, className, ...props }, ref) => {
+ const Comp = asChild ? Slot : "a"
+
+ return (
+ <Comp
+ ref={ref}
+ className={cn("transition-colors hover:text-foreground", className)}
+ {...props}
+ />
+ )
+})
+BreadcrumbLink.displayName = "BreadcrumbLink"
+
+const BreadcrumbPage = React.forwardRef<
+ HTMLSpanElement,
+ React.ComponentPropsWithoutRef<"span">
+>(({ className, ...props }, ref) => (
+ <span
+ ref={ref}
+ role="link"
+ aria-disabled="true"
+ aria-current="page"
+ className={cn("font-normal text-foreground", className)}
+ {...props}
+ />
+))
+BreadcrumbPage.displayName = "BreadcrumbPage"
+
+const BreadcrumbSeparator = ({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) => (
+ <li
+ role="presentation"
+ aria-hidden="true"
+ className={cn("[&>svg]:size-3.5", className)}
+ {...props}
+ >
+ {children ?? <ChevronRight />}
+ </li>
+)
+BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
+
+const BreadcrumbEllipsis = ({
+ className,
+ ...props
+}: React.ComponentProps<"span">) => (
+ <span
+ role="presentation"
+ aria-hidden="true"
+ className={cn("flex h-9 w-9 items-center justify-center", className)}
+ {...props}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ <span className="sr-only">More</span>
+ </span>
+)
+BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
+
+export {
+ Breadcrumb,
+ BreadcrumbList,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+ BreadcrumbEllipsis,
+}
diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.ts
index e6c05f64..905af3bd 100644
--- a/lib/swr/use-documents.ts
+++ b/lib/swr/use-documents.ts
@@ -2,6 +2,7 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";
import { useTeam } from "@/context/team-context";
+import { Folder } from "@prisma/client";
export default function useDocuments() {
const teamInfo = useTeam();
@@ -25,6 +26,57 @@ export default function useDocuments() {
};
}
+export function useFolderDocuments({ name }: { name: string[] }) {
+ const teamInfo = useTeam();
+
+ const { data: documents, error } = useSWR<
+ DocumentWithLinksAndLinkCountAndViewCount[]
+ >(
+ teamInfo?.currentTeam?.id &&
+ name &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${name.join("/")}`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ documents,
+ loading: !documents && !error,
+ error,
+ };
+}
+
+export type FolderWithCount = Folder & {
+ _count: {
+ documents: number;
+ childFolders: number;
+ };
+};
+
+export function useFolder({ name }: { name: string[] }) {
+ const teamInfo = useTeam();
+
+ const { data: folders, error } = useSWR<FolderWithCount[]>(
+ teamInfo?.currentTeam?.id &&
+ name &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/${name.join("/")}`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ folders,
+ loading: !folders && !error,
+ error,
+ };
+}
+
export type FolderWithDocuments = Folder & {
childFolders: FolderWithDocuments[];
documents: {
diff --git a/pages/api/teams/[teamId]/folders/[...name].ts b/pages/api/teams/[teamId]/folders/[...name].ts
new file mode 100644
index 00000000..4d368fe1
--- /dev/null
+++ b/pages/api/teams/[teamId]/folders/[...name].ts
@@ -0,0 +1,79 @@
+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[] };
+
+ const path = "/" + name.join("/"); // construct the materialized path
+
+ 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");
+ }
+
+ const parentFolder = await prisma.folder.findUnique({
+ where: {
+ teamId_path: {
+ teamId: teamId,
+ path: path,
+ },
+ },
+ select: {
+ id: true,
+ parentId: true,
+ },
+ });
+
+ if (!parentFolder) {
+ return res.status(404).end("Parent Folder not found");
+ }
+
+ const folders = await prisma.folder.findMany({
+ where: {
+ teamId: teamId,
+ parentId: parentFolder.id,
+ },
+ include: {
+ _count: {
+ select: { documents: true, childFolders: true },
+ },
+ },
+ });
+
+ return res.status(200).json(folders);
+ } 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/api/teams/[teamId]/folders/documents/[...name].ts b/pages/api/teams/[teamId]/folders/documents/[...name].ts
new file mode 100644
index 00000000..2c03b7df
--- /dev/null
+++ b/pages/api/teams/[teamId]/folders/documents/[...name].ts
@@ -0,0 +1,79 @@
+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/documents/: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[] };
+
+ const path = "/" + name.join("/"); // construct the materialized path
+
+ 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");
+ }
+
+ const folder = await prisma.folder.findUnique({
+ where: {
+ teamId_path: {
+ teamId: teamId,
+ path: path,
+ },
+ },
+ select: {
+ id: true,
+ parentId: true,
+ },
+ });
+
+ if (!folder) {
+ return res.status(404).end("Folder not found");
+ }
+
+ const documents = await prisma.document.findMany({
+ where: {
+ teamId: teamId,
+ folderId: folder.id,
+ },
+ include: {
+ _count: {
+ select: { links: true, views: true, versions: true },
+ },
+ },
+ });
+
+ return res.status(200).json(documents);
+ } catch (error) {
+ console.error("Request error", error);
+ return res.status(500).json({ error: "Error fetching folders" });
+ }
+ } else {
+ // We only allow GET requests
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/documents/tree/[...name].tsx b/pages/documents/tree/[...name].tsx
new file mode 100644
index 00000000..79f95651
--- /dev/null
+++ b/pages/documents/tree/[...name].tsx
@@ -0,0 +1,157 @@
+import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import DocumentCard from "@/components/documents/document-card";
+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 { PlusIcon } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+export default function DocumentTreePage() {
+ const router = useRouter();
+ const { name } = router.query as { name: string[] };
+
+ const { folders } = useFolder({ name });
+ const { documents } = useFolderDocuments({ name });
+ const teamInfo = useTeam();
+
+ 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>
+
+ <section className="flex items-center justify-between mb-4 md:mb-8 lg:mb-12 mt-4">
+ <div className="space-y-1">
+ <h2 className="text-xl sm:text-2xl text-foreground font-semibold tracking-tight">
+ All Documents
+ </h2>
+ <p className="text-xs sm:text-sm text-muted-foreground">
+ Manage all your documents in one place.
+ </p>
+ </div>
+ <div className="flex items-center justify-between gap-4">
+ <AddDocumentModal>
+ <Button
+ size="icon"
+ className="fixed bottom-6 right-5 z-30 lg:hidden sm:bottom-0 sm:right-0 sm:relative w-10 sm:w-44 h-10 sm:h-10"
+ >
+ <span className="hidden sm:block">Add New Document</span>
+ <span className="block sm:hidden">
+ <PlusIcon className="w-6 h-6" />
+ </span>
+ </Button>
+ </AddDocumentModal>
+ </div>
+ </section>
+
+ <Separator className="mb-5 bg-gray-200 dark:bg-gray-800" />
+
+ {/* Folders list */}
+ <ul role="list" className="space-y-4">
+ {folders && folders.length > 0
+ ? folders.map((folder) => {
+ return (
+ <FolderCard
+ key={folder.id}
+ folder={folder}
+ teamInfo={teamInfo}
+ />
+ );
+ })
+ : Array.from({ length: 3 }).map((_, i) => (
+ <li
+ key={i}
+ className="relative w-full py-5 px-4 border rounded-lg flex items-center space-x-3 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="h-5 w-20 absolute top-[50%] transform -translate-y-[50%] right-5"
+ />
+ </li>
+ ))}
+ </ul>
+
+ {/* Documents list */}
+ <ul role="list" className="space-y-4">
+ {documents
+ ? documents.map((document) => {
+ return (
+ <DocumentCard
+ key={document.id}
+ document={document}
+ teamInfo={teamInfo}
+ />
+ );
+ })
+ : Array.from({ length: 3 }).map((_, i) => (
+ <li
+ key={i}
+ className="relative w-full py-5 px-4 border rounded-lg flex items-center space-x-3 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="h-5 w-20 absolute top-[50%] transform -translate-y-[50%] right-5"
+ />
+ </li>
+ ))}
+ </ul>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/pages/documents/tree/[name].tsx b/pages/documents/tree/[name].tsx
deleted file mode 100644
index de173b74..00000000
--- a/pages/documents/tree/[name].tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import AppLayout from "@/components/layouts/app";
-
-export default function DocumentTreePage() {
- return (
- <AppLayout>
- <main className="relative overflow-hidden mx-2 sm:mx-3 md:mx-5 lg:mx-7 xl:mx-10 mt-4 md:mt-5 lg:mt-8 mb-10 space-y-8 px-1">
- <h1>DocumentPage</h1>
- </main>
- </AppLayout>
- );
-}