Skip to content

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

feat: add special route for deck

Marc Seitz06dcdd86ab2a
diff --git a/components/welcome/special-upload.tsx b/components/welcome/special-upload.tsx
new file mode 100644
index 00000000..ad31505b
--- /dev/null
+++ b/components/welcome/special-upload.tsx
@@ -0,0 +1,338 @@
+import { useRouter } from "next/router";
+import { motion } from "framer-motion";
+import { useEffect, useState } from "react";
+import DocumentUpload from "@/components/document-upload";
+import { toast } from "sonner";
+import Skeleton from "../Skeleton";
+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";
+import {
+ convertDataUrlToFile,
+ copyToClipboard,
+ uploadImage,
+} from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { usePlausible } from "next-plausible";
+import { useTeam } from "@/context/team-context";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { LinkOptions } from "../links/link-sheet/link-options";
+import { DEFAULT_LINK_PROPS, DEFAULT_LINK_TYPE } from "../links/link-sheet";
+import { useAnalytics } from "@/lib/analytics";
+import { putFile } from "@/lib/files/put-file";
+import { DocumentData, createDocument } from "@/lib/documents/create-document";
+import Cookies from "js-cookie";
+
+export default function DeckGeneratorUpload() {
+ const router = useRouter();
+ const plausible = usePlausible();
+ const analytics = useAnalytics();
+ const [uploading, setUploading] = useState<boolean>(false);
+ const [isLoading, setIsLoading] = useState<boolean>(false);
+ const [currentFile, setCurrentFile] = useState<File | null>(null);
+ const [currentBlob, setCurrentBlob] = useState<boolean>(false);
+ const [currentLinkId, setCurrentLinkId] = useState<string | null>(null);
+ const [currentDocId, setCurrentDocId] = useState<string | null>(null);
+ const [linkData, setLinkData] =
+ useState<DEFAULT_LINK_TYPE>(DEFAULT_LINK_PROPS);
+ const teamInfo = useTeam();
+
+ const teamId = teamInfo?.currentTeam?.id as string;
+
+ // When the user enters this page, it will fetch the reportUrl from the cookies with js-cookie, then it will use putFile to upload the file to the server
+
+ useEffect(() => {
+ const reportUrl = Cookies.get("savedReport");
+ if (reportUrl) {
+ const blob = fetch(reportUrl)
+ .then((response) => response.blob())
+ .then((blob) => {
+ const file = new File([blob], "report.pdf", {
+ type: "application/pdf",
+ });
+ setCurrentFile(file);
+ })
+ .catch((error) => console.error("Error fetching report:", error));
+
+ // Cookies.remove("reportUrl");
+ }
+ }, []);
+
+ const handleBrowserUpload = async (event: any) => {
+ event.preventDefault();
+
+ // Check if the file is chosen
+ if (!currentFile) {
+ toast.error("Please select a file to upload.");
+ return; // prevent form from submitting
+ }
+
+ try {
+ setUploading(true);
+
+ const { type, data, numPages } = await putFile({
+ file: currentFile,
+ teamId,
+ });
+
+ setCurrentFile(null);
+ setCurrentBlob(true);
+
+ const documentData: DocumentData = {
+ name: currentFile.name,
+ key: data!,
+ storageType: type!,
+ };
+ // create a document in the database
+ const response = await createDocument({ documentData, teamId, numPages });
+
+ if (response) {
+ const document = await response.json();
+ const linkId = document.links[0].id;
+
+ // track the event
+ plausible("documentUploaded");
+ analytics.capture("Document Added", {
+ documentId: document.id,
+ name: document.name,
+ numPages: document.numPages,
+ path: router.asPath,
+ type: "pdf",
+ teamId: teamInfo?.currentTeam?.id,
+ });
+ analytics.capture("Link Added", {
+ linkId: document.links[0].id,
+ documentId: document.id,
+ customDomain: null,
+ teamId: teamInfo?.currentTeam?.id,
+ });
+
+ setTimeout(() => {
+ setCurrentDocId(document.id);
+ setCurrentLinkId(linkId);
+ setUploading(false);
+ }, 2000);
+ }
+ } catch (error) {
+ console.error("An error occurred while uploading the file: ", error);
+ setCurrentFile(null);
+ setUploading(false);
+ }
+ };
+
+ const handleSubmit = async (event: any) => {
+ event.preventDefault();
+
+ setIsLoading(true);
+
+ // Upload the image if it's a data URL
+ let blobUrl: string | null =
+ linkData.metaImage && linkData.metaImage.startsWith("data:")
+ ? null
+ : linkData.metaImage;
+ if (linkData.metaImage && linkData.metaImage.startsWith("data:")) {
+ // Convert the data URL to a blob
+ const blob = convertDataUrlToFile({ dataUrl: linkData.metaImage });
+ // Upload the blob to vercel storage
+ blobUrl = await uploadImage(blob);
+ setLinkData({ ...linkData, metaImage: blobUrl });
+ }
+
+ const response = await fetch(`/api/links/${currentLinkId}`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...linkData,
+ metaImage: blobUrl,
+ targetId: currentDocId,
+ linkType: "DOCUMENT_LINK",
+ }),
+ });
+
+ if (!response.ok) {
+ // handle error with toast message
+ const { error } = await response.json();
+ toast.error(error);
+ setIsLoading(false);
+ return;
+ }
+
+ copyToClipboard(
+ `${process.env.NEXT_PUBLIC_BASE_URL}/view/${currentLinkId}`,
+ "Link copied to clipboard. Redirecting to document page...",
+ );
+
+ router.push(`/documents/${currentDocId}`);
+ setIsLoading(false);
+ };
+
+ return (
+ <>
+ {!currentBlob && (
+ <motion.div
+ className="z-10 flex flex-col space-y-10 text-center"
+ variants={{
+ hidden: { opacity: 0, scale: 0.95 },
+ show: {
+ opacity: 1,
+ scale: 1,
+ transition: {
+ staggerChildren: 0.2,
+ },
+ },
+ }}
+ initial="hidden"
+ animate="show"
+ exit="hidden"
+ transition={{ duration: 0.3, type: "spring" }}
+ >
+ <motion.div
+ variants={STAGGER_CHILD_VARIANTS}
+ className="flex flex-col items-center space-y-10 text-center"
+ >
+ <h1 className="font-display text-3xl font-semibold text-foreground transition-colors sm:text-4xl">
+ {`Upload your ${router.query.type ? router.query.type : "document"}`}
+ </h1>
+ </motion.div>
+ <motion.div variants={STAGGER_CHILD_VARIANTS}>
+ <main className="mt-8">
+ <form
+ encType="multipart/form-data"
+ onSubmit={handleBrowserUpload}
+ className="flex flex-col"
+ >
+ <div className="space-y-12">
+ <div className="pb-6">
+ <div className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
+ <DocumentUpload
+ currentFile={currentFile}
+ setCurrentFile={setCurrentFile}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-center">
+ <Button
+ type="submit"
+ className="w-full"
+ loading={uploading}
+ disabled={!currentFile}
+ >
+ {uploading ? "Uploading..." : "Upload Document"}
+ </Button>
+ </div>
+ </form>
+
+ <div className="text-xs text-muted-foreground">
+ <span>Use our</span>{" "}
+ <Button
+ variant="link"
+ className="text-xs font-normal px-0 underline text-muted-foreground hover:text-gray-700"
+ onClick={async () => {
+ const response = await fetch(
+ "/_example/papermark-example-document.pdf",
+ );
+ const blob = await response.blob();
+ const file = new File(
+ [blob],
+ "papermark-example-document.pdf",
+ {
+ type: "application/pdf",
+ },
+ );
+ setCurrentFile(file);
+ }}
+ >
+ sample document
+ </Button>
+ </div>
+ </main>
+ </motion.div>
+ </motion.div>
+ )}
+
+ {currentBlob && (
+ <motion.div
+ className="z-10 flex flex-col space-y-10 text-center"
+ variants={{
+ hidden: { opacity: 0, scale: 0.95 },
+ show: {
+ opacity: 1,
+ scale: 1,
+ transition: {
+ staggerChildren: 0.2,
+ },
+ },
+ }}
+ initial="hidden"
+ animate="show"
+ exit="hidden"
+ transition={{ duration: 0.3, type: "spring" }}
+ >
+ <motion.div
+ variants={STAGGER_CHILD_VARIANTS}
+ className="flex flex-col items-center space-y-10 text-center"
+ >
+ <h1 className="font-display text-3xl font-semibold text-foreground transition-colors sm:text-4xl">
+ Share your unique link
+ </h1>
+ </motion.div>
+
+ <motion.div variants={STAGGER_CHILD_VARIANTS}>
+ {!currentLinkId && (
+ <main className="min-h-[300px]">
+ <div className="flex flex-col justify-center">
+ <div className="flex py-8">
+ <div className="flex w-full focus-within:z-10">
+ <Skeleton className="h-6 w-full" />
+ </div>
+ </div>
+ </div>
+ </main>
+ )}
+ {currentLinkId && currentDocId && (
+ <main className="min-h-[300px]">
+ <div className="flex flex-col justify-center">
+ <div className="relative">
+ <div className="flex py-8">
+ <div className="flex w-full max-w-xs sm:max-w-lg focus-within:z-10">
+ <p className="block w-full md:min-w-[500px] rounded-md px-4 text-left border-0 py-1.5 text-secondary-foreground bg-secondary leading-6 overflow-y-scroll">
+ {`${process.env.NEXT_PUBLIC_BASE_URL}/view/${currentLinkId}`}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div className="w-full max-w-xs sm:max-w-lg pb-8">
+ <Accordion type="single" collapsible>
+ <AccordionItem value="item-1" className="border-none">
+ <AccordionTrigger className="py-0 rounded-lg space-x-2">
+ <span className="text-sm font-medium leading-6 text-foreground">
+ Configure Link Options
+ </span>
+ </AccordionTrigger>
+ <AccordionContent className="first:pt-5">
+ <LinkOptions data={linkData} setData={setLinkData} />
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ </div>
+ <div className="flex items-center justify-center mb-4">
+ <Button onClick={handleSubmit} loading={isLoading}>
+ Share Document
+ </Button>
+ </div>
+ </div>
+ </main>
+ )}
+ </motion.div>
+ </motion.div>
+ )}
+ </>
+ );
+}
diff --git a/lib/middleware/app.ts b/lib/middleware/app.ts
index 43072978..2e460e81 100644
--- a/lib/middleware/app.ts
+++ b/lib/middleware/app.ts
@@ -2,7 +2,8 @@ import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export default async function AppMiddleware(req: NextRequest) {
- const path = req.nextUrl.pathname;
+ const url = req.nextUrl;
+ const path = url.pathname;
const token = (await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
@@ -13,28 +14,31 @@ export default async function AppMiddleware(req: NextRequest) {
};
};
- // if there's no token and the path isn't /login, redirect to /login
+ // UNAUTHENTICATED if there's no token and the path isn't /login, redirect to /login
if (!token?.email && path !== "/login") {
- return NextResponse.redirect(
- new URL(
- `/login${path !== "/" ? `?next=${encodeURIComponent(path)}` : ""}`,
- req.url,
- ),
- );
+ const loginUrl = new URL(`/login`, req.url);
+ // Append "next" parameter only if not navigating to the root
+ if (path !== "/") {
+ loginUrl.searchParams.set("next", encodeURIComponent(path));
+ }
+ return NextResponse.redirect(loginUrl);
+ }
- // if there's a token
- } else if (token?.email) {
- // if the user was created in the last 10 seconds, redirect to "/welcome"
- if (
- token?.user?.createdAt &&
- new Date(token?.user?.createdAt).getTime() > Date.now() - 10000 &&
- path !== "/welcome"
- ) {
- return NextResponse.redirect(new URL("/welcome", req.url));
+ // AUTHENTICATED if the user was created in the last 10 seconds, redirect to "/welcome"
+ if (
+ token?.email &&
+ token?.user?.createdAt &&
+ new Date(token?.user?.createdAt).getTime() > Date.now() - 10000 &&
+ path !== "/welcome"
+ ) {
+ return NextResponse.redirect(new URL("/welcome", req.url));
+ }
- // if the path is /login, redirect to "/documents"
- } else if (path === "/login") {
- return NextResponse.redirect(new URL("/documents", req.url));
- }
+ // AUTHENTICATED if the path is /login, redirect to "/documents"
+ if (token?.email && path === "/login") {
+ const nextPath = url.searchParams.get("next") || "/documents"; // Default redirection to "/documents" if no next parameter
+ return NextResponse.redirect(
+ new URL(decodeURIComponent(nextPath), req.url),
+ );
}
}
diff --git a/pages/documents/new.tsx b/pages/documents/new.tsx
new file mode 100644
index 00000000..2df47fbf
--- /dev/null
+++ b/pages/documents/new.tsx
@@ -0,0 +1,54 @@
+import { useRouter } from "next/router";
+import Intro from "@/components/welcome/intro";
+import Next from "@/components/welcome/next";
+import Upload from "@/components/welcome/upload";
+import { ArrowLeft as ArrowLeftIcon } from "lucide-react";
+import { AnimatePresence } from "framer-motion";
+import NotionForm from "@/components/welcome/notion-form";
+import { Button } from "@/components/ui/button";
+import Dataroom from "@/components/welcome/dataroom";
+import DataroomTrial from "@/components/welcome/dataroom-trial";
+import DeckGeneratorUpload from "@/components/welcome/special-upload";
+
+export default function DocumentNew() {
+ const router = useRouter();
+
+ return (
+ <div className="flex h-screen flex-col items-center justify-center max-w-3xl mx-auto overflow-x-hidden">
+ <div
+ className="absolute inset-x-0 top-10 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl"
+ aria-hidden="true"
+ >
+ <div
+ className="aspect-[1108/632] w-[69.25rem] flex-none bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-20"
+ style={{
+ clipPath:
+ "polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)",
+ }}
+ />
+ </div>
+ <AnimatePresence mode="wait">
+ {router.query.type ? (
+ <>
+ <button
+ className="group absolute left-2 sm:left-10 top-10 z-40 rounded-full p-2 transition-all hover:bg-gray-400"
+ onClick={() => router.back()}
+ >
+ <ArrowLeftIcon className="h-8 w-8 text-gray-500 group-hover:text-gray-800 group-active:scale-90" />
+ </button>
+
+ <Button
+ variant={"link"}
+ onClick={() => router.push("/documents")}
+ className="absolute right-2 sm:right-10 top-10 z-40 p-2 text-muted-foreground"
+ >
+ Skip to dashboard
+ </Button>
+ </>
+ ) : (
+ <DeckGeneratorUpload key="document" />
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}