Skip to content

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

refactor: make document view its own component

Marc Seitz56e61c91176c
diff --git a/components/view/access-form/email-section.tsx b/components/view/access-form/email-section.tsx
index a70e19d4..9cab3891 100644
--- a/components/view/access-form/email-section.tsx
+++ b/components/view/access-form/email-section.tsx
@@ -1,5 +1,5 @@
-import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
import { Dispatch, SetStateAction } from "react";
+import { DEFAULT_ACCESS_FORM_TYPE } from "../document-view";
export default function EmailSection({
diff --git a/components/view/access-form/index.tsx b/components/view/access-form/index.tsx
index f97948e9..26a720b6 100644
--- a/components/view/access-form/index.tsx
+++ b/components/view/access-form/index.tsx
@@ -1,8 +1,8 @@
import { Dispatch, SetStateAction } from "react";
import PasswordSection from "./password-section";
import EmailSection from "./email-section";
-import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
import { Button } from "@/components/ui/button";
+import { DEFAULT_ACCESS_FORM_TYPE } from "../document-view";
export default function AccessForm({
diff --git a/components/view/access-form/password-section.tsx b/components/view/access-form/password-section.tsx
index deb966fc..a610c3e7 100644
--- a/components/view/access-form/password-section.tsx
+++ b/components/view/access-form/password-section.tsx
@@ -1,7 +1,8 @@
import { Dispatch, SetStateAction, useState } from "react";
import Eye from "@/components/shared/icons/eye";
import EyeOff from "@/components/shared/icons/eye-off";
-import { DEFAULT_ACCESS_FORM_TYPE } from "@/pages/view/[linkId]";
+import { DEFAULT_ACCESS_FORM_TYPE } from "../document-view";
+
export default function PasswordSection({
data,
setData,
diff --git a/components/view/document-view.tsx b/components/view/document-view.tsx
new file mode 100644
index 00000000..341bc279
--- /dev/null
+++ b/components/view/document-view.tsx
@@ -0,0 +1,167 @@
+import React, { useEffect, useRef, useState } from "react";
+import { getExtension } from "@/lib/utils";
+import ErrorPage from "next/error";
+import PDFViewer from "@/components/PDFViewer";
+import AccessForm from "@/components/view/access-form";
+import { useSession } from "next-auth/react";
+import { usePlausible } from "next-plausible";
+import { toast } from "sonner";
+import { LinkWithDocument } from "@/lib/types";
+
+export const DEFAULT_ACCESS_FORM_DATA = {
+ email: null,
+ password: null,
+};
+
+export type DEFAULT_ACCESS_FORM_TYPE = {
+ email: string | null;
+ password: string | null;
+};
+
+export type DEFAULT_DOCUMENT_VIEW_TYPE = {
+ viewId: string;
+ file: string;
+};
+
+export default function DocumentView({ link, error }: { link: LinkWithDocument; error: any }) {
+ const { data: session } = useSession();
+ const plausible = usePlausible();
+
+ const [submitted, setSubmitted] = useState<boolean>(false);
+ // const [viewId, setViewId] = useState<string>("");
+ const hasInitiatedSubmit = useRef(false);
+ const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({
+ viewId: "",
+ file: "",
+ });
+
+ const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(
+ DEFAULT_ACCESS_FORM_DATA
+ );
+
+ useEffect(() => {
+ const userEmail = session?.user?.email;
+ if (userEmail) {
+ setData((prevData) => ({
+ ...prevData,
+ email: userEmail || prevData.email,
+ }));
+ }
+ }, [session]);
+
+ if (error && error.status === 404) {
+ return <ErrorPage statusCode={404} />;
+ }
+
+ if (!link) {
+ return <div>Loading...</div>;
+ }
+
+ const { document, expiresAt, emailProtected, password: linkPassword } = link;
+
+ // Check if link is expired
+ const isExpired = expiresAt && new Date(expiresAt) < new Date();
+ if (isExpired) {
+ return <div>Link is expired</div>;
+ }
+
+ const handleSubmission = async () => {
+ const response = await fetch("/api/views", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...data,
+ linkId: link.id,
+ documentId: document.id,
+ }),
+ });
+
+ if (response.ok) {
+ const { viewId, file } = (await response.json()) as {
+ viewId: string;
+ file: string;
+ };
+ plausible("documentViewed"); // track the event
+ setViewData({ viewId, file });
+ setSubmitted(true);
+ } else {
+ const { message } = await response.json();
+ toast.error(message);
+ }
+ };
+
+ const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (
+ event: React.FormEvent
+ ) => {
+ event.preventDefault();
+ await handleSubmission();
+ };
+
+ if ((!submitted && emailProtected) || (!submitted && linkPassword)) {
+ return (
+ <AccessForm
+ onSubmitHandler={handleSubmit}
+ data={data}
+ setData={setData}
+ requireEmail={emailProtected}
+ requirePassword={!!linkPassword}
+ />
+ );
+ }
+
+ if (
+ !emailProtected &&
+ !linkPassword &&
+ !submitted &&
+ !hasInitiatedSubmit.current
+ ) {
+ hasInitiatedSubmit.current = true;
+ handleSubmission();
+ }
+
+ // get the file extension
+ const extension = getExtension(viewData.file);
+
+ if (
+ extension.includes(".docx") ||
+ extension.includes(".pptx") ||
+ extension.includes(".xlsx") ||
+ extension.includes(".xls") ||
+ extension.includes(".doc") ||
+ extension.includes(".ppt")
+ ) {
+ return (
+ <div className="h-screen bg-gray-900">
+ <iframe
+ className="w-full h-full"
+ src={`https://view.officeapps.live.com/op/embed.aspx?src=${viewData.file}`}
+ ></iframe>
+ </div>
+ );
+ }
+
+ if (
+ extension.includes(".png") ||
+ extension.includes(".jpeg") ||
+ extension.includes(".gif") ||
+ extension.includes(".jpg")
+ ) {
+ return (
+ <div className="h-screen bg-gray-900">
+ <img className="w-full h-full" src={viewData.file} />
+ </div>
+ );
+ }
+ return (
+ <div className="bg-gray-950">
+ <PDFViewer
+ file={viewData.file}
+ viewId={viewData.viewId}
+ linkId={link.id}
+ documentId={document.id}
+ />
+ </div>
+ );
+}
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index f6a7c332..297b99ad 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -10,11 +10,6 @@ export default async function handle(
) {
if (req.method === "GET") {
// GET /api/links/:id
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).end("Unauthorized");
- }
-
const { id } = req.query as { id: string };
try {
diff --git a/pages/api/links/domains/[domain]/[slug]/index.ts b/pages/api/links/domains/[domain]/[slug]/index.ts
index 45bbe465..8b1b8cc1 100644
--- a/pages/api/links/domains/[domain]/[slug]/index.ts
+++ b/pages/api/links/domains/[domain]/[slug]/index.ts
@@ -1,7 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
-import { getServerSession } from "next-auth/next";
-import { authOptions } from "@/pages/api/auth/[...nextauth]";
export default async function handle(
req: NextApiRequest,
@@ -17,11 +15,14 @@ export default async function handle(
domainSlug_slug: {
slug: slug,
domainSlug: domain,
- }
+ },
},
select: {
id: true,
- document: { select: { id: true, name: true, file: true } },
+ expiresAt: true,
+ emailProtected: true,
+ password: true,
+ document: { select: { id: true } },
},
});
diff --git a/pages/view/[linkId].tsx b/pages/view/[linkId].tsx
index 3f47215c..c6e481a2 100644
--- a/pages/view/[linkId].tsx
+++ b/pages/view/[linkId].tsx
@@ -1,162 +1,12 @@
-import React, { useEffect, useRef, useState } from "react";
-import { getExtension } from "@/lib/utils";
+import DocumentView from "@/components/view/document-view";
import { useLink } from "@/lib/swr/use-link";
-import ErrorPage from "next/error";
-import PDFViewer from "@/components/PDFViewer";
-import AccessForm from "@/components/view/access-form";
-import { useSession } from "next-auth/react";
-import { usePlausible } from "next-plausible";
-import { toast } from "sonner";
-
-export const DEFAULT_ACCESS_FORM_DATA = {
- email: null,
- password: null,
-};
-
-export type DEFAULT_ACCESS_FORM_TYPE = {
- email: string | null;
- password: string | null;
-};
-
-export type DEFAULT_DOCUMENT_VIEW_TYPE = {
- viewId: string;
- file: string;
-}
-
-export default function DocumentView() {
+export default function ViewPage() {
const { link, error } = useLink();
- const { data: session } = useSession();
- const plausible = usePlausible();
-
- const [submitted, setSubmitted] = useState<boolean>(false);
- // const [viewId, setViewId] = useState<string>("");
- const hasInitiatedSubmit = useRef(false);
- const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({viewId: "", file: ""})
-
- const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(
- DEFAULT_ACCESS_FORM_DATA
- );
-
- useEffect(() => {
- const userEmail = session?.user?.email;
- if (userEmail) {
- setData((prevData) => ({
- ...prevData,
- email: userEmail || prevData.email,
- }));
- }
- }, [session]);
- if (error && error.status === 404) {
- return <ErrorPage statusCode={404} />;
- }
-
- if (!link) {
+ if (!link){
return <div>Loading...</div>;
}
-
- const { document, expiresAt, emailProtected, password: linkPassword } = link;
-
- // Check if link is expired
- const isExpired = expiresAt && new Date(expiresAt) < new Date();
- if (isExpired) {
- return <div>Link is expired</div>;
- }
-
- const handleSubmission = async () => {
- const response = await fetch("/api/views", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- ...data,
- linkId: link.id,
- documentId: document.id,
- }),
- });
-
- if (response.ok) {
- const { viewId, file } = await response.json() as { viewId: string, file: string};
- plausible("documentViewed"); // track the event
- setViewData({ viewId, file });
- setSubmitted(true);
- } else {
- const { message } = await response.json();
- toast.error(message);
- }
- }
-
- const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (event: React.FormEvent) => {
- event.preventDefault()
- await handleSubmission();
- };
-
- if ((!submitted && emailProtected) || (!submitted && linkPassword)) {
- return (
- <AccessForm
- onSubmitHandler={handleSubmit}
- data={data}
- setData={setData}
- requireEmail={emailProtected}
- requirePassword={!!linkPassword}
- />
- );
- }
-
- if (
- !emailProtected &&
- !linkPassword &&
- !submitted &&
- !hasInitiatedSubmit.current
- ) {
- hasInitiatedSubmit.current = true;
- handleSubmission();
- }
-
- // get the file extension
- const extension = getExtension(viewData.file);
-
- if (
- extension.includes(".docx") ||
- extension.includes(".pptx") ||
- extension.includes(".xlsx") ||
- extension.includes(".xls") ||
- extension.includes(".doc") ||
- extension.includes(".ppt")
- ) {
- return (
- <div className="h-screen bg-gray-900">
- <iframe
- className="w-full h-full"
- src={`https://view.officeapps.live.com/op/embed.aspx?src=${viewData.file}`}
- ></iframe>
- </div>
- );
- }
-
- if (
- extension.includes(".png") ||
- extension.includes(".jpeg") ||
- extension.includes(".gif") ||
- extension.includes(".jpg")
- ) {
- return (
- <div className="h-screen bg-gray-900">
- <img className="w-full h-full" src={viewData.file} />
- </div>
- );
- }
- return (
- <div className="bg-gray-950">
- <PDFViewer
- file={viewData.file}
- viewId={viewData.viewId}
- linkId={link.id}
- documentId={document.id}
- />
- </div>
- );
+ return <DocumentView link={link} error={error} />;
}
diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsx
index 98dd6667..f9c2557a 100644
--- a/pages/view/domains/[domain]/[slug]/index.tsx
+++ b/pages/view/domains/[domain]/[slug]/index.tsx
@@ -1,155 +1,12 @@
-import React, { useEffect, useRef, useState } from "react";
-import { getExtension } from "@/lib/utils";
+import DocumentView from "@/components/view/document-view";
import { useDomainLink } from "@/lib/swr/use-link";
-import ErrorPage from "next/error";
-import PDFViewer from "@/components/PDFViewer";
-import AccessForm from "@/components/view/access-form";
-import { useSession } from "next-auth/react";
-import { usePlausible } from "next-plausible";
-import { toast } from "sonner";
-import { DEFAULT_ACCESS_FORM_DATA, DEFAULT_ACCESS_FORM_TYPE, DEFAULT_DOCUMENT_VIEW_TYPE } from "@/pages/view/[linkId]";
-
-export default function DocumentView() {
+export default function ViewPage() {
const { link, error } = useDomainLink();
- const { data: session } = useSession();
- const plausible = usePlausible();
-
- const [submitted, setSubmitted] = useState<boolean>(false);
- // const [viewId, setViewId] = useState<string>("");
- const hasInitiatedSubmit = useRef(false);
- const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({
- viewId: "",
- file: "",
- });
-
- const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(
- DEFAULT_ACCESS_FORM_DATA
- );
-
- useEffect(() => {
- const userEmail = session?.user?.email;
- if (userEmail) {
- setData((prevData) => ({
- ...prevData,
- email: userEmail || prevData.email,
- }));
- }
- }, [session]);
-
- if (error && error.status === 404) {
- return <ErrorPage statusCode={404} />;
- }
if (!link) {
return <div>Loading...</div>;
}
- const { document, expiresAt, emailProtected, password: linkPassword } = link;
-
- // Check if link is expired
- const isExpired = expiresAt && new Date(expiresAt) < new Date();
- if (isExpired) {
- return <div>Link is expired</div>;
- }
-
- const handleSubmission = async () => {
- const response = await fetch("/api/views", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- ...data,
- linkId: link.id,
- documentId: document.id,
- }),
- });
-
- if (response.ok) {
- const { viewId, file } = (await response.json()) as {
- viewId: string;
- file: string;
- };
- plausible("documentViewed"); // track the event
- setViewData({ viewId, file });
- setSubmitted(true);
- } else {
- const { message } = await response.json();
- toast.error(message);
- }
- };
-
- const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (
- event: React.FormEvent
- ) => {
- event.preventDefault();
- await handleSubmission();
- };
-
- if ((!submitted && emailProtected) || (!submitted && linkPassword)) {
- return (
- <AccessForm
- onSubmitHandler={handleSubmit}
- data={data}
- setData={setData}
- requireEmail={emailProtected}
- requirePassword={!!linkPassword}
- />
- );
- }
-
- if (
- !emailProtected &&
- !linkPassword &&
- !submitted &&
- !hasInitiatedSubmit.current
- ) {
- hasInitiatedSubmit.current = true;
- handleSubmission();
- }
-
- // get the file extension
- const extension = getExtension(viewData.file);
-
- if (
- extension.includes(".docx") ||
- extension.includes(".pptx") ||
- extension.includes(".xlsx") ||
- extension.includes(".xls") ||
- extension.includes(".doc") ||
- extension.includes(".ppt")
- ) {
- return (
- <div className="h-screen bg-gray-900">
- <iframe
- className="w-full h-full"
- src={`https://view.officeapps.live.com/op/embed.aspx?src=${viewData.file}`}
- ></iframe>
- </div>
- );
- }
-
- if (
- extension.includes(".png") ||
- extension.includes(".jpeg") ||
- extension.includes(".gif") ||
- extension.includes(".jpg")
- ) {
- return (
- <div className="h-screen bg-gray-900">
- <img className="w-full h-full" src={viewData.file} />
- </div>
- );
- }
- return (
- <div className="bg-gray-950">
- <PDFViewer
- file={viewData.file}
- viewId={viewData.viewId}
- linkId={link.id}
- documentId={document.id}
- />
- </div>
- );
+ return <DocumentView link={link} error={error} />;
}