Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add link presets (#580)
Marc Seitz3b3fa5d5d809
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 8475a68b..2a112b39 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -260,6 +260,7 @@ export default function LinkSheet({data={data}setData={setData}linkType={linkType}+ editLink={!!currentLink}/></div></div>diff --git a/components/links/link-sheet/link-item.tsx b/components/links/link-sheet/link-item.tsxindex 55a2085f..12f12a43 100644--- a/components/links/link-sheet/link-item.tsx+++ b/components/links/link-sheet/link-item.tsx@@ -1,5 +1,9 @@+import { RotateCcwIcon } from "lucide-react";+import PlanBadge from "@/components/billing/plan-badge";+import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";+import { ButtonTooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";@@ -10,6 +14,7 @@ export default function LinkItem({isAllowed = true,requiredPlan,upgradeAction,+ resetAction,}: {title: string;enabled: boolean;@@ -17,13 +22,14 @@ export default function LinkItem({isAllowed?: boolean;requiredPlan?: string;upgradeAction?: () => void;+ resetAction?: () => void;}) {return (- <div className="flex items-center justify-between">- <div className="flex items-center justify-between space-x-2">+ <div className="flex items-center justify-between gap-x-2">+ <div className="flex w-full items-center justify-between space-x-2"><h2className={cn(- "cursor-pointer text-sm font-medium leading-6",+ "flex-1 cursor-pointer text-sm font-medium leading-6",enabled ? "text-foreground" : "text-muted-foreground",)}onClick={isAllowed ? action : () => upgradeAction?.()}@@ -31,6 +37,22 @@ export default function LinkItem({{title}{!isAllowed && requiredPlan && <PlanBadge plan={requiredPlan} />}</h2>+ {enabled && resetAction && (+ <ButtonTooltip content="Reset to defaults">+ <Button+ size="icon"+ variant="ghost"+ className="h-6"+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ resetAction();+ }}+ >+ <RotateCcwIcon className="h-4 w-4" />+ </Button>+ </ButtonTooltip>+ )}</div><Switchchecked={enabled}diff --git a/components/links/link-sheet/link-options.tsx b/components/links/link-sheet/link-options.tsxindex ce7395a9..8f5ccde3 100644--- a/components/links/link-sheet/link-options.tsx+++ b/components/links/link-sheet/link-options.tsx@@ -34,10 +34,12 @@ export const LinkOptions = ({data,setData,linkType,+ editLink,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;linkType: LinkType;+ editLink?: boolean;}) => {const { plan, trial } = usePlan();const { limits } = useLimits();@@ -83,6 +85,7 @@ export const LinkOptions = ({isDatarooms}handleUpgradeStateChange={handleUpgradeStateChange}+ editLink={editLink ?? false}/><EmailAuthenticationSectiondiff --git a/components/links/link-sheet/og-section.tsx b/components/links/link-sheet/og-section.tsxindex 328e0a65..5b8eb1ed 100644--- a/components/links/link-sheet/og-section.tsx+++ b/components/links/link-sheet/og-section.tsx@@ -1,14 +1,18 @@import { useCallback, useEffect, useState } from "react";+import { useTeam } from "@/context/team-context";+import { LinkPreset } from "@prisma/client";import { motion } from "framer-motion";import { Upload as ArrowUpTrayIcon } from "lucide-react";+import useSWRImmutable from "swr/immutable";import { Input } from "@/components/ui/input";import LoadingSpinner from "@/components/ui/loading-spinner";import { Textarea } from "@/components/ui/textarea";import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";-import { cn } from "@/lib/utils";+import { cn, fetcher } from "@/lib/utils";+import { resizeImage } from "@/lib/utils/resize-image";import { DEFAULT_LINK_TYPE } from ".";import LinkItem from "./link-item";@@ -19,6 +23,7 @@ export default function OGSection({setData,isAllowed,handleUpgradeStateChange,+ editLink,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;@@ -28,15 +33,21 @@ export default function OGSection({trigger,plan,}: LinkUpgradeOptions) => void;+ editLink: boolean;}) {const { enableCustomMetatag, metaTitle, metaDescription, metaImage } = data;- const [enabled, setEnabled] = useState<boolean>(false);+ const teamInfo = useTeam();+ const { data: presets } = useSWRImmutable<LinkPreset>(+ `/api/teams/${teamInfo?.currentTeam?.id}/presets`,+ fetcher,+ );+ const [enabled, setEnabled] = useState<boolean>(false);const [fileError, setFileError] = useState<string | null>(null);const [dragActive, setDragActive] = useState(false);const onChangePicture = useCallback(- (e: any) => {+ async (e: any) => {setFileError(null);const file = e.target.files[0];if (file) {@@ -45,14 +56,11 @@ export default function OGSection({} 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) => {- setData((prev) => ({- ...prev,- metaImage: e.target?.result as string,- }));- };- reader.readAsDataURL(file);+ const image = await resizeImage(file);+ setData((prev) => ({+ ...prev,+ metaImage: image,+ }));}}},@@ -63,6 +71,29 @@ export default function OGSection({setEnabled(enableCustomMetatag);}, [enableCustomMetatag]);+ useEffect(() => {+ if (presets && !(metaTitle || metaDescription || metaImage)) {+ const preset = presets;+ if (preset) {+ setData((prev) => ({+ ...prev,+ metaImage: prev.metaImage || preset.metaImage,+ metaTitle: prev.metaTitle || preset.metaTitle,+ metaDescription: prev.metaDescription || preset.metaDescription,+ enableCustomMetatag: !editLink && true,+ }));+ }+ }+ }, [+ presets,+ setData,+ editLink,+ enableCustomMetatag,+ metaTitle,+ metaDescription,+ metaImage,+ ]);+const handleCustomMetatag = async () => {const updatedCustomMetatag = !enabled;@@ -70,6 +101,15 @@ export default function OGSection({setEnabled(updatedCustomMetatag);};+ const resetMetatags = () => {+ setData({+ ...data,+ metaImage: null || (presets?.metaImage ?? null),+ metaTitle: null || (presets?.metaTitle ?? null),+ metaDescription: null || (presets?.metaDescription ?? null),+ });+ };+return (<div className="pb-5"><LinkItem@@ -85,6 +125,7 @@ export default function OGSection({plan: "Business",})}+ resetAction={resetMetatags}/>{enabled && (@@ -101,7 +142,7 @@ export default function OGSection({</div><labelhtmlFor="image"- className="group relative mt-1 flex h-[14rem] cursor-pointer flex-col items-center justify-center rounded-md border border-input bg-white shadow-sm transition-all hover:border-muted-foreground hover:bg-gray-50 hover:ring-muted-foreground dark:bg-gray-800 hover:dark:bg-transparent"+ className="group relative mt-1 flex aspect-[1200/630] h-full min-h-[14rem] cursor-pointer flex-col items-center justify-center rounded-md border border-input bg-white shadow-sm transition-all hover:border-muted-foreground hover:bg-gray-50 hover:ring-muted-foreground dark:bg-gray-800 hover:dark:bg-transparent">{false && (<div className="absolute z-[5] flex h-full w-full items-center justify-center rounded-md bg-white">@@ -125,7 +166,7 @@ export default function OGSection({e.stopPropagation();setDragActive(false);}}- onDrop={(e) => {+ onDrop={async (e) => {e.preventDefault();e.stopPropagation();setDragActive(false);@@ -142,14 +183,11 @@ export default function OGSection({"File type not supported (.png or .jpg only)",);} else {- const reader = new FileReader();- reader.onload = (e) => {- setData((prev) => ({- ...prev,- metaImage: e.target?.result as string,- }));- };- reader.readAsDataURL(file);+ const image = await resizeImage(file);+ setData((prev) => ({+ ...prev,+ metaImage: image,+ }));}}}}diff --git a/components/settings/og-preview.tsx b/components/settings/og-preview.tsxnew file mode 100644index 00000000..2a05c790--- /dev/null+++ b/components/settings/og-preview.tsx@@ -0,0 +1,203 @@+import { Dispatch, SetStateAction, useMemo } from "react";++import { ImageIcon } from "lucide-react";+import ReactTextareaAutosize from "react-textarea-autosize";++import { Facebook } from "../shared/icons/facebook";+import LinkedIn from "../shared/icons/linkedin";+import Twitter from "../shared/icons/twitter";++export default function Preview({+ data,+ setData,+}: {+ data: {+ metaImage: string | null;+ metaTitle: string | null;+ metaDescription: string | null;+ };+ setData: Dispatch<+ SetStateAction<{+ metaImage: string | null;+ metaTitle: string | null;+ metaDescription: string | null;+ }>+ >;+}) {+ const {+ metaTitle: title,+ metaDescription: description,+ metaImage: image,+ } = data;++ const hostname = "papermark.io";++ return (+ <div>+ <div className="sticky top-0 z-10 flex h-10 items-center justify-center border-b border-border bg-white px-5 dark:bg-gray-900 sm:h-14">+ <h2 className="text-lg font-medium">Previews</h2>+ </div>+ <div className="grid gap-5 p-5">+ {/* Twitter */}+ <div>+ <div className="relative mb-2">+ <div+ className="absolute inset-0 flex items-center"+ aria-hidden="true"+ >+ <div className="w-full border-t border-border" />+ </div>+ <div className="relative flex justify-center">+ <div className="flex items-center space-x-2 bg-white px-3 dark:bg-gray-900">+ <Twitter className="h-4 w-4" />+ <p className="text-sm text-muted-foreground">Twitter</p>+ </div>+ </div>+ </div>+ <div className="group relative overflow-hidden rounded-2xl border border-border">+ <ImagePreview image={image} />+ {(title || title === "") && (+ <div className="absolute bottom-2 left-2 rounded-md bg-[#414142] px-1.5 py-px">+ <h3 className="max-w-sm truncate text-sm text-white">+ {title}+ </h3>+ </div>+ )}+ </div>+ {hostname && (+ <p className="mt-2 text-[0.8rem] text-[#606770]">{hostname}</p>+ )}+ </div>++ {/* LinkedIn */}+ <div>+ <div className="relative mb-2">+ <div+ className="absolute inset-0 flex items-center"+ aria-hidden="true"+ >+ <div className="w-full border-t border-border" />+ </div>+ <div className="relative flex justify-center">+ <div className="flex items-center space-x-2 bg-white px-3 dark:bg-gray-900">+ <LinkedIn className="h-4 w-4" />+ <p className="text-sm text-muted-foreground">LinkedIn</p>+ </div>+ </div>+ </div>+ <div className="relative overflow-hidden rounded-[2px] shadow-[0_0_0_1px_rgba(0,0,0,0.15),0_2px_3px_rgba(0,0,0,0.2)] dark:shadow-[0_0_0_1px_rgba(255,255,255,0.15),0_2px_3px_rgba(255,255,255,0.2)]">+ <ImagePreview image={image} />+ <div className="grid gap-1 border-t border-border bg-white p-3">+ {title || title === "" ? (+ <input+ className="truncate border-none bg-transparent p-0 font-semibold text-[#000000E6] outline-none focus:ring-0"+ value={title}+ onChange={(e) => {+ setData((prev) => ({+ ...prev,+ title: e.currentTarget.value,+ }));+ }}+ />+ ) : (+ <div className="mb-1 h-5 w-full rounded-md bg-gray-200" />+ )}+ {hostname ? (+ <p className="text-xs text-[#00000099]">{hostname}</p>+ ) : (+ <div className="mb-1 h-4 w-24 rounded-md bg-gray-200" />+ )}+ </div>+ </div>+ </div>++ {/* Facebook */}+ <div>+ <div className="relative mb-2">+ <div+ className="absolute inset-0 flex items-center"+ aria-hidden="true"+ >+ <div className="w-full border-t border-border" />+ </div>+ <div className="relative flex justify-center">+ <div className="flex items-center space-x-2 bg-white px-3 dark:bg-gray-900">+ <Facebook className="h-4 w-4" />+ <p className="text-sm text-muted-foreground">Facebook</p>+ </div>+ </div>+ </div>+ <div className="relative border border-border">+ <ImagePreview image={image} />+ <div className="grid gap-1 border-t border-border bg-[#f2f3f5] p-3">+ {hostname ? (+ <p className="text-[0.8rem] uppercase text-[#606770]">+ {hostname}+ </p>+ ) : (+ <div className="mb-1 h-4 w-24 rounded-md bg-gray-200" />+ )}+ {title || title === "" ? (+ <input+ className="truncate border-none bg-transparent p-0 font-semibold text-[#1d2129] outline-none focus:ring-0"+ value={title}+ onChange={(e) => {+ setData((prev) => ({+ ...prev,+ title: e.currentTarget.value,+ }));+ }}+ />+ ) : (+ <div className="mb-1 h-5 w-full rounded-md bg-gray-200" />+ )}+ {description || description === "" ? (+ <ReactTextareaAutosize+ className="mb-1 line-clamp-2 w-full resize-none rounded-md border-none bg-gray-200 bg-transparent p-0 text-sm text-[#606770] outline-none focus:ring-0"+ value={description}+ maxRows={2}+ onChange={(e) => {+ setData((prev) => ({+ ...prev,+ description: e.currentTarget.value,+ }));+ }}+ />+ ) : (+ <div className="grid gap-2">+ <div className="h-4 w-full rounded-md bg-gray-200" />+ <div className="h-4 w-48 rounded-md bg-gray-200" />+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}++const ImagePreview = ({ image }: { image: string | null }) => {+ const previewImage = useMemo(() => {+ if (image) {+ return (+ <img+ src={image}+ alt="Preview"+ className="aspect-[1200/630] h-full w-full object-cover"+ />+ );+ } else {+ return (+ <div className="flex aspect-[1200/630] h-full min-h-[250px] w-full flex-col items-center justify-center space-y-4 bg-gray-100">+ <ImageIcon className="h-8 w-8 text-gray-400" />+ <p className="text-sm text-gray-400">+ Add an image to generate a preview.+ </p>+ </div>+ );+ }+ }, [image]);++ return <>{previewImage}</>;+};diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsxindex cd48cb87..efb15273 100644--- a/components/settings/settings-header.tsx+++ b/components/settings/settings-header.tsx@@ -36,6 +36,11 @@ export function SettingsHeader() {href: `/settings/branding`,segment: "branding",},+ {+ label: "Presets",+ href: `/settings/presets`,+ segment: "presets",+ },{label: "Billing",href: `/settings/billing`,diff --git a/components/shared/icons/facebook.tsx b/components/shared/icons/facebook.tsxnew file mode 100644index 00000000..7e23d1bf--- /dev/null+++ b/components/shared/icons/facebook.tsx@@ -0,0 +1,23 @@+export function Facebook({+ className,+ fill = "#1977f3",+}: {+ className?: string;+ fill?: string;+}) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="1365.12"+ height="1365.12"+ viewBox="0 0 14222 14222"+ className={className}+ >+ <circle cx="7111" cy="7112" r="7111" fill={fill} />+ <path+ d="M9879 9168l315-2056H8222V5778c0-562 275-1111 1159-1111h897V2917s-814-139-1592-139c-1624 0-2686 984-2686 2767v1567H4194v2056h1806v4969c362 57 733 86 1111 86s749-30 1111-86V9168z"+ fill="#fff"+ />+ </svg>+ );+}diff --git a/lib/utils/resize-image.ts b/lib/utils/resize-image.tsnew file mode 100644index 00000000..3322905a--- /dev/null+++ b/lib/utils/resize-image.ts@@ -0,0 +1,75 @@+export const resizeImage = (+ file: File,+ opts: {+ width: number;+ height: number;+ quality: number;+ } = {+ width: 1200, // Desired output width+ height: 630, // Desired output height+ quality: 1.0, // Set quality to maximum+ },+): Promise<string> => {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = (e: ProgressEvent<FileReader>) => {+ const img = new Image();+ img.src = e.target?.result as string;+ img.onload = () => {+ const targetWidth = opts.width;+ const targetHeight = opts.height;+ const canvas = document.createElement("canvas");+ canvas.width = targetWidth;+ canvas.height = targetHeight;++ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;+ ctx.imageSmoothingQuality = "high"; // Set image smoothing quality to high++ // Calculating the aspect ratio+ const sourceWidth = img.width;+ const sourceHeight = img.height;+ const sourceAspectRatio = sourceWidth / sourceHeight;+ const targetAspectRatio = targetWidth / targetHeight;++ let drawWidth: number;+ let drawHeight: number;+ let offsetX = 0;+ let offsetY = 0;++ // Adjust drawing sizes based on the aspect ratio+ if (sourceAspectRatio > targetAspectRatio) {+ // Source is wider+ drawHeight = sourceHeight;+ drawWidth = sourceHeight * targetAspectRatio;+ offsetX = (sourceWidth - drawWidth) / 2;+ } else {+ // Source is taller or has the same aspect ratio+ drawWidth = sourceWidth;+ drawHeight = sourceWidth / targetAspectRatio;+ offsetY = (sourceHeight - drawHeight) / 2;+ }++ // Draw the image onto the canvas+ ctx.drawImage(+ img,+ offsetX,+ offsetY,+ drawWidth,+ drawHeight,+ 0,+ 0,+ targetWidth,+ targetHeight,+ );++ // Convert the canvas to a base64 string+ const base64Image = canvas.toDataURL("image/jpeg", opts.quality);+ resolve(base64Image);+ };+ img.onerror = (error) =>+ reject(new Error("Image loading error: " + error));+ };+ reader.onerror = (error) => reject(new Error("FileReader error: " + error));+ reader.readAsDataURL(file);+ });+};diff --git a/package-lock.json b/package-lock.jsonindex 35d87e5f..5769d4c8 100644--- a/package-lock.json+++ b/package-lock.json@@ -103,6 +103,7 @@"stripe": "^16.8.0","swr": "^2.2.5","tailwind-merge": "^2.5.2",+ "tailwind-scrollbar-hide": "^1.1.7","tailwindcss": "^3.4.10","tailwindcss-animate": "^1.0.7","ts-pattern": "^5.3.1",@@ -19264,6 +19265,11 @@"url": "https://github.com/sponsors/dcastil"}},+ "node_modules/tailwind-scrollbar-hide": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/tailwind-scrollbar-hide/-/tailwind-scrollbar-hide-1.1.7.tgz",+ "integrity": "sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA=="+ },"node_modules/tailwindcss": {"version": "3.4.10","resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.10.tgz",diff --git a/package.json b/package.jsonindex 967a89bb..5cb08781 100644--- a/package.json+++ b/package.json@@ -112,6 +112,7 @@"stripe": "^16.8.0","swr": "^2.2.5","tailwind-merge": "^2.5.2",+ "tailwind-scrollbar-hide": "^1.1.7","tailwindcss": "^3.4.10","tailwindcss-animate": "^1.0.7","ts-pattern": "^5.3.1",diff --git a/pages/api/teams/[teamId]/presets/index.ts b/pages/api/teams/[teamId]/presets/index.tsnew file mode 100644index 00000000..1a606337--- /dev/null+++ b/pages/api/teams/[teamId]/presets/index.ts@@ -0,0 +1,129 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++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 } = req.query as { teamId: string };++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ },+ select: {+ id: true,+ users: { select: { userId: true } },+ },+ });++ // check that the user is member of the team, otherwise return 403+ const teamUsers = team?.users;+ const isUserPartOfTeam = teamUsers?.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );+ if (!isUserPartOfTeam) {+ return res.status(403).end("Unauthorized to access this team");+ }+ } catch (error) {+ errorhandler(error, res);+ }++ if (req.method === "GET") {+ // GET /api/teams/:teamId/presets+ const presets = await prisma.linkPreset.findMany({+ where: {+ teamId: teamId,+ },+ });++ if (!presets) {+ return res.status(200).json(null);+ }++ return res.status(200).json(presets[0]);+ } else if (req.method === "POST") {+ // POST /api/teams/:teamId/presets+ const { metaImage, metaTitle, metaDescription } = req.body as {+ metaImage?: string;+ metaTitle?: string;+ metaDescription?: string;+ };++ // update team with new preset+ const preset = await prisma.linkPreset.create({+ data: {+ metaImage,+ metaTitle,+ metaDescription,+ enableCustomMetaTag: true,+ name: "Default Link Metatag",+ teamId: teamId,+ },+ });++ return res.status(200).json(preset);+ } else if (req.method === "PUT") {+ // PUT /api/teams/:teamId/presets+ const { metaImage, metaTitle, metaDescription } = req.body as {+ metaImage?: string;+ metaTitle?: string;+ metaDescription?: string;+ };++ const presets = await prisma.linkPreset.findMany({+ where: {+ teamId: teamId,+ },+ });++ // if metaImage is different from previous one, delete the previous image++ const preset = await prisma.linkPreset.update({+ where: {+ teamId: teamId,+ id: presets[0].id,+ },+ data: {+ metaImage,+ metaTitle,+ metaDescription,+ },+ });++ return res.status(200).json(preset);+ } else if (req.method === "DELETE") {+ // DELETE /api/teams/:teamId/presets+ const preset = await prisma.linkPreset.findFirst({+ where: {+ teamId: teamId,+ },+ select: { id: true },+ });++ // delete the presets from database+ await prisma.linkPreset.delete({+ where: {+ id: preset?.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/settings/presets.tsx b/pages/settings/presets.tsxnew file mode 100644index 00000000..a6c62eb1--- /dev/null+++ b/pages/settings/presets.tsx@@ -0,0 +1,358 @@+import { ChangeEvent, useCallback, useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { LinkPreset } from "@prisma/client";+import { Upload as ArrowUpTrayIcon } from "lucide-react";+import { toast } from "sonner";+import useSWR, { mutate } from "swr";+import useSWRImmutable from "swr/immutable";++import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";+import AppLayout from "@/components/layouts/app";+import Preview from "@/components/settings/og-preview";+import { SettingsHeader } from "@/components/settings/settings-header";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import LoadingSpinner from "@/components/ui/loading-spinner";+import { Textarea } from "@/components/ui/textarea";++import { usePlan } from "@/lib/swr/use-billing";+import { cn, convertDataUrlToFile, fetcher, uploadImage } from "@/lib/utils";+import { resizeImage } from "@/lib/utils/resize-image";++export default function Presets() {+ const teamInfo = useTeam();+ const { plan } = usePlan();+ const { data: presets, mutate: mutatePreset } = useSWRImmutable<LinkPreset>(+ `/api/teams/${teamInfo?.currentTeam?.id}/presets`,+ fetcher,+ );++ const [data, setData] = useState<{+ metaImage: string | null;+ metaTitle: string | null;+ metaDescription: string | null;+ enableCustomMetatag?: boolean;+ }>({+ metaImage: null,+ metaTitle: null,+ metaDescription: null,+ enableCustomMetatag: false,+ });++ const [fileError, setFileError] = useState<string | null>(null);+ const [dragActive, setDragActive] = useState(false);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ console.log("presets", presets);+ if (presets) {+ setData({+ metaImage: presets.metaImage,+ metaTitle: presets.metaTitle,+ metaDescription: presets.metaDescription,+ });+ }+ }, [presets]);++ const onChangePicture = useCallback(+ async (e: ChangeEvent<HTMLInputElement>) => {+ setFileError(null);+ const file = e.target.files && 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 image = await resizeImage(file);+ setData((prev) => ({+ ...prev,+ metaImage: image,+ }));+ }+ }+ },+ [setData],+ );++ const handleSavePreset = async (e: any) => {+ e.preventDefault();++ setIsLoading(true);++ let blobUrl: string | null =+ data.metaImage && data.metaImage.startsWith("data:")+ ? null+ : data.metaImage;+ if (data.metaImage && data.metaImage.startsWith("data:")) {+ const blob = convertDataUrlToFile({ dataUrl: data.metaImage });+ blobUrl = await uploadImage(blob);+ setData({ ...data, metaImage: blobUrl });+ }++ const res = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {+ method: presets ? "PUT" : "POST",+ body: JSON.stringify(data),+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (res.ok) {+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/presets`);+ setIsLoading(false);+ toast.success("Presets updated successfully");+ mutatePreset();+ }+ };++ const handleDelete = async () => {+ setIsLoading(true);+ const res = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (res.ok) {+ setData({+ metaImage: null,+ metaTitle: null,+ metaDescription: null,+ enableCustomMetatag: false,+ });+ setIsLoading(false);+ toast.success("Preset reset successfully");+ mutatePreset();+ }+ };++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <SettingsHeader />+ <div>+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">+ <div className="space-y-1">+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">+ Link Presets+ </h3>+ <p className="text-sm text-muted-foreground">+ Configure your default link settings.+ </p>+ </div>+ </div>+ <div className="grid w-full gap-x-8 divide-x divide-border overflow-auto scrollbar-hide md:grid-cols-2 md:overflow-hidden">+ <div className="scrollbar-hide md:max-h-[95vh] md:overflow-auto">+ <div className="sticky top-0 z-10 flex h-10 items-center justify-center border-b border-border px-5 sm:h-14">+ <h2 className="text-lg font-medium">Social Media Card</h2>+ </div>+ <div className="relative mt-4 space-y-3 rounded-md">+ <div>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-foreground">+ Image+ </p>+ {fileError ? (+ <p className="text-sm text-red-500">{fileError}</p>+ ) : null}+ </div>+ <label+ htmlFor="image"+ className="group relative mt-1 flex aspect-[1200/630] h-full min-h-[250px] cursor-pointer flex-col items-center justify-center rounded-md border border-input bg-white shadow-sm transition-all hover:border-muted-foreground hover:bg-gray-50 hover:ring-muted-foreground dark:bg-gray-800 hover:dark:bg-transparent"+ >+ {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={async (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 image = await resizeImage(file);+ setData((prev) => ({+ ...prev,+ metaImage: image,+ }));+ }+ }+ }}+ />+ <div+ className={cn(+ "absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md transition-all",+ dragActive &&+ "cursor-copy border-2 border-black bg-gray-50 opacity-100 dark:bg-transparent",+ data.metaImage+ ? "opacity-0 group-hover:opacity-100"+ : "group-hover:bg-gray-50 group-hover:dark:bg-transparent",+ )}+ >+ <ArrowUpTrayIcon+ className={cn(+ "h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95",+ dragActive ? "scale-110" : "scale-100",+ )}+ />+ <p className="mt-2 text-center text-sm text-gray-500">+ Drag and drop or click to upload.+ </p>+ <p className="mt-2 text-center text-sm text-gray-500">+ Recommended: 1200 x 630 pixels (max 5MB)+ </p>+ <span className="sr-only">OG image upload</span>+ </div>+ {data.metaImage && (+ <img+ src={data.metaImage}+ alt="Preview"+ className="aspect-[1200/630] h-full w-full rounded-md object-cover"+ />+ )}+ </label>+ <div className="mt-1 flex rounded-md shadow-sm">+ <input+ id="image"+ name="image"+ type="file"+ accept="image/*"+ className="sr-only"+ onChange={onChangePicture}+ />+ </div>+ </div>++ <div>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-foreground">+ Title+ </p>+ <p className="text-sm text-muted-foreground">+ {data.metaTitle?.length || 0}/120+ </p>+ </div>+ <div className="relative mt-1 flex rounded-md shadow-sm">+ {false && (+ <div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">+ <LoadingSpinner />+ </div>+ )}+ <Input+ name="title"+ id="title"+ maxLength={120}+ className="focus:ring-inset"+ placeholder={`Papermark - open-source document sharing infrastructure.`}+ value={data.metaTitle || ""}+ onChange={(e) => {+ setData({ ...data, metaTitle: e.target.value });+ }}+ aria-invalid="true"+ />+ </div>+ </div>++ <div>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-foreground">+ Description+ </p>+ <p className="text-sm text-muted-foreground">+ {data.metaDescription?.length || 0}/240+ </p>+ </div>+ <div className="relative mt-1 flex rounded-md shadow-sm">+ {false && (+ <div className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white">+ <LoadingSpinner />+ </div>+ )}+ <Textarea+ name="description"+ id="description"+ rows={3}+ maxLength={240}+ className="focus:ring-inset"+ placeholder={`Papermark is an open-source document sharing infrastructure for modern teams.`}+ value={data.metaDescription || ""}+ onChange={(e) => {+ setData({+ ...data,+ metaDescription: e.target.value,+ });+ }}+ aria-invalid="true"+ />+ </div>+ </div>++ <div className="flex justify-end">+ {plan === "free" ? (+ <UpgradePlanModal+ clickedPlan="Pro"+ trigger={"branding_page"}+ >+ <Button>Upgrade to Save Preset</Button>+ </UpgradePlanModal>+ ) : (+ <Button onClick={handleSavePreset} loading={isLoading}>+ Save Preset+ </Button>+ )}++ {presets ? (+ <Button+ variant="link"+ onClick={handleDelete}+ className="ml-2"+ loading={isLoading}+ >+ Reset+ </Button>+ ) : null}+ </div>+ </div>+ </div>+ <div className="scrollbar-hide md:max-h-[95vh] md:overflow-auto">+ <Preview data={data} setData={setData} />+ </div>+ </div>+ </div>+ </main>+ </AppLayout>+ );+}diff --git a/prisma/migrations/20240902000000_add_link_presets/migration.sql b/prisma/migrations/20240902000000_add_link_presets/migration.sqlnew file mode 100644index 00000000..f7469627--- /dev/null+++ b/prisma/migrations/20240902000000_add_link_presets/migration.sql@@ -0,0 +1,21 @@+-- CreateTable+CREATE TABLE "LinkPreset" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "teamId" TEXT NOT NULL,+ "enableCustomMetaTag" BOOLEAN DEFAULT false,+ "metaTitle" TEXT,+ "metaDescription" TEXT,+ "metaImage" TEXT,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "LinkPreset_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "LinkPreset_teamId_idx" ON "LinkPreset"("teamId");++-- AddForeignKey+ALTER TABLE "LinkPreset" ADD CONSTRAINT "LinkPreset_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 2a2ad913..71f872bf 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -76,6 +76,8 @@ model Team {startsAt DateTime? // Stripe subscription start dateendsAt DateTime? // Stripe subscription end date+ linkPresets LinkPreset[] // Link presets for the team+limits Json? // Plan limits // {datarooms: 1, users: 1, domains: 1, customDomainOnPro: boolean, customDomainInDataroom: boolean}createdAt DateTime @default(now())@@ -244,6 +246,23 @@ model Link {@@index([documentId])}+model LinkPreset {+ id String @id @default(cuid())+ name String+ teamId String+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)++ enableCustomMetaTag Boolean? @default(false) // Optional give user a option to enable the custom metatag+ metaTitle String? // This will be the meta title of the link+ metaDescription String? // This will be the meta description of the link+ metaImage String? // This will be the meta image of the link++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([teamId])+}+model Domain {id String @id @default(cuid())slug String @uniquediff --git a/tailwind.config.js b/tailwind.config.jsindex 8cd5415f..55903688 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -239,5 +239,6 @@ module.exports = {require("@tailwindcss/forms"),require("tailwindcss-animate"),require("@tailwindcss/typography"),+ require("tailwind-scrollbar-hide"),],};