Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add brand to dataroom
Marc Seitzd9787cd0c4f8
diff --git a/components/Sidebar.tsx b/components/Sidebar.tsxindex 2c5d9792..6bde33eb 100644--- a/components/Sidebar.tsx+++ b/components/Sidebar.tsx@@ -125,7 +125,8 @@ export const SidebarComponent = ({ className }: { className?: string }) => {icon: SettingsIcon,current:router.pathname.includes("settings") &&- !router.pathname.includes("branding"),+ !router.pathname.includes("branding") &&+ !router.pathname.includes("datarooms"),active: false,disabled: false,},diff --git a/components/view/PagesViewer.tsx b/components/view/PagesViewer.tsxindex d4c22114..78d30fbe 100644--- a/components/view/PagesViewer.tsx+++ b/components/view/PagesViewer.tsx@@ -5,7 +5,7 @@ import LoadingSpinner from "@/components/ui/loading-spinner";import BlankImg from "@/public/_static/blank.gif";import Nav from "./nav";import Toolbar from "./toolbar";-import { Brand } from "@prisma/client";+import { Brand, DataroomBrand } from "@prisma/client";import { useRouter } from "next/router";const DEFAULT_PRELOADED_IMAGES_NUM = 10;@@ -31,7 +31,7 @@ export default function PagesViewer({allowDownload: boolean;feedbackEnabled: boolean;versionNumber: number;- brand?: Brand;+ brand?: Brand | DataroomBrand;dataroomId?: string;setDocumentData?: (data: any) => void;}) {diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex 0de277e2..fc835e07 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -8,7 +8,7 @@ import { toast } from "sonner";import LoadingSpinner from "@/components/ui/loading-spinner";import EmailVerificationMessage from "../email-verification-form";-import { Brand } from "@prisma/client";+import { Brand, DataroomBrand } from "@prisma/client";import { useRouter } from "next/router";import { useAnalytics } from "@/lib/analytics";import DataroomViewer from "../DataroomViewer";@@ -35,7 +35,7 @@ export default function DataroomView({userEmail: string | null | undefined;userId: string | null | undefined;isProtected: boolean;- brand?: Brand;+ brand?: DataroomBrand;token?: string;verifiedEmail?: string;}) {diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex 1fcba0ee..ab0dcbcb 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -2,7 +2,7 @@ import Link from "next/link";import { Button } from "../ui/button";import PapermarkSparkle from "../shared/icons/papermark-sparkle";import { ArrowUpRight, Download } from "lucide-react";-import { Brand } from "@prisma/client";+import { Brand, DataroomBrand } from "@prisma/client";import Image from "next/image";import { toast } from "sonner";import {@@ -32,7 +32,7 @@ export default function Nav({numPages?: number;allowDownload?: boolean;assistantEnabled?: boolean;- brand?: Brand;+ brand?: Brand | DataroomBrand;embeddedLinks?: string[];viewId?: string;linkId?: string;diff --git a/lib/swr/use-brand.ts b/lib/swr/use-brand.tsindex 01f3f668..f56426fe 100644--- a/lib/swr/use-brand.ts+++ b/lib/swr/use-brand.ts@@ -3,7 +3,7 @@ import useSWR from "swr";import { fetcher } from "@/lib/utils";import { useMemo } from "react";import { useTeam } from "@/context/team-context";-import { Brand } from "@prisma/client";+import { Brand, DataroomBrand } from "@prisma/client";export function useBrand() {const teamInfo = useTeam();@@ -23,3 +23,22 @@ export function useBrand() {loading: !brand && !error,};}++export function useDataroomBrand({ dataroomId }: { dataroomId: string }) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: brand, error } = useSWR<DataroomBrand>(+ teamId && `/api/teams/${teamId}/datarooms/${dataroomId}/branding`,+ fetcher,+ {+ dedupingInterval: 30000,+ },+ );++ return {+ brand,+ error,+ loading: !brand && !error,+ };+}diff --git a/pages/api/links/[id]/dataroom.ts b/pages/api/links/[id]/dataroom.tsindex 5a43770d..bf4588f8 100644--- a/pages/api/links/[id]/dataroom.ts+++ b/pages/api/links/[id]/dataroom.ts@@ -42,6 +42,7 @@ export default async function handle(select: {id: true,folderId: true,+ updatedAt: true,document: {select: {id: true,@@ -77,12 +78,13 @@ export default async function handle(return res.status(404).json({ error: "Link is archived" });}- let brand = await prisma.brand.findFirst({+ let brand = await prisma.dataroomBrand.findFirst({where: {- teamId: link.dataroom?.teamId!,+ dataroomId: link.dataroom?.id!,},select: {logo: true,+ banner: true,brandColor: true,},});diff --git a/pages/api/teams/[teamId]/datarooms/[id]/branding.ts b/pages/api/teams/[teamId]/datarooms/[id]/branding.tsnew file mode 100644index 00000000..81d75d83--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/branding.ts@@ -0,0 +1,143 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import { del } from "@vercel/blob";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: dataroomId } = req.query as {+ teamId: string;+ id: string;+ };++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: (session.user as CustomUser).id,+ },+ },+ },+ select: {+ id: true,+ },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId: teamId,+ },+ });++ if (!dataroom) {+ return res.status(404).end("Dataroom not found");+ }+ } catch (error) {+ errorhandler(error, res);+ }++ if (req.method === "GET") {+ // GET /api/teams/:teamId/datarooms/:id/branding+ const brand = await prisma.dataroomBrand.findUnique({+ where: {+ dataroomId,+ },+ });++ if (!brand) {+ return res.status(200).json(null);+ }++ return res.status(200).json(brand);+ } else if (req.method === "POST") {+ // POST /api/teams/:teamId/datarooms/:id/branding+ const { logo, banner, brandColor, accentColor } = req.body as {+ logo?: string;+ banner?: string;+ brandColor?: string;+ accentColor?: string;+ };++ // update team with new branding+ const brand = await prisma.dataroomBrand.create({+ data: {+ logo,+ banner,+ brandColor,+ accentColor,+ dataroomId,+ },+ });++ return res.status(200).json(brand);+ } else if (req.method === "PUT") {+ // PUT /api/teams/:teamId/datarooms/:id/branding+ const { logo, banner, brandColor, accentColor } = req.body as {+ logo?: string;+ banner?: string;+ brandColor?: string;+ accentColor?: string;+ };++ const brand = await prisma.dataroomBrand.update({+ where: {+ dataroomId,+ },+ data: {+ logo,+ banner,+ brandColor,+ accentColor,+ },+ });++ return res.status(200).json(brand);+ } else if (req.method === "DELETE") {+ // DELETE /api/teams/:teamId/datarooms/:id/branding+ const brand = await prisma.dataroomBrand.findFirst({+ where: {+ dataroomId,+ },+ select: { id: true, logo: true, banner: true },+ });++ if (brand && brand.logo) {+ // delete the logo from vercel blob+ await del(brand.logo);+ }+ if (brand && brand.banner) {+ // delete the logo from vercel blob+ await del(brand.banner);+ }++ // delete the branding from database+ await prisma.dataroomBrand.delete({+ where: {+ id: brand?.id,+ },+ });++ return res.status(204).end();+ } else {+ // We only allow GET and DELETE requests+ res.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/datarooms/[id]/settings/index.tsx b/pages/datarooms/[id]/settings/index.tsxnew file mode 100644index 00000000..85320c8c--- /dev/null+++ b/pages/datarooms/[id]/settings/index.tsx@@ -0,0 +1,463 @@+import { DataroomHeader } from "@/components/datarooms/dataroom-header";+import AppLayout from "@/components/layouts/app";+import { NavMenu } from "@/components/navigation-menu";+import { Button } from "@/components/ui/button";+import { Card, CardContent, CardFooter } from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import LoadingSpinner from "@/components/ui/loading-spinner";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { useTeam } from "@/context/team-context";+import { useDataroomBrand } from "@/lib/swr/use-brand";+import { useDataroom } from "@/lib/swr/use-dataroom";+import { convertDataUrlToFile, uploadImage } from "@/lib/utils";+import { PlusIcon } from "lucide-react";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";+import { HexColorInput, HexColorPicker } from "react-colorful";+import { toast } from "sonner";+import { mutate } from "swr";++export default function DataroomBrandPage() {+ const router = useRouter();+ const teamInfo = useTeam();+ const { dataroom } = useDataroom();+ const { brand } = useDataroomBrand({ dataroomId: dataroom?.id });++ const [brandColor, setBrandColor] = useState<string>("#000000");+ const [logo, setLogo] = useState<string | null>(null);+ const [banner, setBanner] = useState<string | null>(null);++ const [isLoading, setIsLoading] = useState<boolean>(false);+ const [fileError, setFileError] = useState<string | null>(null);+ const [dragActive, setDragActive] = useState(false);++ const onChangeLogo = useCallback(+ (e: any) => {+ setFileError(null);+ const file = e.target.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 2) {+ setFileError("File size too big (max 2MB)");+ } else if (file.type !== "image/png" && file.type !== "image/jpeg") {+ setFileError("File type not supported (.png or .jpg only)");+ } else {+ const reader = new FileReader();+ reader.onload = (e) => {+ setLogo(e.target?.result as string);+ };+ reader.readAsDataURL(file);+ }+ }+ },+ [setLogo],+ );++ const onChangeBanner = useCallback(+ (e: any) => {+ setFileError(null);+ const file = e.target.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 5) {+ setFileError("File size too big (max 5MB)");+ } else if (file.type !== "image/png" && file.type !== "image/jpeg") {+ setFileError("File type not supported (.png or .jpg only)");+ } else {+ const reader = new FileReader();+ reader.onload = (e) => {+ setBanner(e.target?.result as string);+ };+ reader.readAsDataURL(file);+ }+ }+ },+ [setBanner],+ );++ useEffect(() => {+ if (brand) {+ setBrandColor(brand.brandColor || "#000000");+ setLogo(brand.logo || null);+ setBanner(brand.banner || null);+ }+ }, [brand]);++ if (!dataroom) {+ return <div>Loading...</div>;+ }++ const saveBranding = async (e: any) => {+ e.preventDefault();++ setIsLoading(true);++ // Upload the image if it's a data URL+ let blobUrl: string | null = logo && logo.startsWith("data:") ? null : logo;+ if (logo && logo.startsWith("data:")) {+ // Convert the data URL to a blob+ const blob = convertDataUrlToFile({ dataUrl: logo });+ // Upload the blob to vercel storage+ blobUrl = await uploadImage(blob);+ setLogo(blobUrl);+ }++ let bannerBlobUrl: string | null =+ banner && banner.startsWith("data:") ? null : banner;+ if (banner && banner.startsWith("data:")) {+ // Convert the data URL to a blob+ const blob = convertDataUrlToFile({ dataUrl: banner });+ // Upload the blob to vercel storage+ bannerBlobUrl = await uploadImage(blob);+ setBanner(blobUrl);+ }++ const data = {+ brandColor: brandColor,+ logo: blobUrl,+ banner: bannerBlobUrl,+ };++ const res = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroom.id}/branding`,+ {+ method: brand ? "PUT" : "POST",+ body: JSON.stringify(data),+ headers: {+ "Content-Type": "application/json",+ },+ },+ );+ if (res.ok) {+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroom.id}/branding`,+ );+ setIsLoading(false);+ toast.success("Branding updated successfully");+ }+ };++ const handleDelete = async () => {+ setIsLoading(true);++ const res = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroom.id}/branding`,+ {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ },+ );+ if (res.ok) {+ setLogo(null);+ setBanner(null);+ setBrandColor("#000000");+ setIsLoading(false);+ toast.success("Branding reset successfully");+ router.reload();+ }+ };++ return (+ <AppLayout>+ <div className="relative overflow-hidden mx-2 sm:mx-3 md:mx-5 lg:mx-7 xl:mx-10 mt-4 md:mt-5 lg:mt-8 mb-10 space-y-8 px-1">+ <header>+ <DataroomHeader+ title={dataroom.name}+ description={dataroom.pId}+ actions={+ [+ // <Button onClick={() => setIsLinkSheetOpen(true)} key={1}>+ // Create Link+ // </Button>,+ ]+ }+ />++ <NavMenu+ navigation={[+ {+ label: "Overview",+ href: `/datarooms/${dataroom.id}`,+ segment: `${dataroom.id}`,+ },+ {+ label: "Documents",+ href: `/datarooms/${dataroom.id}/documents`,+ segment: "documents",+ },+ {+ label: "Analytics",+ href: `/datarooms/${dataroom.id}/analytics`,+ segment: "analytics",+ },+ {+ label: "Settings",+ href: `/datarooms/${dataroom.id}/settings`,+ segment: "settings",+ },+ ]}+ />+ </header>++ <div className="space-y-4">+ <div>+ <Card className="dark:bg-secondary">+ <CardContent className="pt-6">+ <div className="grid gap-6">+ {/* Logo Input */}+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <Label htmlFor="logo">+ Logo{" "}+ <span className="italic text-muted-foreground text-sm">+ (max 2 MB)+ </span>+ </Label>+ {fileError ? (+ <p className="text-sm text-red-500">{fileError}</p>+ ) : null}+ </div>+ <label+ htmlFor="image"+ className="group relative mt-1 flex h-[4rem] w-[12rem] cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"+ >+ {false && (+ <div className="absolute z-[5] flex h-full w-full items-center justify-center rounded-md bg-white">+ <LoadingSpinner />+ </div>+ )}+ <div+ className="absolute z-[5] h-full w-full rounded-md"+ onDragOver={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(true);+ }}+ onDragEnter={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(true);+ }}+ onDragLeave={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(false);+ }}+ onDrop={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(false);+ setFileError(null);+ const file =+ e.dataTransfer.files && e.dataTransfer.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 2) {+ setFileError("File size too big (max 2MB)");+ } else if (+ file.type !== "image/png" &&+ file.type !== "image/jpeg"+ ) {+ setFileError(+ "File type not supported (.png or .jpg only)",+ );+ } else {+ const reader = new FileReader();+ reader.onload = (e) => {+ setLogo(e.target?.result as string);+ };+ reader.readAsDataURL(file);+ }+ }+ }}+ />+ <div+ className={`${+ dragActive+ ? "cursor-copy border-2 border-black bg-gray-50 opacity-100"+ : ""+ } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md bg-white transition-all ${+ logo+ ? "opacity-0 group-hover:opacity-100"+ : "group-hover:bg-gray-50"+ }`}+ >+ <PlusIcon+ className={`${+ dragActive ? "scale-110" : "scale-100"+ } h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}+ />+ <span className="sr-only">OG image upload</span>+ </div>+ {logo && (+ <img+ src={logo}+ alt="Preview"+ className="h-full w-full rounded-md object-contain"+ />+ )}+ </label>+ <div className="mt-1 flex rounded-md shadow-sm">+ <input+ id="image"+ name="image"+ type="file"+ accept="image/jpeg,image/png"+ className="sr-only"+ onChange={onChangeLogo}+ />+ </div>+ </div>++ {/* Banner Input */}+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <Label htmlFor="banner">+ Banner{" "}+ <span className="italic text-muted-foreground text-sm">+ (max 5 MB, min. 1920x320)+ </span>+ </Label>+ {fileError ? (+ <p className="text-sm text-red-500">{fileError}</p>+ ) : null}+ </div>+ <label+ htmlFor="banner-image"+ className="group relative mt-1 flex h-[4rem] w-[12rem] cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"+ >+ {false && (+ <div className="absolute z-[5] flex h-full w-full items-center justify-center rounded-md bg-white">+ <LoadingSpinner />+ </div>+ )}+ <div+ className="absolute z-[5] h-full w-full rounded-md"+ onDragOver={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(true);+ }}+ onDragEnter={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(true);+ }}+ onDragLeave={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(false);+ }}+ onDrop={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setDragActive(false);+ setFileError(null);+ const file =+ e.dataTransfer.files && e.dataTransfer.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 5) {+ setFileError("File size too big (max 5MB)");+ } else if (+ file.type !== "image/png" &&+ file.type !== "image/jpeg"+ ) {+ setFileError(+ "File type not supported (.png or .jpg only)",+ );+ } else {+ const reader = new FileReader();+ reader.onload = (e) => {+ setBanner(e.target?.result as string);+ };+ reader.readAsDataURL(file);+ }+ }+ }}+ />+ <div+ className={`${+ dragActive+ ? "cursor-copy border-2 border-black bg-gray-50 opacity-100"+ : ""+ } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md bg-white transition-all ${+ banner+ ? "opacity-0 group-hover:opacity-100"+ : "group-hover:bg-gray-50"+ }`}+ >+ <PlusIcon+ className={`${+ dragActive ? "scale-110" : "scale-100"+ } h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}+ />+ <span className="sr-only">OG image upload</span>+ </div>+ {banner && (+ <img+ src={banner}+ alt="Preview"+ className="h-full w-full rounded-md object-contain"+ />+ )}+ </label>+ <div className="mt-1 flex rounded-md shadow-sm">+ <input+ id="banner-image"+ name="image"+ type="file"+ accept="image/jpeg,image/png"+ className="sr-only"+ onChange={onChangeBanner}+ />+ </div>+ </div>++ {/* Brand Color Input */}+ <div className="flex flex-col gap-2">+ <Label htmlFor="primary-color">Brand Color</Label>+ <div className="flex space-x-1">+ <Popover>+ <PopoverTrigger>+ <div+ className="w-9 h-9 rounded-md cursor-pointer ring-1 ring-muted-foreground shadow-sm hover:ring-1 hover:ring-gray-300"+ style={{ backgroundColor: brandColor }}+ />+ </PopoverTrigger>+ <PopoverContent>+ <HexColorPicker+ color={brandColor}+ onChange={setBrandColor}+ />+ </PopoverContent>+ </Popover>+ <HexColorInput+ className="flex h-9 w-full rounded-md border-0 bg-background px-3 py-2 text-sm ring-1 ring-muted-foreground shadow-sm placeholder:text-muted-foreground focus:ring-1 focus:ring-gray-300 focus:border-0"+ color={brandColor}+ onChange={setBrandColor}+ prefixed+ />+ </div>+ </div>+ </div>+ </CardContent>+ <CardFooter className="border-t p-6">+ <Button onClick={saveBranding} loading={isLoading}>+ Save changes+ </Button>++ {/* delete button */}+ <Button variant="link" onClick={handleDelete} disabled={!brand}>+ Reset branding+ </Button>+ </CardFooter>+ </Card>+ </div>+ </div>+ </div>+ </AppLayout>+ );+}diff --git a/pages/view/d/[linkId]/index.tsx b/pages/view/d/[linkId]/index.tsxindex bc8d51cc..1f214072 100644--- a/pages/view/d/[linkId]/index.tsx+++ b/pages/view/d/[linkId]/index.tsx@@ -5,7 +5,7 @@ import { useSession } from "next-auth/react";import { CustomUser } from "@/lib/types";import { GetStaticPropsContext } from "next";import { useRouter } from "next/router";-import { Brand, DataroomFolder, Link } from "@prisma/client";+import { Brand, DataroomBrand, DataroomFolder, Link } from "@prisma/client";import CustomMetatag from "@/components/view/custom-metatag";import Head from "next/head";import DataroomView from "@/components/view/dataroom/dataroom-view";@@ -47,7 +47,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {}const { link, brand } = (await res.json()) as {link: LinkWithDataroom;- brand: Brand | null;+ brand: DataroomBrand | null;};if (!link || !link.dataroom) {@@ -116,7 +116,7 @@ export default function ViewPage({metaDescription: string | null;metaImage: string | null;} | null;- brand?: Brand;+ brand?: DataroomBrand;}) {const router = useRouter();const { token, email: verifiedEmail } = router.query as {