Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
add upload document and create link function
Marc Seitz076e363ee33a
diff --git a/components/Notification.tsx b/components/Notification.tsxnew file mode 100644index 00000000..8b66d8d4--- /dev/null+++ b/components/Notification.tsx@@ -0,0 +1,59 @@+import { CheckCircleIcon } from "@heroicons/react/24/outline";+import { XMarkIcon } from "@heroicons/react/20/solid";+import { Transition } from "@headlessui/react";+import { Fragment } from "react";++export default function Notification({+ t,+ closeToast,+}: {+ t: any;+ closeToast: () => void;+}) {+ return (+ <div className="flex w-full flex-col items-center space-y-4 sm:items-end">+ {/* Notification panel, dynamically insert this into the live region when it needs to be displayed */}+ <Transition+ show={t.visible}+ as={Fragment}+ enter="transform ease-out duration-300 transition"+ enterFrom="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"+ enterTo="translate-y-0 opacity-100 sm:translate-x-0"+ leave="transition ease-in duration-100"+ leaveFrom="opacity-100"+ leaveTo="opacity-0"+ >+ <div className="pointer-events-auto w-full max-w-sm overflow-hidden rounded-lg bg-gray-900 shadow-lg ring-1 ring-black ring-opacity-5">+ <div className="p-4">+ <div className="flex items-start">+ <div className="flex-shrink-0">+ <CheckCircleIcon+ className="h-6 w-6 text-green-400"+ aria-hidden="true"+ />+ </div>+ <div className="ml-3 w-0 flex-1 pt-0.5">+ <p className="text-sm font-medium text-gray-300">+ Link copied to clipboard!+ </p>+ <p className="mt-1 text-sm text-gray-500">+ Document uploaded and link copied to clipboard.+ </p>+ </div>+ <div className="ml-4 flex flex-shrink-0">+ <button+ type="button"+ className="inline-flex rounded-md bg-gray-900 text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"+ onClick={closeToast}+ >+ <span className="sr-only">Close</span>+ <XMarkIcon className="h-5 w-5" aria-hidden="true" />+ </button>+ </div>+ </div>+ </div>+ </div>+ </Transition>+ </div>+ );+}diff --git a/components/Sidebar.tsx b/components/Sidebar.tsxnew file mode 100644index 00000000..eb35c3f3--- /dev/null+++ b/components/Sidebar.tsx@@ -0,0 +1,266 @@+import { Fragment, useState } from "react";+import { Menu, Dialog, Transition } from "@headlessui/react";+import { signIn, signOut, useSession } from "next-auth/react";+import {+ Bars3Icon,+ ChevronDownIcon,+ PlusIcon,+} from "@heroicons/react/20/solid";+import { FolderIcon, XMarkIcon } from "@heroicons/react/24/outline";+import Link from "next/link";+import { classNames } from "@/lib/utils";+import { useRouter } from "next/router";++export default function Sidebar({ children }: { children: React.ReactNode }) {+ const { data: session } = useSession();+ const [sidebarOpen, setSidebarOpen] = useState(false);+ const router = useRouter();++ const navigation = [+ {+ name: "Documents",+ href: "/documents",+ icon: FolderIcon,+ current: router.pathname.includes("documents"),+ },+ ];++ return (+ <>+ <Transition.Root show={sidebarOpen} as={Fragment}>+ <Dialog+ as="div"+ className="relative z-50 xl:hidden"+ onClose={setSidebarOpen}+ >+ <Transition.Child+ as={Fragment}+ enter="transition-opacity ease-linear duration-300"+ enterFrom="opacity-0"+ enterTo="opacity-100"+ leave="transition-opacity ease-linear duration-300"+ leaveFrom="opacity-100"+ leaveTo="opacity-0"+ >+ <div className="fixed inset-0 bg-gray-900/80" />+ </Transition.Child>++ <div className="fixed inset-0 flex">+ <Transition.Child+ as={Fragment}+ enter="transition ease-in-out duration-300 transform"+ enterFrom="-translate-x-full"+ enterTo="translate-x-0"+ leave="transition ease-in-out duration-300 transform"+ leaveFrom="translate-x-0"+ leaveTo="-translate-x-full"+ >+ <Dialog.Panel className="relative mr-16 flex w-full max-w-xs flex-1">+ <Transition.Child+ as={Fragment}+ enter="ease-in-out duration-300"+ enterFrom="opacity-0"+ enterTo="opacity-100"+ leave="ease-in-out duration-300"+ leaveFrom="opacity-100"+ leaveTo="opacity-0"+ >+ <div className="absolute left-full top-0 flex w-16 justify-center pt-5">+ <button+ type="button"+ className="-m-2.5 p-2.5"+ onClick={() => setSidebarOpen(false)}+ >+ <span className="sr-only">Close sidebar</span>+ <XMarkIcon+ className="h-6 w-6 text-white"+ aria-hidden="true"+ />+ </button>+ </div>+ </Transition.Child>+ {/* Sidebar component, swap this element with another sidebar if you like */}+ <div className="flex grow flex-col gap-y-5 overflow-y-auto bg-gray-900 px-6 ring-1 ring-white/10">+ <div className="flex h-16 shrink-0 items-center">+ <p className="text-2xl font-bold tracking-tighter text-white">+ Papermark+ </p>+ </div>+ <nav className="flex flex-1 flex-col">+ <ul role="list" className="flex flex-1 flex-col gap-y-7">+ <li>+ <ul role="list" className="-mx-2 space-y-1">+ {navigation.map((item) => (+ <li key={item.name}>+ <a+ href={item.href}+ className={classNames(+ item.current+ ? "bg-gray-800 text-white"+ : "text-gray-400 hover:text-white hover:bg-gray-800",+ "group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold"+ )}+ >+ <item.icon+ className="h-6 w-6 shrink-0"+ aria-hidden="true"+ />+ {item.name}+ </a>+ </li>+ ))}+ </ul>+ </li>+ </ul>+ </nav>+ </div>+ </Dialog.Panel>+ </Transition.Child>+ </div>+ </Dialog>+ </Transition.Root>++ {/* Static sidebar for desktop */}+ <div className="hidden xl:fixed xl:inset-y-0 xl:z-50 xl:flex xl:w-72 xl:flex-col">+ {/* Sidebar component, swap this element with another sidebar if you like */}+ <div className="flex grow flex-col gap-y-5 overflow-y-auto bg-black/10 px-6 ring-1 ring-white/5">+ <div className="flex h-16 shrink-0 items-center">+ <p className="text-2xl font-bold tracking-tighter text-white">+ Papermark+ </p>+ </div>+ <nav className="flex flex-1 flex-col">+ <ul role="list" className="flex flex-1 flex-col gap-y-7">+ <li>+ <ul role="list" className="-mx-2 space-y-1">+ {navigation.map((item) => (+ <li key={item.name}>+ <a+ href={item.href}+ className={classNames(+ item.current+ ? "bg-gray-800 text-white"+ : "text-gray-400 hover:text-white hover:bg-gray-800",+ "group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold"+ )}+ >+ <item.icon+ className="h-6 w-6 shrink-0"+ aria-hidden="true"+ />+ {item.name}+ </a>+ </li>+ ))}+ </ul>+ </li>+ </ul>+ </nav>+ </div>+ </div>++ <div className="xl:pl-72">+ {/* Navbar */}+ <div className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-black/10 bg-black/10 px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8">+ <button+ type="button"+ className="-m-2.5 p-2.5 text-gray-700 lg:hidden"+ onClick={() => setSidebarOpen(true)}+ >+ <span className="sr-only">Open sidebar</span>+ <Bars3Icon className="h-6 w-6" aria-hidden="true" />+ </button>++ {/* Separator */}+ <div+ className="h-6 w-px bg-gray-900/10 lg:hidden"+ aria-hidden="true"+ />++ <div className="flex flex-1 gap-x-4 self-stretch items-center lg:gap-x-6 justify-end">+ <div className="flex-shrink-0">+ <Link+ href="/documents/new"+ type="button"+ className="relative inline-flex items-center gap-x-1.5 rounded-md bg-indigo-500 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500"+ >+ <PlusIcon className="-ml-0.5 h-5 w-5" aria-hidden="true" />+ New Link+ </Link>+ </div>+ <div className="flex items-center gap-x-4 lg:gap-x-6">+ {/* Profile dropdown */}+ <Menu as="div" className="relative">+ <Menu.Button className="-m-1.5 flex items-center p-1.5">+ <span className="sr-only">Open user menu</span>+ <img+ className="h-8 w-8 rounded-full bg-gray-50"+ src={session?.user?.image || ""}+ alt=""+ />+ <span className="flex items-center">+ <span+ className="ml-4 text-sm font-semibold leading-6 text-white"+ aria-hidden="true"+ >+ {session?.user?.name}+ </span>+ <ChevronDownIcon+ className="ml-2 h-5 w-5 text-gray-400"+ aria-hidden="true"+ />+ </span>+ </Menu.Button>+ <Transition+ as={Fragment}+ enter="transition ease-out duration-100"+ enterFrom="transform opacity-0 scale-95"+ enterTo="transform opacity-100 scale-100"+ leave="transition ease-in duration-75"+ leaveFrom="transform opacity-100 scale-100"+ leaveTo="transform opacity-0 scale-95"+ >+ <Menu.Items className="absolute right-0 z-10 mt-2.5 w-fit origin-top-right rounded-md bg-white py-2 shadow-lg ring-1 ring-gray-900/5 focus:outline-none">+ {session && (+ <Menu.Item>+ <p className="block px-3 py-1 text-sm leading-6 text-gray-500 bg-gray-50">+ {session?.user?.email}+ </p>+ </Menu.Item>+ )}+ {session && (+ <Menu.Item>+ <Link+ onClick={() =>+ signOut({+ callbackUrl: `${window.location.origin}`,+ })+ }+ className="block px-3 py-1 text-sm leading-6 text-gray-900 bg-gray-50"+ href={""}+ >+ Sign Out+ </Link>+ </Menu.Item>+ )}+ {!session && (+ <Menu.Item>+ <a+ onClick={() => signIn()}+ className="block px-3 py-1 text-sm leading-6 text-gray-900 bg-gray-50"+ >+ Sign In+ </a>+ </Menu.Item>+ )}+ </Menu.Items>+ </Transition>+ </Menu>+ </div>+ </div>+ </div>+ {children}+ </div>+ </>+ );+}diff --git a/package.json b/package.jsonindex 78638c28..d2ec8eeb 100644--- a/package.json+++ b/package.json@@ -9,11 +9,14 @@"lint": "next lint"},"dependencies": {+ "@headlessui/react": "^1.7.14",+ "@heroicons/react": "^2.0.18","@next-auth/prisma-adapter": "^1.0.6","@prisma/client": "^4.14.1","@types/node": "20.2.5","@types/react": "18.2.7","@types/react-dom": "18.2.4",+ "@vercel/blob": "^0.8.3","autoprefixer": "10.4.14","eslint": "8.41.0","eslint-config-next": "13.4.4",@@ -22,10 +25,12 @@"postcss": "8.4.23","react": "18.2.0","react-dom": "18.2.0",+ "react-hot-toast": "^2.4.1","tailwindcss": "3.3.2","typescript": "5.0.4"},"devDependencies": {+ "@tailwindcss/forms": "^0.5.3","prisma": "^4.14.1"}}diff --git a/pages/_app.tsx b/pages/_app.tsxindex 6d7a178a..21ec04b1 100644--- a/pages/_app.tsx+++ b/pages/_app.tsx@@ -3,6 +3,7 @@ import type { AppProps } from "next/app";import { Inter } from "next/font/google";import type { Session } from "next-auth";import { SessionProvider } from "next-auth/react";+import { Toaster } from "react-hot-toast";const inter = Inter({ subsets: ["latin"] });@@ -13,6 +14,7 @@ export default function App({return (<SessionProvider session={session}><main className={inter.className}>+ <Toaster position="top-right" reverseOrder={false} /><Component {...pageProps} /></main></SessionProvider>diff --git a/pages/api/documents.ts b/pages/api/documents.tsnew file mode 100644index 00000000..70986f21--- /dev/null+++ b/pages/api/documents.ts@@ -0,0 +1,58 @@+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+) {+ // We only allow POST requests+ if (req.method !== "POST") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).json({ error: "Unauthorized" });+ return;+ }++ // Assuming data is an object with `name` and `description` properties+ const { name, url, description } = req.body;++ console.log("name", name);+ console.log("url", url);++ // You could perform some validation here++ try {+ // Save data to the database+ const document = await prisma.document.create({+ data: {+ name: name,+ description: description,+ file: url,+ ownerId: (session.user as CustomUser).id,+ },+ });++ const link = await prisma.link.create({+ data: {+ documentId: document.id,+ // url: nanoid(),+ },+ });++ console.log("link", link);++ res.status(201).json({ document, linkId: link.id });+ } catch (error) {+ res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+}diff --git a/pages/api/file/upload.ts b/pages/api/file/upload.tsnew file mode 100644index 00000000..1cc0b45f--- /dev/null+++ b/pages/api/file/upload.ts@@ -0,0 +1,22 @@+import * as vercelBlob from "@vercel/blob";+import { NextResponse, NextRequest } from "next/server";++export const config = {+ runtime: "edge",+};++export default async function upload(request: NextRequest) {+ const form = await request.formData();+ const file = form.get("file") as File;++ if (!file) {+ return NextResponse.json(+ { error: "File name or file not submitted" },+ { status: 400 }+ );+ }++ const blob = await vercelBlob.put(file.name, file, { access: "public" });++ return NextResponse.json(blob);+}diff --git a/pages/documents/new.tsx b/pages/documents/new.tsxnew file mode 100644index 00000000..f5d8e2a5--- /dev/null+++ b/pages/documents/new.tsx@@ -0,0 +1,208 @@+import { PhotoIcon, UserCircleIcon } from "@heroicons/react/20/solid";+import Sidebar from "@/components/Sidebar";+import { useState, useMemo } from "react";+import { useRouter } from "next/router";+import type { PutBlobResult } from "@vercel/blob";+import toast from "react-hot-toast";+import Notification from "@/components/Notification";++export default function Form() {+ const router = useRouter();+ const [uploading, setUploading] = useState(false);+ const [currentFile, setCurrentFile] = useState<File | null>(null);++ const imageBlobUrl = useMemo(+ () => (currentFile ? URL.createObjectURL(currentFile) : ""),+ [currentFile]+ );++ const handleSubmit = async (event) => {+ event.preventDefault();++ const data = new FormData(event.target);++ try {+ setUploading(true);++ // upload the file to the blob storage+ const blobResponse = await fetch("/api/file/upload", {+ method: "POST",+ body: data,+ });++ if (!blobResponse.ok) {+ throw new Error(`HTTP error! status: ${blobResponse.status}`);+ }++ // get the blob url from the response+ const blob = (await blobResponse.json()) as PutBlobResult;++ console.log("Blob uploaded successfully!", blob);++ // create a document in the database with the blob url+ const response = await fetch("/api/documents", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: blob.pathname,+ description: data.get("description"),+ url: blob.url,+ }),+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const { document, linkId } = await response.json();++ console.log("Document created successfully!", document);++ navigator.clipboard.writeText(+ `${process.env.NEXT_PUBLIC_BASE_URL}/view/${linkId}`+ );++ toast.custom((t) => (+ <Notification t={t} closeToast={() => toast.dismiss(t.id)} />+ ));+ } catch (error) {+ console.error("An error occurred while uploading the file: ", error);+ } finally {+ setUploading(false);+ }+ };++ return (+ <>+ <div>+ <Sidebar>+ {/* Main content */}+ <main className="mx-10 mt-8">+ <form encType="multipart/form-data" onSubmit={handleSubmit}>+ <div className="space-y-12">+ <div className="border-b border-white/10 pb-12">+ <h2 className="text-base font-semibold leading-7 text-white">+ Share a document+ </h2>+ <p className="mt-1 text-sm leading-6 text-gray-400">+ This information will be displayed publicly so be careful+ what you share.+ </p>++ <div className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">+ <div className="col-span-full">+ <label+ htmlFor="cover-photo"+ className="block text-sm font-medium leading-6 text-white"+ >+ Upload a document+ </label>+ <div className="mt-2 flex justify-center rounded-lg border border-dashed border-white/25 px-6 py-10">+ <div className="text-center">+ {currentFile && (+ <div>+ <img+ className="h-12 w-12 mx-auto"+ src={imageBlobUrl}+ alt="File preview"+ />+ </div>+ )}+ <PhotoIcon+ className="mx-auto h-12 w-12 text-gray-500"+ aria-hidden="true"+ />+ <div className="mt-4 flex text-sm leading-6 text-gray-400">+ <label+ htmlFor="file-upload"+ className="relative cursor-pointer rounded-md bg-gray-900 font-semibold text-white focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 focus-within:ring-offset-gray-900 hover:text-indigo-500"+ >+ <span>Upload a file</span>+ <input+ id="file-upload"+ name="file"+ type="file"+ className="sr-only"+ onChange={(e) =>+ setCurrentFile(e.target.files?.[0] || null)+ }+ />+ </label>+ {/* <p className="pl-1">or drag and drop</p> */}+ </div>+ <p className="text-xs leading-5 text-gray-400">+ PDF, DOCX, PPTX and more up to 4MB+ </p>+ </div>+ </div>+ </div>++ {/* <div className="sm:col-span-4">+ <label+ htmlFor="linkname"+ className="block text-sm font-medium leading-6 text-white"+ >+ Pick a Link+ </label>+ <div className="mt-2">+ <div className="flex rounded-md bg-white/5 ring-1 ring-inset ring-white/10 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-500">+ <span className="flex select-none items-center pl-3 text-gray-500 sm:text-sm">+ papermark.io/view/+ </span>+ <input+ type="text"+ name="name"+ id="linkname"+ autoComplete="linkname"+ className="flex-1 border-0 bg-transparent py-1.5 pl-1 text-white focus:ring-0 sm:text-sm sm:leading-6"+ placeholder="acme-presentation"+ />+ </div>+ </div>+ </div> */}++ <div className="col-span-full">+ <label+ htmlFor="about"+ className="block text-sm font-medium leading-6 text-white"+ >+ Description+ </label>+ <div className="mt-2">+ <textarea+ id="about"+ name="description"+ rows={1}+ className="block w-full rounded-md border-0 bg-white/5 py-1.5 text-white shadow-sm ring-1 ring-inset ring-white/10 focus:ring-2 focus:ring-inset focus:ring-indigo-500 sm:text-sm sm:leading-6"+ defaultValue={""}+ placeholder="Acme Presentation"+ />+ </div>+ <p className="mt-3 text-sm leading-6 text-gray-400">+ This is description will help you find your document+ later.+ </p>+ </div>+ </div>+ </div>+ </div>++ <div className="mt-6 flex items-center justify-center w-full">+ <button+ type="submit"+ className="rounded-md bg-indigo-500 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500"+ disabled={uploading}+ >+ {uploading ? "Uploading..." : "Create a link"}+ </button>+ </div>+ </form>+ </main>+ {/* End: Main content */}+ </Sidebar>+ </div>+ </>+ );+}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 9cfda328..146ffebe 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -44,6 +44,7 @@ model User {image String?accounts Account[]sessions Session[]+ documents Document[]}model VerificationToken {@@ -53,3 +54,25 @@ model VerificationToken {@@unique([identifier, token])}++model Document {+ id String @id @default(cuid())+ name String+ description String?+ file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)+ type String? // This should be a reference to the file type (pdf, docx, etc.)+ owner User @relation(fields: [ownerId], references: [id])+ ownerId String // This field holds the foreign key.+ createdAt DateTime @default(now())+ links Link[]+}++model Link {+ id String @id @default(cuid())+ document Document @relation(fields: [documentId], references: [id])+ documentId String+ url String? @unique+ expiresAt DateTime? // Optional expiration date+ password String? // Optional password for link protection+ allowedEmails String[] // Array of emails allowed to view the document+}diff --git a/tailwind.config.js b/tailwind.config.jsindex 8c4d1b21..3f5c0d16 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -1,18 +1,18 @@/** @type {import('tailwindcss').Config} */module.exports = {content: [- './pages/**/*.{js,ts,jsx,tsx,mdx}',- './components/**/*.{js,ts,jsx,tsx,mdx}',- './app/**/*.{js,ts,jsx,tsx,mdx}',+ "./pages/**/*.{js,ts,jsx,tsx,mdx}",+ "./components/**/*.{js,ts,jsx,tsx,mdx}",+ "./app/**/*.{js,ts,jsx,tsx,mdx}",],theme: {extend: {backgroundImage: {- 'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',- 'gradient-conic':- 'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',+ "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",+ "gradient-conic":+ "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",},},},- plugins: [],-}+ plugins: [require("@tailwindcss/forms")],+};