Skip to content

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

feat: add folder modal and move file to folder

Marc Seitz786b08449c1c
diff --git a/components/Sidebar.tsx b/components/Sidebar.tsx
index e08662fb..d4ab89e5 100644
--- a/components/Sidebar.tsx
+++ b/components/Sidebar.tsx
@@ -1,6 +1,5 @@
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
-import FolderIcon from "@/components/shared/icons/folder";
import SettingsIcon from "@/components/shared/icons/settings";
import MenuIcon from "@/components/shared/icons/menu";
import { cn } from "@/lib/utils";
@@ -15,9 +14,16 @@ import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import ProfileMenu from "./profile-menu";
import { AddDocumentModal } from "./documents/add-document-modal";
import { Button } from "./ui/button";
-import { PaletteIcon, PlusIcon } from "lucide-react";
-import { FileTree } from "./ui/nextra-filetree";
+import {
+ FolderPlusIcon,
+ PaletteIcon,
+ PlusIcon,
+ FolderIcon as FolderLucideIcon,
+ FolderOpenIcon,
+} from "lucide-react";
import SiderbarFolders from "./sidebar-folders";
+import { AddFolderModal } from "./documents/add-folder-modal";
+import { ScrollArea } from "./ui/scroll-area";
export default function Sidebar() {
return (
@@ -69,10 +75,6 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
}
}, []);
- const createFolder = () => {
- console.log("clicked");
- };
-
const userPlan = plan && plan.plan;
const navigation = [
@@ -86,8 +88,13 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
{
name: "Documents",
href: "/documents",
- icon: FolderIcon,
- current: router.pathname.includes("documents"),
+ icon: router.pathname.includes("documents")
+ ? FolderOpenIcon
+ : FolderLucideIcon,
+ current:
+ router.pathname.includes("documents") &&
+ !router.pathname.includes("tree"),
+ active: router.pathname.includes("documents"),
disabled: false,
},
{
@@ -95,6 +102,7 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
href: "/settings/branding",
icon: PaletteIcon,
current: router.pathname.includes("branding"),
+ active: false,
disabled: false,
},
{
@@ -104,95 +112,133 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
current:
router.pathname.includes("settings") &&
!router.pathname.includes("branding"),
+ active: false,
disabled: false,
},
];
return (
- <aside
- className={cn(
- "w-full h-screen lg:w-72 flex-shrink-0 flex-col justify-between gap-y-6 bg-gray-50 dark:bg-black px-4 lg:px-6 pt-4 lg:pt-6",
- className,
- )}
- >
- {/* Sidebar component, swap this element with another sidebar if you like */}
-
- <div className="flex h-16 shrink-0 items-center space-x-3">
- <p className="text-2xl font-bold tracking-tighter text-black dark:text-white flex items-center">
- Papermark{" "}
- {userPlan == "pro" ? (
- <span className="bg-background text-foreground ring-1 ring-gray-800 rounded-full px-2.5 py-1 text-xs ml-4">
- Pro
- </span>
- ) : null}
- </p>
- </div>
+ <div>
+ <aside
+ className={cn(
+ "w-full h-screen lg:w-72 flex-shrink-0 flex-col justify-between gap-y-6 bg-gray-50 dark:bg-black px-4 lg:px-6 pt-4 lg:pt-6",
+ className,
+ )}
+ >
+ {/* Sidebar component, swap this element with another sidebar if you like */}
- <SelectTeam
- currentTeam={currentTeam}
- teams={teams}
- isLoading={isLoading}
- setCurrentTeam={() => {}}
- />
+ <div className="flex h-16 shrink-0 items-center space-x-3">
+ <p className="text-2xl font-bold tracking-tighter text-black dark:text-white flex items-center">
+ Papermark{" "}
+ {userPlan == "pro" ? (
+ <span className="bg-background text-foreground ring-1 ring-gray-800 rounded-full px-2.5 py-1 text-xs ml-4">
+ Pro
+ </span>
+ ) : null}
+ </p>
+ </div>
- <AddDocumentModal>
- <Button
- className="w-full text-left group flex gap-x-3 items-center justify-start px-3"
- title="Add New Document"
- >
- <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
- <span>Add New Document</span>
- </Button>
- </AddDocumentModal>
+ <SelectTeam
+ currentTeam={currentTeam}
+ teams={teams}
+ isLoading={isLoading}
+ setCurrentTeam={() => {}}
+ />
- <section className="flex flex-1 flex-col gap-y-6">
- <div className="space-y-2">
- {navigation.map((item) => {
- return (
- <>
- <button
- key={item.name}
- onClick={() => router.push(item.href)}
- disabled={item.disabled}
- className={cn(
- item.current
- ? "bg-gray-200 dark:bg-secondary text-secondary-foreground font-semibold"
- : "text-muted-foreground hover:text-foreground hover:bg-gray-200 hover:dark:bg-muted duration-200",
- "group flex gap-x-3 items-center rounded-md px-3 py-2 text-sm leading-6 w-full disabled:hover:bg-transparent disabled:text-muted-foreground disabled:cursor-default",
- )}
- >
- <item.icon className="h-5 w-5 shrink-0" aria-hidden="true" />
- {item.name}
- {item.name === "Documents" ? (
- <span
- className="ml-auto text-xs bg-primary text-white rounded-full px-2 py-1"
- onClick={() => createFolder()}
- >
- addfolder
- </span>
- ) : null}
- </button>
- {item.name === "Documents" ? <SiderbarFolders /> : null}
- </>
- );
- })}
+ <div className="flex items-center gap-x-1">
+ <AddDocumentModal>
+ <Button
+ className="flex-1 text-left group flex gap-x-3 items-center justify-start px-3"
+ title="Add New Document"
+ >
+ <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
+ <span>Add New Document</span>
+ </Button>
+ </AddDocumentModal>
+ <AddFolderModal path={(router.query.name as string[])?.join("/")}>
+ <Button
+ size="icon"
+ variant="outline"
+ className="bg-gray-50 dark:bg-black border-gray-500 hover:bg-gray-200 hover:dark:bg-muted"
+ >
+ <FolderPlusIcon className="w-5 h-5 shrink-0" aria-hidden="true" />
+ </Button>
+ </AddFolderModal>
</div>
- </section>
- <div className="mb-4">
- {/* if user is on trial show banner,
- * if user is pro show nothing,
- * if user is free and showProBanner is true show pro banner
- */}
- {userPlan === "trial" && session ? <Banner session={session} /> : null}
- {userPlan === "pro" && null}
- {userPlan === "free" && showProBanner ? (
- <ProBanner setShowProBanner={setShowProBanner} />
- ) : null}
- <div className="w-full hidden lg:block">
- <ProfileMenu size="large" />
+ <ScrollArea className="flex-grow" showScrollbar>
+ <section className="flex flex-1 flex-col gap-y-6">
+ <div className="space-y-2">
+ {navigation.map((item) => {
+ if (item.name === "Documents") {
+ return (
+ <>
+ <button
+ key={item.name}
+ onClick={() => router.push(item.href)}
+ disabled={item.disabled}
+ className={cn(
+ item.current
+ ? "bg-gray-200 dark:bg-secondary text-secondary-foreground font-semibold"
+ : "text-muted-foreground hover:text-foreground hover:bg-gray-200 hover:dark:bg-muted duration-200",
+ router.pathname.includes("documents") &&
+ "text-foreground",
+ "group flex gap-x-2 items-center rounded-md px-3 py-2 text-sm leading-6 w-full disabled:hover:bg-transparent disabled:text-muted-foreground disabled:cursor-default",
+ )}
+ >
+ <item.icon
+ className="h-5 w-5 shrink-0"
+ aria-hidden="true"
+ />
+ {item.name}
+ </button>
+ {item.active ? <SiderbarFolders /> : null}
+ </>
+ );
+ }
+ return (
+ <button
+ key={item.name}
+ onClick={() => router.push(item.href)}
+ disabled={item.disabled}
+ className={cn(
+ item.current
+ ? "bg-gray-200 dark:bg-secondary text-secondary-foreground font-semibold"
+ : "text-muted-foreground hover:text-foreground hover:bg-gray-200 hover:dark:bg-muted duration-200",
+ router.pathname.includes("documents") &&
+ "text-foreground",
+ "group flex gap-x-2 items-center rounded-md px-3 py-2 text-sm leading-6 w-full disabled:hover:bg-transparent disabled:text-muted-foreground disabled:cursor-default",
+ )}
+ >
+ <item.icon
+ className="h-5 w-5 shrink-0"
+ aria-hidden="true"
+ />
+ {item.name}
+ </button>
+ );
+ })}
+ </div>
+ </section>
+ </ScrollArea>
+ <div className="mb-4">
+ {/* if user is on trial show banner,
+ * if user is pro show nothing,
+ * if user is free and showProBanner is true show pro banner
+ */}
+ {userPlan === "trial" && session ? (
+ <Banner session={session} />
+ ) : null}
+ {userPlan === "pro" && null}
+ {userPlan === "free" && showProBanner ? (
+ <ProBanner setShowProBanner={setShowProBanner} />
+ ) : null}
+
+ <div className="w-full hidden lg:block">
+ <ProfileMenu size="large" />
+ </div>
</div>
- </div>
- </aside>
+ </aside>
+ </div>
);
};
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsx
index c0bc9c15..c27b5cf1 100644
--- a/components/documents/add-document-modal.tsx
+++ b/components/documents/add-document-modal.tsx
@@ -43,6 +43,9 @@ export function AddDocumentModal({
const teamId = teamInfo?.currentTeam?.id as string;
+ /** current folder name */
+ const currentFolderPath = router.query.name as string[] | undefined;
+
const handleFileUpload = async (
event: FormEvent<HTMLFormElement>,
): Promise<void> => {
@@ -71,7 +74,12 @@ export function AddDocumentModal({
// create a document or new version in the database
if (!newVersion) {
// create a document in the database
- response = await createDocument({ documentData, teamId, numPages });
+ response = await createDocument({
+ documentData,
+ teamId,
+ numPages,
+ folderPathName: currentFolderPath?.join("/"),
+ });
} else {
// create a new version for existing document in the database
const documentId = router.query.id as string;
diff --git a/components/documents/add-folder-modal.tsx b/components/documents/add-folder-modal.tsx
new file mode 100644
index 00000000..3b608185
--- /dev/null
+++ b/components/documents/add-folder-modal.tsx
@@ -0,0 +1,126 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { useTeam } from "@/context/team-context";
+import { useState } from "react";
+import { toast } from "sonner";
+import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
+import { usePlan } from "@/lib/swr/use-billing";
+import { useAnalytics } from "@/lib/analytics";
+import { mutate } from "swr";
+import { Folder } from "@prisma/client";
+
+export function AddFolderModal({
+ // open,
+ // setOpen,
+ path,
+ onAddition,
+ children,
+}: {
+ // open?: boolean;
+ // setOpen?: React.Dispatch<React.SetStateAction<boolean>>;
+ path?: string;
+ onAddition?: (folderName: string) => void;
+ children?: React.ReactNode;
+}) {
+ const [folderName, setFolderName] = useState<string>("");
+ const [loading, setLoading] = useState<boolean>(false);
+ const [open, setOpen] = useState<boolean>(false);
+
+ const teamInfo = useTeam();
+ const { plan } = usePlan();
+ const analytics = useAnalytics();
+
+ const handleSubmit = async (event: any) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (folderName == "") return;
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: folderName,
+ path: path || "/",
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const { message } = await response.json();
+ setLoading(false);
+ toast.error(message);
+ return;
+ }
+
+ analytics.capture("Folder Added", { folderName: folderName });
+ toast.success("Folder added successfully! 🎉");
+
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/folders`);
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/folders/${path}`);
+ } catch (error) {
+ setLoading(false);
+ toast.error("Error adding folder. Please try again.");
+ return;
+ } finally {
+ setLoading(false);
+ setOpen(false);
+ }
+ };
+
+ // If the team is on a free plan, show the upgrade modal
+ if (plan && plan.plan === "free") {
+ if (children) {
+ return (
+ <UpgradePlanModal clickedPlan="Pro" trigger={"add_domain_overview"}>
+ {children}
+ </UpgradePlanModal>
+ );
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>Add Folder</DialogTitle>
+ <DialogDescription>You can easily add a folder.</DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <Label htmlFor="folder-name" className="opacity-80">
+ Folder Name
+ </Label>
+ <Input
+ id="folder-name"
+ placeholder="folder-123"
+ className="w-full mt-1 mb-4"
+ onChange={(e) => setFolderName(e.target.value)}
+ />
+ <DialogFooter>
+ <Button type="submit" className="w-full h-9">
+ Add new folder
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsx
index f6308155..ce377fa1 100644
--- a/components/documents/document-card.tsx
+++ b/components/documents/document-card.tsx
@@ -12,16 +12,21 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
+ DropdownMenuPortal,
DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { TrashIcon, MoreVertical } from "lucide-react";
+import { TrashIcon, MoreVertical, FileIcon } from "lucide-react";
import { mutate } from "swr";
import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";
import Check from "@/components/shared/icons/check";
import Copy from "@/components/shared/icons/copy";
import { useEffect, useRef, useState } from "react";
import { useTheme } from "next-themes";
+import { MoveToFolderModal } from "./move-folder-modal";
type DocumentsCardProps = {
document: DocumentWithLinksAndLinkCountAndViewCount;
@@ -38,6 +43,7 @@ export default function DocumentsCard({
const { isCopied, copyToClipboard } = useCopyToClipboard({});
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
const [menuOpen, setMenuOpen] = useState<boolean>(false);
+ const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
function handleCopyToClipboard(id: string) {
@@ -119,110 +125,122 @@ export default function DocumentsCard({
};
return (
- <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-200 dark:ring-gray-700 transition-all hover:ring-gray-300 hover:dark:ring-gray-500 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">
- {prismaDocument.type === "notion" ? (
- <NotionIcon className="w-8 h-8" />
- ) : (
- <Image
- src={`/_icons/${prismaDocument.type}${isLight ? "-light" : ""}.svg`}
- alt="File icon"
- width={50}
- height={50}
- />
- )}
+ <>
+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-200 dark:ring-gray-700 transition-all hover:ring-gray-300 hover:dark:ring-gray-500 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">
+ {prismaDocument.type === "notion" ? (
+ <NotionIcon className="w-8 h-8" />
+ ) : (
+ <Image
+ src={`/_icons/${prismaDocument.type}${isLight ? "-light" : ""}.svg`}
+ alt="File icon"
+ width={50}
+ height={50}
+ />
+ )}
+ </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/${prismaDocument.id}`}
+ className="truncate w-full"
+ >
+ <span>{prismaDocument.name}</span>
+ <span className="absolute inset-0" />
+ </Link>
+ </h2>
+ <div className="flex ml-2">
+ <button
+ className="group rounded-md bg-gray-200 dark:bg-gray-700 z-10 p-1 transition-all duration-75 hover:scale-105 hover:bg-emerald-100 hover:dark:bg-emerald-200 active:scale-95"
+ onClick={() =>
+ handleCopyToClipboard(prismaDocument.links[0].id)
+ }
+ title="Copy to clipboard"
+ >
+ {isCopied ? (
+ <Check className="size-3 text-muted-foreground group-hover:text-emerald-700" />
+ ) : (
+ <Copy className="size-3 text-muted-foreground group-hover:text-emerald-700" />
+ )}
+ </button>
+ </div>
+ </div>
+ <div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">
+ <p className="truncate">{timeAgo(prismaDocument.createdAt)}</p>
+ <p>•</p>
+ <p className="truncate">
+ {prismaDocument._count.links}{" "}
+ {prismaDocument._count.links === 1 ? "Link" : "Links"}
+ </p>
+ {prismaDocument._count.versions > 1 ? (
+ <>
+ <p>•</p>
+ <p className="truncate">{`${prismaDocument._count.versions} Versions`}</p>
+ </>
+ ) : null}
+ </div>
+ </div>
</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/${prismaDocument.id}`}
- className="truncate w-full"
+ <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 open={menuOpen} onOpenChange={handleMenuStateChange}>
+ <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>{prismaDocument.name}</span>
- <span className="absolute inset-0" />
- </Link>
- </h2>
- <div className="flex ml-2">
- <button
- className="group rounded-md bg-gray-200 dark:bg-gray-700 z-10 p-1 transition-all duration-75 hover:scale-105 hover:bg-emerald-100 hover:dark:bg-emerald-200 active:scale-95"
- onClick={() =>
- handleCopyToClipboard(prismaDocument.links[0].id)
- }
- title="Copy to clipboard"
+ <span className="sr-only">Open menu</span>
+ <MoreVertical className="w-4 h-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" ref={dropdownRef}>
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem onClick={() => setMoveFolderOpen(true)}>
+ Move to folder
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(event) => handleButtonClick(event, prismaDocument.id)}
+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
>
- {isCopied ? (
- <Check className="size-3 text-muted-foreground group-hover:text-emerald-700" />
+ {isFirstClick ? (
+ "Really delete?"
) : (
- <Copy className="size-3 text-muted-foreground group-hover:text-emerald-700" />
+ <>
+ <TrashIcon className="w-4 h-4 mr-2" /> Delete document
+ </>
)}
- </button>
- </div>
- </div>
- <div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">
- <p className="truncate">{timeAgo(prismaDocument.createdAt)}</p>
- <p>•</p>
- <p className="truncate">
- {prismaDocument._count.links}{" "}
- {prismaDocument._count.links === 1 ? "Link" : "Links"}
- </p>
- {prismaDocument._count.versions > 1 ? (
- <>
- <p>•</p>
- <p className="truncate">{`${prismaDocument._count.versions} Versions`}</p>
- </>
- ) : null}
- </div>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</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 open={menuOpen} onOpenChange={handleMenuStateChange}>
- <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>
+ </li>
+ {moveFolderOpen ? (
+ <MoveToFolderModal
+ open={moveFolderOpen}
+ setOpen={setMoveFolderOpen}
+ documentId={prismaDocument.id}
+ documentName={prismaDocument.name}
+ />
+ ) : null}
+ </>
);
}
diff --git a/components/documents/empty-document.tsx b/components/documents/empty-document.tsx
new file mode 100644
index 00000000..57014715
--- /dev/null
+++ b/components/documents/empty-document.tsx
@@ -0,0 +1,29 @@
+import { FilePlusIcon, PlusIcon } from "lucide-react";
+import { Button } from "../ui/button";
+import { AddDocumentModal } from "./add-document-modal";
+
+export function EmptyDocuments() {
+ return (
+ <div className="text-center">
+ <FilePlusIcon
+ className="mx-auto h-12 w-12 text-muted-foreground"
+ strokeWidth={1}
+ />
+ <h3 className="mt-2 text-sm font-medium text-foreground">No documents</h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Get started by uploading a new document.
+ </p>
+ <div className="mt-6">
+ <AddDocumentModal>
+ <Button
+ className="w-full flex gap-x-3 items-center justify-center px-3"
+ title="Add New Document"
+ >
+ <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
+ <span>Add Document</span>
+ </Button>
+ </AddDocumentModal>
+ </div>
+ </div>
+ );
+}
diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsx
index 6f89f53a..351c551b 100644
--- a/components/documents/folder-card.tsx
+++ b/components/documents/folder-card.tsx
@@ -22,10 +22,10 @@ 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">
+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 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" />
+ <FolderIcon className="w-8 h-8 " strokeWidth={1} />
</div>
<div className="flex-col">
diff --git a/components/documents/move-folder-modal.tsx b/components/documents/move-folder-modal.tsx
new file mode 100644
index 00000000..9e9cabb0
--- /dev/null
+++ b/components/documents/move-folder-modal.tsx
@@ -0,0 +1,137 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { useTeam } from "@/context/team-context";
+import { useState } from "react";
+import { toast } from "sonner";
+import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
+import { usePlan } from "@/lib/swr/use-billing";
+import { useAnalytics } from "@/lib/analytics";
+import { mutate } from "swr";
+import { Folder } from "@prisma/client";
+import { useFolders } from "@/lib/swr/use-documents";
+import { string } from "zod";
+import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
+import { as } from "@upstash/redis/zmscore-5d82e632";
+import SidebarFolderTree, {
+ SidebarFolderTreeSelection,
+} from "../sidebar-folders";
+import { useRouter } from "next/router";
+
+export function MoveToFolderModal({
+ open,
+ setOpen,
+ folderPath,
+ documentId,
+ documentName,
+ onAddition,
+ children,
+}: {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ folderPath?: string;
+ documentId?: string;
+ documentName?: string;
+ onAddition?: (folderName: string) => void;
+ children?: React.ReactNode;
+}) {
+ const router = useRouter();
+ const [folderName, setFolderName] = useState<string>("");
+ const [folderId, setFolderId] = useState<string>("");
+ const [loading, setLoading] = useState<boolean>(false);
+ const { folders } = useFolders();
+
+ const teamInfo = useTeam();
+ const { plan } = usePlan();
+ const analytics = useAnalytics();
+
+ const currentPath = router.query.name
+ ? (router.query.name as string[]).join("/")
+ : "";
+
+ const handleSubmit = async (event: any) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (folderId === "") return;
+
+ setLoading(true);
+ try {
+ const response = await fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/documents/${documentId}`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ folderId: folderId,
+ currentPathName: "/" + currentPath,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const { message } = await response.json();
+ setLoading(false);
+ toast.error(message);
+ return;
+ }
+
+ const { newPath, oldPath } = (await response.json()) as {
+ newPath: string;
+ oldPath: string;
+ };
+
+ toast.success("Document moved successfully!");
+
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/folders`);
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/folders${oldPath}`);
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/folders${newPath}`).then(
+ () => {
+ router.push(`/documents/tree${newPath}`);
+ },
+ );
+ } catch (error) {
+ console.error("Error moving document", error);
+ toast.error("Failed to move document. Try again.");
+ } finally {
+ setLoading(false);
+ setOpen(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>
+ Move <span className="font-bold">{documentName}</span>
+ </DialogTitle>
+ <DialogDescription>Move your document to a folder.</DialogDescription>
+ </DialogHeader>
+ <form>
+ <SidebarFolderTreeSelection
+ selectedFolderId={folderId}
+ setFolderId={setFolderId}
+ />
+
+ <DialogFooter>
+ <Button onClick={handleSubmit} className="w-full h-9">
+ Move to folder
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/sidebar-folders.tsx b/components/sidebar-folders.tsx
index d2900963..61c786fb 100644
--- a/components/sidebar-folders.tsx
+++ b/components/sidebar-folders.tsx
@@ -2,6 +2,7 @@ import { useRouter } from "next/router";
import { FileTree } from "./ui/nextra-filetree";
import { FolderWithDocuments, useFolders } from "@/lib/swr/use-documents";
import { memo, useMemo } from "react";
+import { set } from "ts-pattern/dist/patterns";
// Helper function to build nested folder structure
const buildNestedFolderStructure = (folders: FolderWithDocuments[]) => {
@@ -65,6 +66,52 @@ const FolderComponent = memo(({ folder }: { folder: FolderWithDocuments }) => {
);
});
+const FolderComponentSelection = memo(
+ ({
+ folder,
+ selectedFolderId,
+ setFolderId,
+ }: {
+ folder: FolderWithDocuments;
+ selectedFolderId: string;
+ setFolderId: React.Dispatch<React.SetStateAction<string>>;
+ }) => {
+ // const router = useRouter();
+
+ // Recursively render child folders if they exist
+ const childFolders = useMemo(
+ () =>
+ folder.childFolders.map((childFolder) => (
+ <FolderComponentSelection
+ key={childFolder.id}
+ folder={childFolder}
+ selectedFolderId={selectedFolderId}
+ setFolderId={setFolderId}
+ />
+ )),
+ [folder.childFolders, selectedFolderId, setFolderId],
+ );
+
+ return (
+ <div
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setFolderId(folder.id);
+ }}
+ >
+ <FileTree.Folder
+ name={folder.name}
+ key={folder.id}
+ active={folder.id === selectedFolderId}
+ >
+ {childFolders}
+ </FileTree.Folder>
+ </div>
+ );
+ },
+);
+
const SidebarFolders = ({ folders }: { folders: FolderWithDocuments[] }) => {
const nestedFolders = useMemo(() => {
if (folders) {
@@ -89,3 +136,35 @@ export default function SidebarFolderTree() {
return <SidebarFolders folders={folders} />;
}
+
+export function SidebarFolderTreeSelection({
+ selectedFolderId,
+ setFolderId,
+}: {
+ selectedFolderId: string;
+ setFolderId: React.Dispatch<React.SetStateAction<string>>;
+}) {
+ const { folders, error } = useFolders();
+
+ if (!folders || error) return null;
+
+ const nestedFolders = useMemo(() => {
+ if (folders) {
+ return buildNestedFolderStructure(folders);
+ }
+ return [];
+ }, [folders, selectedFolderId, setFolderId]);
+
+ return (
+ <FileTree>
+ {nestedFolders.map((folder) => (
+ <FolderComponentSelection
+ key={folder.id}
+ folder={folder}
+ selectedFolderId={selectedFolderId}
+ setFolderId={setFolderId}
+ />
+ ))}
+ </FileTree>
+ );
+}
diff --git a/components/ui/nextra-filetree.tsx b/components/ui/nextra-filetree.tsx
index 3178f995..d23765b9 100644
--- a/components/ui/nextra-filetree.tsx
+++ b/components/ui/nextra-filetree.tsx
@@ -1,3 +1,9 @@
+/**
+ * This component is based on the nextra's filetree component from @shuding
+ * https://github.com/shuding/nextra/blob/main/packages/nextra/src/components/file-tree.tsx
+ *
+ */
+
import { cn } from "@/lib/utils";
import { createContext, memo, useCallback, useContext, useState } from "react";
import type { ReactElement, ReactNode } from "react";
@@ -36,7 +42,7 @@ interface FileProps {
function Tree({ children }: { children: ReactNode }): ReactElement {
return (
- <div className={cn("nextra-filetree w-full select-none text-sm")}>
+ <div className={cn("nextra-filetree w-full select-none text-sm !mt-0")}>
<div className="block rounded-lg">{children}</div>
</div>
);
@@ -80,9 +86,9 @@ const Folder = memo<FolderProps>(
onClick={toggle}
title={name}
className={cn(
- "inline-flex cursor-pointer items-center py-1 w-full",
+ "inline-flex cursor-pointer items-center w-full",
"text-foreground hover:bg-gray-200 hover:dark:bg-muted duration-100 rounded-md",
- "px-3",
+ "px-3 py-1.5 leading-6",
active && "bg-gray-200 dark:bg-muted font-semibold",
)}
>
@@ -108,17 +114,16 @@ const Folder = memo<FolderProps>(
/>
</svg> */}
{isFolderOpen ? (
- <FolderOpenIcon
- className="h-4 w-4 shrink-0 fill-muted-foreground"
- aria-hidden="true"
- />
+ <FolderOpenIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
) : (
- <FolderIcon
- className="h-4 w-4 shrink-0 fill-muted-foreground"
- aria-hidden="true"
- />
+ <FolderIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
)}
- <span className="ml-2">{label ?? name}</span>
+ <span
+ className="ml-2 w-fit truncate"
+ title={(label ?? name) as string}
+ >
+ {label ?? name}
+ </span>
</button>
{isFolderOpen && (
<ul>
@@ -141,12 +146,12 @@ const File = memo<FileProps>(({ label, name, active, onToggle }) => {
className={cn(
"flex list-none",
"text-foreground hover:bg-gray-200 hover:dark:bg-muted duration-100 rounded-md",
- "px-3",
+ "px-3 py-1.5 leading-6",
active && "bg-gray-200 dark:bg-muted font-semibold",
)}
>
<span
- className="inline-flex cursor-default items-center py-1"
+ className="inline-flex cursor-default items-center ml-5"
onClick={toggle}
>
<Ident />
@@ -160,8 +165,10 @@ const File = memo<FileProps>(({ label, name, active, onToggle }) => {
d="M9 12h6m-6 4h6m2 5H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5.586a1 1 0 0 1 .707.293l5.414 5.414a1 1 0 0 1 .293.707V19a2 2 0 0 1-2 2Z"
/>
</svg> */}
- <FileIcon className="h-4 w-4 shrink-0" aria-hidden="true" />
- <span className="ml-2">{label ?? name}</span>
+ <FileIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
+ <span className="ml-2 w-fit truncate" title={(label ?? name) as string}>
+ {label ?? name}
+ </span>
</span>
</li>
);
diff --git a/components/ui/scroll-area.tsx b/components/ui/scroll-area.tsx
index 4689816c..de123fc9 100644
--- a/components/ui/scroll-area.tsx
+++ b/components/ui/scroll-area.tsx
@@ -1,12 +1,14 @@
-import * as React from "react"
-import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
+import * as React from "react";
+import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
->(({ className, children, ...props }, ref) => (
+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
+ showScrollbar?: boolean;
+ }
+>(({ className, children, showScrollbar, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
@@ -15,11 +17,12 @@ const ScrollArea = React.forwardRef<
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
- <ScrollBar className="hidden" />
+
<ScrollAreaPrimitive.Corner />
+ <ScrollBar className={showScrollbar ? "" : "hidden"} />
</ScrollAreaPrimitive.Root>
-))
-ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
+));
+ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
@@ -34,13 +37,13 @@ const ScrollBar = React.forwardRef<
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
- className
+ className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
-))
-ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
+));
+ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
-export { ScrollArea, ScrollBar }
+export { ScrollArea, ScrollBar };
diff --git a/lib/documents/create-document.ts b/lib/documents/create-document.ts
index cb59d5b6..019bec9e 100644
--- a/lib/documents/create-document.ts
+++ b/lib/documents/create-document.ts
@@ -10,10 +10,12 @@ export const createDocument = async ({
documentData,
teamId,
numPages,
+ folderPathName,
}: {
documentData: DocumentData;
teamId: string;
numPages?: number;
+ folderPathName?: string;
}) => {
// create a document in the database with the blob url
const response = await fetch(`/api/teams/${teamId}/documents`, {
@@ -26,6 +28,7 @@ export const createDocument = async ({
url: documentData.key,
storageType: documentData.storageType,
numPages: numPages,
+ folderPathName: folderPathName,
}),
});
diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.ts
index 905af3bd..e262dadb 100644
--- a/lib/swr/use-documents.ts
+++ b/lib/swr/use-documents.ts
@@ -105,3 +105,23 @@ export function useFolders() {
error,
};
}
+
+export function useRootFolders() {
+ const teamInfo = useTeam();
+
+ const { data: folders, error } = useSWR<FolderWithCount[]>(
+ teamInfo?.currentTeam?.id &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders?root=true`,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ folders,
+ loading: !folders && !error,
+ error,
+ };
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/index.ts b/pages/api/teams/[teamId]/documents/[id]/index.ts
index 323afe53..4c21af95 100644
--- a/pages/api/teams/[teamId]/documents/[id]/index.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/index.ts
@@ -48,6 +48,54 @@ export default async function handle(
} catch (error) {
errorhandler(error, res);
}
+ } else if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/document/:id
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+ const userId = (session.user as CustomUser).id;
+ const { teamId, id: docId } = req.query as { teamId: string; id: string };
+ const { folderId, currentPathName } = req.body as {
+ folderId: string;
+ currentPathName: string;
+ };
+
+ const document = await prisma.document.update({
+ where: {
+ id: docId,
+ teamId: teamId,
+ team: {
+ users: {
+ some: {
+ role: "ADMIN",
+ userId: userId,
+ },
+ },
+ },
+ },
+ data: {
+ folderId: folderId,
+ },
+ select: {
+ folder: {
+ select: {
+ path: true,
+ },
+ },
+ },
+ });
+
+ if (!document) {
+ return res.status(404).end("Document not found");
+ }
+
+ return res.status(200).json({
+ message: "Document moved successfully",
+ newPath: document.folder?.path,
+ oldPath: currentPathName,
+ });
} else if (req.method === "DELETE") {
// DELETE /api/teams/:teamId/document/:id
const session = await getServerSession(req, res, authOptions);
@@ -110,8 +158,8 @@ export default async function handle(
errorhandler(error, res);
}
} else {
- // We only allow GET and DELETE requests
- res.setHeader("Allow", ["GET", "DELETE"]);
+ // We only allow GET, PUT and DELETE requests
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.ts
index 10ecbb6b..e04f2b1a 100644
--- a/pages/api/teams/[teamId]/documents/index.ts
+++ b/pages/api/teams/[teamId]/documents/index.ts
@@ -31,6 +31,9 @@ export default async function handle(
teamId,
userId,
options: {
+ where: {
+ folderId: null,
+ },
orderBy: {
createdAt: "desc",
},
@@ -68,15 +71,17 @@ export default async function handle(
const {
name,
url: fileUrl,
+ storageType,
numPages,
type: fileType,
- storageType,
+ folderPathName,
} = req.body as {
name: string;
url: string;
- numPages: number;
- type?: string;
storageType: DocumentStorageType;
+ numPages?: number;
+ type?: string;
+ folderPathName?: string;
};
try {
@@ -101,6 +106,18 @@ export default async function handle(
}
}
+ const folder = await prisma.folder.findUnique({
+ where: {
+ teamId_path: {
+ teamId,
+ path: "/" + folderPathName,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
// Save data to the database
const document = await prisma.document.create({
data: {
@@ -124,6 +141,7 @@ export default async function handle(
versionNumber: 1,
},
},
+ folderId: folder?.id ? folder.id : null,
},
include: {
links: true,
diff --git a/pages/api/teams/[teamId]/folders/index.ts b/pages/api/teams/[teamId]/folders/index.ts
index 81ebfd28..1820a24b 100644
--- a/pages/api/teams/[teamId]/folders/index.ts
+++ b/pages/api/teams/[teamId]/folders/index.ts
@@ -3,6 +3,7 @@ import { getServerSession } from "next-auth/next";
import prisma from "@/lib/prisma";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { CustomUser } from "@/lib/types";
+import slugify from "@sindresorhus/slugify";
export default async function handle(
req: NextApiRequest,
@@ -16,7 +17,7 @@ export default async function handle(
}
const userId = (session.user as CustomUser).id;
- const { teamId } = req.query as { teamId: string };
+ const { teamId, root } = req.query as { teamId: string; root?: string };
try {
// Check if the user is part of the team
@@ -35,6 +36,23 @@ export default async function handle(
return res.status(401).end("Unauthorized");
}
+ /** if root is present then only get root folders */
+ if (root === "true") {
+ const folders = await prisma.folder.findMany({
+ where: {
+ teamId: teamId,
+ parentId: null,
+ },
+ include: {
+ _count: {
+ select: { documents: true, childFolders: true },
+ },
+ },
+ });
+
+ return res.status(200).json(folders);
+ }
+
const folders = await prisma.folder.findMany({
where: {
teamId: teamId,
@@ -66,6 +84,70 @@ export default async function handle(
console.error("Request error", error);
return res.status(500).json({ error: "Error fetching folders" });
}
+ } else if (req.method === "POST") {
+ // POST /api/teams/:teamId/folders
+ 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 { name, path } = req.body as { name: string; path: string };
+
+ 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,
+ name: true,
+ path: true,
+ },
+ });
+
+ const folder = await prisma.folder.create({
+ data: {
+ name: name,
+ path: "/" + path + "/" + slugify(name),
+ parentId: parentFolder?.id ?? null,
+ teamId: teamId,
+ },
+ });
+
+ const folderWithDocs = {
+ ...folder,
+ documents: [],
+ childFolders: [],
+ };
+
+ res.status(201).json(folderWithDocs);
+ } catch (error) {
+ console.error("Request error", error);
+ res.status(500).json({ error: "Error creating folder" });
+ }
} else {
// We only allow POST requests
res.setHeader("Allow", ["GET", "POST"]);
diff --git a/pages/documents/index.tsx b/pages/documents/index.tsx
index bd9aa83d..2b08d351 100644
--- a/pages/documents/index.tsx
+++ b/pages/documents/index.tsx
@@ -1,21 +1,24 @@
-import useDocuments from "@/lib/swr/use-documents";
+import useDocuments, { useRootFolders } from "@/lib/swr/use-documents";
import { useTeam } from "@/context/team-context";
import DocumentCard from "@/components/documents/document-card";
import { Skeleton } from "@/components/ui/skeleton";
-import { PlusIcon } from "lucide-react";
+import { FileIcon, FolderIcon, PlusIcon } from "lucide-react";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { Separator } from "@/components/ui/separator";
import AppLayout from "@/components/layouts/app";
import { Button } from "@/components/ui/button";
import Folder from "@/components/shared/icons/folder";
+import FolderCard from "@/components/documents/folder-card";
+import { EmptyDocuments } from "@/components/documents/empty-document";
export default function Documents() {
const { documents } = useDocuments();
+ const { folders } = useRootFolders();
const teamInfo = useTeam();
return (
<AppLayout>
- <div className="p-4 sm:py-4 sm:px-10 sm:m-4">
+ <main className="p-4 sm:py-4 sm:px-4 sm:m-4">
<section className="flex items-center justify-between mb-4 md:mb-8 lg:mb-12">
<div className="space-y-1">
<h2 className="text-xl sm:text-2xl text-foreground font-semibold tracking-tight">
@@ -40,88 +43,91 @@ export default function Documents() {
</div>
</section>
- {documents && documents.length > 0 ? (
- <p className="text-sm text-gray-400 mt-8 sm:mt-5 mb-2 flex items-center">
- <Folder className="w-[16px] h-[16px] mr-1" /> Total documents{" "}
- {documents.length}
- </p>
- ) : null}
+ <section className="flex items-center gap-x-2 mb-2">
+ {folders && folders.length > 0 ? (
+ <p className="text-sm text-gray-400 flex items-center gap-x-1">
+ <FolderIcon className="w-4 h-4" />
+ <span>{folders.length} folders</span>
+ </p>
+ ) : null}
+ {documents && documents.length > 0 ? (
+ <p className="text-sm text-gray-400 flex items-center gap-x-1">
+ <FileIcon className="w-4 h-4" />
+ <span>{documents.length} documents</span>
+ </p>
+ ) : null}
+ </section>
<Separator className="mb-5 bg-gray-200 dark:bg-gray-800" />
- {documents && documents.length === 0 && (
- <div className="flex items-center justify-center h-96">
- <EmptyDocuments />
- </div>
- )}
+ <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}
+ />
+ );
+ })
+ : 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>
- </div>
- </AppLayout>
- );
-}
+ {/* 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>
-export function EmptyDocuments() {
- return (
- <div className="text-center">
- <svg
- className="mx-auto h-12 w-12 text-muted-foreground"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- aria-hidden="true"
- >
- <path
- vectorEffect="non-scaling-stroke"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"
- />
- </svg>
- <h3 className="mt-2 text-sm font-medium text-foreground">No documents</h3>
- <p className="mt-1 text-sm text-muted-foreground">
- Get started by uploading a new document.
- </p>
- <div className="mt-6">
- <AddDocumentModal>
- <Button
- className="w-full text-left group flex gap-x-3 items-center justify-start px-3"
- title="Add New Document"
- >
- <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
- <span>Add Document</span>
- </Button>
- </AddDocumentModal>
- </div>
- </div>
+ {documents && documents.length === 0 && (
+ <div className="flex items-center justify-center">
+ <EmptyDocuments />
+ </div>
+ )}
+ </div>
+ </main>
+ </AppLayout>
);
}
diff --git a/pages/documents/tree/[...name].tsx b/pages/documents/tree/[...name].tsx
index 79f95651..56d24beb 100644
--- a/pages/documents/tree/[...name].tsx
+++ b/pages/documents/tree/[...name].tsx
@@ -1,5 +1,6 @@
import { AddDocumentModal } from "@/components/documents/add-document-modal";
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 {
@@ -15,7 +16,7 @@ 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 { FileIcon, FolderIcon, PlusIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/router";
@@ -90,67 +91,90 @@ export default function DocumentTreePage() {
</div>
</section>
+ <section className="flex items-center gap-x-2 mb-2">
+ {folders && folders.length > 0 ? (
+ <p className="text-sm text-gray-400 flex items-center gap-x-1">
+ <FolderIcon className="w-4 h-4" />
+ <span>{folders.length} folders</span>
+ </p>
+ ) : null}
+ {documents && documents.length > 0 ? (
+ <p className="text-sm text-gray-400 flex items-center gap-x-1">
+ <FileIcon className="w-4 h-4" />
+ <span>{documents.length} documents</span>
+ </p>
+ ) : null}
+ </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>
+ <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}
+ />
+ );
+ })
+ : 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>
+ {/* 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>
+
+ {documents && documents.length === 0 && (
+ <div className="flex items-center justify-center h-96">
+ <EmptyDocuments />
+ </div>
+ )}
+ </div>
</main>
</AppLayout>
);