Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Preset Option
Ashish Viradiya790975d6d526
diff --git a/components/links/link-sheet/agreement-panel/index.tsx b/components/links/link-sheet/agreement-panel/index.tsxindex bae76183..34ae635c 100644--- a/components/links/link-sheet/agreement-panel/index.tsx+++ b/components/links/link-sheet/agreement-panel/index.tsx@@ -34,23 +34,52 @@ import { getSupportedContentType } from "@/lib/utils/get-content-type";import LinkItem from "../link-item";export default function AgreementSheet({+ defaultData,isOpen,setIsOpen,+ isOnlyView = false,+ onClose,}: {+ defaultData?: { name: string; link: string; requireName: boolean } | null;isOpen: boolean;setIsOpen: Dispatch<SetStateAction<boolean>>;+ isOnlyView?: boolean;+ onClose?: () => void;}) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;const [data, setData] = useState({ name: "", link: "", requireName: true });const [isLoading, setIsLoading] = useState<boolean>(false);const [currentFile, setCurrentFile] = useState<File | null>(null);- const [currentLink, setCurrentLink] = useState<string | null>(null);++ useEffect(() => {+ if (defaultData) {+ setData({+ name: defaultData?.name || "",+ link: defaultData?.link || "",+ requireName: defaultData?.requireName || true,+ });+ }+ }, [defaultData]);++ const handleClose = (open: boolean) => {+ setIsOpen(open);+ setData({ name: "", link: "", requireName: true });+ setCurrentFile(null);+ setIsLoading(false);+ if (onClose) {+ onClose();+ }+ };const handleBrowserUpload = async () => {// event.preventDefault();// event.stopPropagation();-+ if (isOnlyView) {+ handleClose(false);+ toast.error("Cannot upload file in view mode!");+ return;+ }// Check if the file is chosenif (!currentFile) {toast.error("Please select a file to upload.");@@ -112,6 +141,11 @@ export default function AgreementSheet({const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {e.preventDefault();e.stopPropagation();+ if (isOnlyView) {+ handleClose(false);+ toast.error("Agreement cannot be created in view mode");+ return;+ }setIsLoading(true);@@ -151,13 +185,15 @@ export default function AgreementSheet({}, [currentFile]);return (- <Sheet open={isOpen} onOpenChange={setIsOpen}>+ <Sheet open={isOpen} onOpenChange={handleClose}><SheetContent className="flex h-full w-[85%] flex-col justify-between bg-background px-4 text-foreground sm:w-[500px] md:px-5"><SheetHeader className="text-start">- <SheetTitle>Create a new agreement</SheetTitle>+ <SheetTitle>{isOnlyView ? "View Agreement" : "Create a new agreement"}</SheetTitle><SheetDescription>- An agreement is a special document that visitors must accept before- accessing your link. You can create a new agreement here.+ {isOnlyView+ ? "View the details of this agreement."+ : "An agreement is a special document that visitors must accept before accessing your link. You can create a new agreement here."+ }</SheetDescription></SheetHeader>@@ -182,6 +218,7 @@ export default function AgreementSheet({name: e.target.value,})}+ disabled={isOnlyView}/></div>@@ -192,6 +229,7 @@ export default function AgreementSheet({action={() =>setData({ ...data, requireName: !data.requireName })}+ isAllowed={!isOnlyView}/></div>@@ -220,10 +258,11 @@ export default function AgreementSheet({"Please enter a valid URL starting with https://",)}+ disabled={isOnlyView}/></div>- <div className="space-y-12">+ {!isOnlyView ? <div className="space-y-12"><div className="space-y-2 pb-6"><Label>Or upload an agreement</Label><div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">@@ -233,15 +272,20 @@ export default function AgreementSheet({/></div></div>- </div>+ </div> : null}</div></div>-- <SheetFooter className="flex-shrink-0">+ <SheetFooter className={`flex-shrink-0 ${isOnlyView ? "mt-6" : ""}`}><div className="flex items-center">- <Button type="submit" loading={isLoading}>- Create Agreement- </Button>+ {isOnlyView ? (+ <Button type="button" onClick={() => handleClose(false)}>+ Close+ </Button>+ ) : (+ <Button type="submit" loading={isLoading}>+ Create Agreement+ </Button>+ )}</div></SheetFooter></form>diff --git a/components/links/link-sheet/allow-list-section.tsx b/components/links/link-sheet/allow-list-section.tsxindex b63a183f..37b102f4 100644--- a/components/links/link-sheet/allow-list-section.tsx+++ b/components/links/link-sheet/allow-list-section.tsx@@ -10,12 +10,14 @@ import { sanitizeAllowDenyList } from "@/lib/utils";import { DEFAULT_LINK_TYPE } from ".";import LinkItem from "./link-item";import { LinkUpgradeOptions } from "./link-options";+import { LinkPreset } from "@prisma/client";export default function AllowListSection({data,setData,isAllowed,handleUpgradeStateChange,+ presets,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;@@ -25,6 +27,7 @@ export default function AllowListSection({trigger,plan,}: LinkUpgradeOptions) => void;+ presets: LinkPreset | null;}) {const { emailProtected, allowList } = data;@@ -36,6 +39,13 @@ export default function AllowListSection({allowList?.join("\n") || "",);+ useEffect(() => {+ if (isAllowed && presets?.enableAllowList) {+ setEnabled(true);+ setAllowListInput(presets.allowList?.join("\n") || "");+ }+ }, [presets, isAllowed]);+useEffect(() => {// Update the allowList in the data state when their inputs changeconst newAllowList = sanitizeAllowDenyList(allowListInput);@@ -99,7 +109,9 @@ export default function AllowListSection({<TextareaclassName="focus:ring-inset"rows={5}- placeholder="Enter allowed emails/domains, one per line, e.g. [email protected] @example.org"+ placeholder={`Enter allowed emails/domains, one per line, e.g.value={allowListInput}onChange={handleAllowListChange}/>diff --git a/components/links/link-sheet/custom-fields-panel/custom-field.tsx b/components/links/link-sheet/custom-fields-panel/custom-field.tsxindex 2a6d565b..09394a7b 100644--- a/components/links/link-sheet/custom-fields-panel/custom-field.tsx+++ b/components/links/link-sheet/custom-fields-panel/custom-field.tsx@@ -1,6 +1,6 @@-import { useEffect, useState } from "react";+import { useEffect, useState, useCallback, memo } from "react";-import { ChevronDown, ChevronUp, Trash2 } from "lucide-react";+import { Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -26,7 +26,7 @@ interface CustomFieldProps {isLast?: boolean;}-export default function CustomField({+export default memo(function CustomField({field,onUpdate,onDelete,@@ -39,7 +39,7 @@ export default function CustomField({useEffect(() => {onUpdate(localField);- }, [localField, onUpdate]);+ }, [localField]);const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>,@@ -166,4 +166,4 @@ export default function CustomField({</div></div>);-}+});diff --git a/components/links/link-sheet/custom-fields-panel/index.tsx b/components/links/link-sheet/custom-fields-panel/index.tsxindex 20c71a17..80c88c4a 100644--- a/components/links/link-sheet/custom-fields-panel/index.tsx+++ b/components/links/link-sheet/custom-fields-panel/index.tsx@@ -1,6 +1,7 @@import { CustomField, CustomFieldType } from "@prisma/client";import { Plus } from "lucide-react";import { toast } from "sonner";+import { useCallback, useMemo } from "react";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";@@ -40,14 +41,13 @@ export default function CustomFieldsPanel({}) {const { isDatarooms, isDataroomsPlus, isBusiness } = usePlan();- const getFieldLimit = () => {+ const fieldLimit = useMemo(() => {if (isDatarooms || isDataroomsPlus) return 3;if (isBusiness) return 1;return 0;- };+ }, [isDatarooms, isDataroomsPlus, isBusiness]);- const addField = () => {- const fieldLimit = getFieldLimit();+ const addField = useCallback(() => {if (fields.length >= fieldLimit) {toast.error(`You can only add up to ${fieldLimit} custom field${fieldLimit === 1 ? "" : "s"} on the ${isDatarooms ? "Data Rooms" : "Business"} plan`,@@ -65,24 +65,24 @@ export default function CustomFieldsPanel({orderIndex: fields.length,};onChange([...fields, newField]);- };+ }, [fields, fieldLimit, isDatarooms, onChange]);- const updateField = (index: number, updatedField: CustomFieldData) => {+ const updateField = useCallback((index: number, updatedField: CustomFieldData) => {const newFields = [...fields];newFields[index] = updatedField;onChange(newFields);- };+ }, [fields, onChange]);- const removeField = (index: number) => {+ const removeField = useCallback((index: number) => {const newFields = fields.filter((_, i) => i !== index);// Update orderIndex for remaining fieldsnewFields.forEach((field, i) => {field.orderIndex = i;});onChange(newFields);- };+ }, [fields, onChange]);- const moveField = (index: number, direction: "up" | "down") => {+ const moveField = useCallback((index: number, direction: "up" | "down") => {if ((direction === "up" && index === 0) ||(direction === "down" && index === fields.length - 1)@@ -102,9 +102,7 @@ export default function CustomFieldsPanel({});onChange(newFields);- };-- const fieldLimit = getFieldLimit();+ }, [fields, onChange]);return (<Sheet open={isConfigOpen} onOpenChange={setIsConfigOpen}>diff --git a/components/links/link-sheet/custom-fields-section.tsx b/components/links/link-sheet/custom-fields-section.tsxindex 9a44ceb1..3aaf0f01 100644--- a/components/links/link-sheet/custom-fields-section.tsx+++ b/components/links/link-sheet/custom-fields-section.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useState, useCallback, useMemo } from "react";import { SettingsIcon } from "lucide-react";import { motion } from "motion/react";@@ -12,52 +12,70 @@ import { CustomFieldData } from "./custom-fields-panel";import CustomFieldsPanel from "./custom-fields-panel";import LinkItem from "./link-item";import { LinkUpgradeOptions } from "./link-options";+import { LinkPreset } from "@prisma/client";export default function CustomFieldsSection({data,setData,isAllowed,handleUpgradeStateChange,+ presets,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;isAllowed: boolean;handleUpgradeStateChange: (options: LinkUpgradeOptions) => void;+ presets: LinkPreset | null;}) {const [enabled, setEnabled] = useState<boolean>(false);const [isConfigOpen, setIsConfigOpen] = useState<boolean>(false);useEffect(() => {- setEnabled(data.customFields.length > 0);- }, [data.customFields]);+ if (isAllowed && presets?.watermarkConfig) {+ setEnabled(true);+ setData((prevData) => ({+ ...prevData,+ customFields: presets.customFields ? JSON.parse(presets.customFields as string) as CustomFieldData[] : [],+ }));+ }+ }, [presets, isAllowed]);- const handleCustomFieldsToggle = () => {+ useEffect(() => {+ const hasCustomFields = data.customFields.length > 0;+ if (enabled !== hasCustomFields) {+ setEnabled(hasCustomFields);+ }+ }, [data.customFields, enabled]);++ const handleCustomFieldsToggle = useCallback(() => {const updatedEnabled = !enabled;- setData({- ...data,+ setData(prevData => ({+ ...prevData,customFields: updatedEnabled? [- {- type: "SHORT_TEXT",- identifier: "",- label: "",- placeholder: "",- required: false,- disabled: false,- orderIndex: 0,- },- ]+ {+ type: "SHORT_TEXT",+ identifier: "",+ label: "",+ placeholder: "",+ required: false,+ disabled: false,+ orderIndex: 0,+ },+ ]: [],- });+ }));setEnabled(updatedEnabled);- };+ }, [enabled, setData]);- const handleConfigSave = (fields: CustomFieldData[]) => {- setData({- ...data,+ const handleConfigSave = useCallback((fields: CustomFieldData[]) => {+ setData(prevData => ({+ ...prevData,customFields: fields,- });- };+ }));+ }, [setData]);++ const memoizedFields = useMemo(() => data.customFields || [], [data.customFields]);return (<div className="pb-5">@@ -84,7 +102,7 @@ export default function CustomFieldsSection({><div className="mt-2 flex w-full items-center justify-between"><div className="space-y-1">- {data.customFields.map((field) => (+ {memoizedFields.map((field) => (<pkey={field.identifier || field.orderIndex}className="text-sm text-muted-foreground"@@ -114,11 +132,11 @@ export default function CustomFieldsSection({)}<CustomFieldsPanel- fields={data.customFields}+ fields={memoizedFields}onChange={handleConfigSave}isConfigOpen={isConfigOpen}setIsConfigOpen={setIsConfigOpen}/></div>);-}+};\ No newline at end of filediff --git a/components/links/link-sheet/deny-list-section.tsx b/components/links/link-sheet/deny-list-section.tsxindex fffb1168..a260dc7e 100644--- a/components/links/link-sheet/deny-list-section.tsx+++ b/components/links/link-sheet/deny-list-section.tsx@@ -10,12 +10,14 @@ import { sanitizeAllowDenyList } from "@/lib/utils";import { DEFAULT_LINK_TYPE } from ".";import LinkItem from "./link-item";import { LinkUpgradeOptions } from "./link-options";+import { LinkPreset } from "@prisma/client";export default function DenyListSection({data,setData,isAllowed,handleUpgradeStateChange,+ presets,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;@@ -26,6 +28,7 @@ export default function DenyListSection({trigger,plan,}: LinkUpgradeOptions) => void;+ presets: LinkPreset | null;}) {const { emailProtected, denyList } = data;// Initialize enabled state based on whether denyList is not null and not empty@@ -36,6 +39,13 @@ export default function DenyListSection({denyList?.join("\n") || "",);+ useEffect(() => {+ if (isAllowed && presets?.enableDenyList) {+ setEnabled(true);+ setDenyListInput(presets.denyList?.join("\n") || "");+ }+ }, [presets, isAllowed]);+useEffect(() => {// Update the denyList in the data state when their inputs changeconst newDenyList = sanitizeAllowDenyList(denyListInput);@@ -99,7 +109,9 @@ export default function DenyListSection({<TextareaclassName="focus:ring-inset"rows={5}- placeholder="Enter blocked emails/domains, one per line, e.g. [email protected] @example.org"+ placeholder={`Enter blocked emails/domains, one per line, e.g.value={denyListInput}onChange={handleDenyListChange}/>diff --git a/components/links/link-sheet/link-options.tsx b/components/links/link-sheet/link-options.tsxindex e6b8ee2c..f81e42f4 100644--- a/components/links/link-sheet/link-options.tsx+++ b/components/links/link-sheet/link-options.tsx@@ -25,6 +25,10 @@ import CustomFieldsSection from "./custom-fields-section";import QuestionSection from "./question-section";import ScreenshotProtectionSection from "./screenshot-protection-section";import WatermarkSection from "./watermark-section";+import useSWRImmutable from "swr/immutable";+import { LinkPreset } from "@prisma/client";+import { fetcher } from "@/lib/utils";+import { useTeam } from "@/context/team-context";export type LinkUpgradeOptions = {state: boolean;@@ -51,8 +55,13 @@ export const LinkOptions = ({isDataroomsPlus,isTrial,} = usePlan();+ const teamInfo = useTeam();+ console.log('data?.id', data?.id)+ const { data: presets } = useSWRImmutable<LinkPreset>(+ `/api/teams/${teamInfo?.currentTeam?.id}/presets`,+ fetcher,+ );const { limits } = useLimits();-const allowAdvancedLinkControls = limits? limits?.advancedLinkControlsOnPro: false;@@ -73,6 +82,7 @@ export const LinkOptions = ({setUpgradePlan(plan as PlanEnum);}};+ const presetsData = editLink ? null : presets!;return (<div>@@ -82,6 +92,7 @@ export const LinkOptions = ({<ExpirationSection {...{ data, setData }} /><OGSection{...{ data, setData }}+ presets={presetsData}isAllowed={isTrial ||(isPro && allowAdvancedLinkControls) ||@@ -107,6 +118,7 @@ export const LinkOptions = ({{data.audienceType === LinkAudienceType.GENERAL ? (<AllowListSection{...{ data, setData }}+ presets={presetsData}isAllowed={isTrial ||(isPro && allowAdvancedLinkControls) ||@@ -127,6 +139,7 @@ export const LinkOptions = ({isDatarooms ||isDataroomsPlus}+ presets={presetsData}handleUpgradeStateChange={handleUpgradeStateChange}/>) : null}@@ -147,6 +160,7 @@ export const LinkOptions = ({isAllowed={isTrial || isDatarooms || isDataroomsPlus || allowWatermarkOnBusiness}+ presets={presetsData}handleUpgradeStateChange={handleUpgradeStateChange}/><AgreementSection@@ -174,6 +188,7 @@ export const LinkOptions = ({) : null}<CustomFieldsSection{...{ data, setData }}+ presets={presetsData}isAllowed={isTrial || isBusiness || isDatarooms || isDataroomsPlus}handleUpgradeStateChange={handleUpgradeStateChange}/>diff --git a/components/links/link-sheet/og-section.tsx b/components/links/link-sheet/og-section.tsxindex 8cb009fc..8b6955b9 100644--- a/components/links/link-sheet/og-section.tsx+++ b/components/links/link-sheet/og-section.tsx@@ -1,11 +1,9 @@import { ChangeEvent, useCallback, useEffect, useState } from "react";-import { useTeam } from "@/context/team-context";import { LinkPreset } from "@prisma/client";import { Label } from "@radix-ui/react-label";import { Upload as ArrowUpTrayIcon, PlusIcon } from "lucide-react";import { motion } from "motion/react";-import useSWRImmutable from "swr/immutable";import { Input } from "@/components/ui/input";import LoadingSpinner from "@/components/ui/loading-spinner";@@ -25,6 +23,7 @@ export default function OGSection({isAllowed,handleUpgradeStateChange,editLink,+ presets,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;@@ -35,6 +34,7 @@ export default function OGSection({plan,}: LinkUpgradeOptions) => void;editLink: boolean;+ presets: LinkPreset | null;}) {const {enableCustomMetatag,@@ -43,12 +43,12 @@ export default function OGSection({metaImage,metaFavicon,} = data;- const teamInfo = useTeam();- const { data: presets } = useSWRImmutable<LinkPreset>(- `/api/teams/${teamInfo?.currentTeam?.id}/presets`,- fetcher,- );+ console.log(enableCustomMetatag,+ metaTitle,+ metaDescription,+ metaImage,+ metaFavicon, 'presets')const [enabled, setEnabled] = useState<boolean>(false);const [fileError, setFileError] = useState<string | null>(null);const [dragActive, setDragActive] = useState(false);@@ -82,7 +82,7 @@ export default function OGSection({useEffect(() => {if (- presets &&+ presets?.enableCustomMetaTag &&!(metaTitle || metaDescription || metaImage || metaFavicon)) {const preset = presets;diff --git a/components/links/link-sheet/watermark-section.tsx b/components/links/link-sheet/watermark-section.tsxindex 4e44ded7..ee2b865a 100644--- a/components/links/link-sheet/watermark-section.tsx+++ b/components/links/link-sheet/watermark-section.tsx@@ -14,16 +14,19 @@ import { DEFAULT_LINK_TYPE } from ".";import LinkItem from "./link-item";import { LinkUpgradeOptions } from "./link-options";import WatermarkConfigSheet from "./watermark-panel";+import { LinkPreset } from "@prisma/client";export default function WatermarkSection({data,setData,isAllowed,handleUpgradeStateChange,+ presets,}: {data: DEFAULT_LINK_TYPE;setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;isAllowed: boolean;+ presets: LinkPreset | null;handleUpgradeStateChange: ({state,trigger,@@ -34,6 +37,17 @@ export default function WatermarkSection({const [enabled, setEnabled] = useState<boolean>(false);const [isConfigOpen, setIsConfigOpen] = useState<boolean>(false);+ useEffect(() => {+ if (isAllowed && presets?.watermarkConfig) {+ setEnabled(true);+ setData((prevData) => ({+ ...prevData,+ enableWatermark: true,+ watermarkConfig: presets.watermarkConfig ? JSON.parse(presets.watermarkConfig as string) as WatermarkConfig : null,+ }));+ }+ }, [presets, isAllowed]);+useEffect(() => {setEnabled(enableWatermark);}, [enableWatermark]);diff --git a/components/settings/og-preview.tsx b/components/settings/og-preview.tsxindex efcd4835..2d35de21 100644--- a/components/settings/og-preview.tsx+++ b/components/settings/og-preview.tsx@@ -6,25 +6,15 @@ import ReactTextareaAutosize from "react-textarea-autosize";import { Facebook } from "../shared/icons/facebook";import LinkedIn from "../shared/icons/linkedin";import Twitter from "../shared/icons/twitter";+import { PresetData } from "@/pages/settings/presets";+export default function Preview({data,setData,}: {- data: {- metaImage: string | null;- metaTitle: string | null;- metaDescription: string | null;- metaFavicon: string | null;- };- setData: Dispatch<- SetStateAction<{- metaImage: string | null;- metaTitle: string | null;- metaDescription: string | null;- metaFavicon: string | null;- }>- >;+ data: PresetData;+ setData: Dispatch<SetStateAction<PresetData>>;}) {const {metaTitle: title,diff --git a/components/settings/presets/preset-options.tsx b/components/settings/presets/preset-options.tsxnew file mode 100644index 00000000..2aa1fe25--- /dev/null+++ b/components/settings/presets/preset-options.tsx@@ -0,0 +1,524 @@+import { Dispatch, SetStateAction, useCallback, useState, useMemo, useEffect } from "react";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { Label } from "@/components/ui/label";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { BadgeTooltip } from "@/components/ui/tooltip";+import { CircleHelpIcon, PlusIcon, MoreVertical, Pencil, Trash2, SettingsIcon } from "lucide-react";+import { PresetData } from "@/pages/settings/presets";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";+import { motion } from "motion/react";+import LinkItem from "@/components/links/link-sheet/link-item";+import { PlanEnum } from "@/ee/stripe/constants";+import { LinkUpgradeOptions } from "@/components/links/link-sheet/link-options";+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";+import AgreementSheet from "@/components/links/link-sheet/agreement-panel";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Checkbox } from "@/components/ui/checkbox";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { format } from "date-fns";+import { Badge } from "@/components/ui/badge";+import CustomFieldsPanel, { CustomFieldData } from "@/components/links/link-sheet/custom-fields-panel";+import { WatermarkConfig } from "@/lib/types";+import WatermarkConfigSheet from "@/components/links/link-sheet/watermark-panel";+import { Agreement } from "@prisma/client";+import { cn, sanitizeAllowDenyList } from "@/lib/utils";+import PlanBadge from "@/components/billing/plan-badge";+interface PresetOptionsProps {+ data: PresetData;+ setData: Dispatch<SetStateAction<PresetData>>;+ agreements: (Agreement & { _count: { links: number } })[];+};++export default function PresetOptions({ data, setData, agreements }: PresetOptionsProps) {+ const { watermarkConfig } = data;+ const [openUpgradeModal, setOpenUpgradeModal] = useState(false);+ const [trigger, setTrigger] = useState("");+ const [isConfigOpen, setIsConfigOpen] = useState(false);+ const [isWatermarkConfigOpen, setIsWatermarkConfigOpen] = useState(false);+ const [isAgreementSheetVisible, setIsAgreementSheetVisible] =+ useState<boolean>(false);+ const [selectedAgreement, setSelectedAgreement] = useState<Agreement | null>(null);+ const [upgradePlan, setUpgradePlan] = useState<PlanEnum>(PlanEnum.Business);+ const [denyListInput, setDenyListInput] = useState<string>(+ data.denyList?.join("\n") || "",+ );+ const [allowListInput, setAllowListInput] = useState<string>(+ data.allowList?.join("\n") || "",+ );++ useEffect(() => {+ if (!denyListInput) {+ setDenyListInput(data.denyList?.join("\n") || "");+ }+ if (!allowListInput) {+ setAllowListInput(data.allowList?.join("\n") || "");+ }+ }, [data.denyList, data.allowList]);++ useEffect(() => {+ const timer = setTimeout(() => {+ const newDenyList = sanitizeAllowDenyList(denyListInput);+ const newAllowList = sanitizeAllowDenyList(allowListInput);+ setData((prevData) => ({+ ...prevData,+ denyList: newDenyList,+ allowList: newAllowList,+ }));+ }, 500);++ return () => clearTimeout(timer);+ }, [denyListInput, allowListInput, setData]);++ const handleCustomFieldsToggle = useCallback(() => {+ setData(prevData => {+ const updatedEnabled = !prevData.enableCustomFields;+ return {+ ...prevData,+ enableCustomFields: updatedEnabled,+ customFields: updatedEnabled+ ? [+ {+ type: "SHORT_TEXT",+ identifier: "",+ label: "",+ placeholder: "",+ required: false,+ disabled: false,+ orderIndex: 0,+ },+ ]+ : [],+ };+ });+ }, [setData]);++ const handleAllowListToggle = useCallback(() => {+ setData(prevData => ({+ ...prevData,+ enableAllowList: !prevData.enableAllowList,+ allowList: prevData.enableAllowList ? [] : data.allowList,+ }));+ }, [setData]);++ const handleDenyListToggle = useCallback(() => {+ setData(prevData => ({+ ...prevData,+ enableDenyList: !prevData.enableDenyList,+ denyList: prevData.enableDenyList ? [] : data.denyList,+ }));+ }, [setData]);++ const handleWatermarkToggle = useCallback(() => {+ setData(prevData => ({+ ...prevData,+ enableWatermark: !prevData.enableWatermark,+ watermarkConfig: prevData.enableWatermark ? null : data.watermarkConfig,+ }));+ }, [setData]);++ const handleToggle = useCallback((field: keyof PresetData) => {+ if (field === "enableCustomFields") {+ handleCustomFieldsToggle();+ return;+ }+ if (field === "enableAllowList") {+ handleAllowListToggle();+ return;+ }+ if (field === "enableDenyList") {+ handleDenyListToggle();+ return;+ }+ if (field === "enableWatermark") {+ handleWatermarkToggle();+ return;+ }+ setData(prevData => ({+ ...prevData,+ [field]: !prevData[field],+ }));+ }, [handleCustomFieldsToggle, handleAllowListToggle, handleDenyListToggle, setData]);++ const handleUpgradeStateChange = ({+ state,+ trigger,+ plan,+ }: LinkUpgradeOptions) => {+ setOpenUpgradeModal(state);+ setTrigger(trigger);+ if (plan) {+ setUpgradePlan(plan as PlanEnum);+ }+ };++ const handleConfigSave = useCallback((fields: CustomFieldData[]) => {+ setData(prevData => ({+ ...prevData,+ customFields: fields,+ }));+ }, [setData]);++ const handleWatermarkConfigSave = (config: WatermarkConfig) => {+ setData({+ ...data,+ watermarkConfig: config,+ });+ };++ const initialConfig: WatermarkConfig = {+ text: watermarkConfig?.text ?? "",+ isTiled: watermarkConfig?.isTiled ?? false,+ opacity: watermarkConfig?.opacity ?? 0.5,+ color: watermarkConfig?.color ?? "#000000",+ fontSize: watermarkConfig?.fontSize ?? 24,+ rotation: (watermarkConfig?.rotation ?? 45) as 0 | 30 | 45 | 90 | 180,+ position: (watermarkConfig?.position ?? "middle-center") as "top-left" | "top-center" | "top-right" | "middle-left" | "middle-center" | "middle-right" | "bottom-left" | "bottom-center" | "bottom-right",+ };++ const memoizedFields = useMemo(() => data.customFields || [], [data.customFields]);++ return (+ <div className="space-y-6">+ <Card>+ <CardHeader>+ <CardTitle>Custom Fields</CardTitle>+ <CardDescription>Add custom fields to collect additional information from viewers</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <LinkItem+ title="Custom Fields"+ tooltipContent="Add custom fields to collect additional information from viewers"+ enabled={data.enableCustomFields}+ action={() => handleToggle("enableCustomFields")}+ isAllowed={true}+ requiredPlan="business"+ upgradeAction={() =>+ handleUpgradeStateChange({+ state: true,+ trigger: "custom_fields",+ plan: "Business",+ })+ }+ />+ {data.enableCustomFields && (+ <motion.div+ className="relative mt-4 space-y-3"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <div className="mt-2 flex w-full items-center justify-between">+ <div className="space-y-1">+ {memoizedFields.map((field, index) => (+ <p+ key={`${field.orderIndex}-${index}`}+ className="text-sm text-muted-foreground"+ >+ {field.orderIndex + 1}. {field.label || "Untitled Field"}+ {field.required && (+ <span className="italic"> (required)</span>+ )}+ </p>+ ))}+ </div>+ <Button+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setIsConfigOpen(true);+ }}+ variant="outline"+ className="h-8"+ size="sm"+ >+ <SettingsIcon className="mr-2 h-4 w-4" />+ Configure+ </Button>+ </div>+ </motion.div>+ )}++ <CustomFieldsPanel+ fields={memoizedFields}+ onChange={handleConfigSave}+ isConfigOpen={isConfigOpen}+ setIsConfigOpen={setIsConfigOpen}+ />+ </CardContent>+ </Card>+ <Card>+ <CardHeader>+ <div className="flex items-center justify-between">+ <CardTitle>NDA Requirement</CardTitle>+ <Button+ variant="default"+ size="icon"+ className="w-auto px-2"+ onClick={() => setIsAgreementSheetVisible(true)}+ >+ <PlusIcon className="h-4 w-4" /> Add Agreement+ </Button>+ </div>+ <CardDescription>Require viewers to accept an NDA before viewing</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <h2+ className={cn(+ "flex flex-1 cursor-pointer flex-row items-center gap-2 text-sm font-medium leading-6 text-foreground",+ )}+ >+ <span>Default NDA Agreement</span>+ <BadgeTooltip+ content="Require viewers to accept an NDA before viewing"+ key="link_tooltip"+ link="https://www.papermark.com/help/article/require-nda-to-view"+ >+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />+ </BadgeTooltip>+ </h2>+ {agreements?.length > 0 ? (+ <div className="mt-4 space-y-3">+ {agreements?.map((agreement) => (+ <Card key={agreement.id} onClick={() => {+ setIsAgreementSheetVisible(true);+ setSelectedAgreement(agreement);+ }}>+ <CardContent className="px-4 py-3">+ <div className="flex items-center justify-between">+ <div className="flex flex-col space-y-1">+ <Label htmlFor={agreement.id} className="cursor-pointer font-medium">+ {agreement.name}+ </Label>+ <div className="text-xs text-muted-foreground">+ Created on {format(+ new Date(agreement.createdAt),+ "MMM d, yyyy",+ )}+ </div>+ </div>+ <Badge variant="outline" className="flex items-center h-fit">+ {agreement._count.links} links+ </Badge>+ </div>+ </CardContent>+ </Card>+ ))}+ </div>+ ) : (+ <div className="mt-4 flex h-24 items-center justify-center rounded-md border border-dashed border-muted-foreground/25 bg-muted/10">+ <div className="flex flex-col items-center space-y-2 text-center">+ <p className="text-sm text-muted-foreground">No agreements found</p>+ <p className="text-xs text-muted-foreground">Create an agreement to require viewers to accept an NDA</p>+ </div>+ </div>+ )}+ <AgreementSheet+ isOpen={isAgreementSheetVisible}+ setIsOpen={setIsAgreementSheetVisible}+ isOnlyView={!!selectedAgreement}+ defaultData={selectedAgreement ? {+ name: selectedAgreement.name,+ link: selectedAgreement.content,+ requireName: selectedAgreement.requireName,+ } : null}+ onClose={() => {+ setIsAgreementSheetVisible(false);+ setSelectedAgreement(null);+ }}+ />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Watermark</CardTitle>+ <CardDescription>Apply a watermark to your documents</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <LinkItem+ title="Apply Watermark"+ link="https://www.papermark.com/help/article/document-watermark"+ tooltipContent="Add a dynamic watermark to your content."+ enabled={data.enableWatermark}+ action={() => handleToggle("enableWatermark")}+ isAllowed={true}+ requiredPlan="datarooms"+ upgradeAction={() =>+ handleUpgradeStateChange({+ state: true,+ trigger: "link_sheet_watermark_section",+ plan: "Data Rooms",+ })+ }+ />+ {data.enableWatermark && (+ <motion.div+ className="relative mt-4 space-y-3"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <div className="flex w-full flex-col items-start gap-6 overflow-x-visible pt-0">+ <div className="w-full space-y-2">+ <Label htmlFor="watermark-text">Watermark Text</Label>+ <Input+ id="watermark-text"+ type="text"+ name="text"+ placeholder="e.g. Confidential {{email}} {{date}}"+ value={data.watermarkConfig?.text ?? ""}+ required={data.enableWatermark}+ onChange={(e) => {+ setData((prevData) => ({+ ...prevData,+ watermarkConfig: {+ ...(data.watermarkConfig || initialConfig),+ text: e.target.value,+ },+ }));+ }}+ className="focus:ring-inset"+ />+ <div className="space-x-1 space-y-1">+ {["email", "date", "time", "link", "ipAddress"].map((item) => (+ <Button+ key={item}+ size="sm"+ variant="outline"+ className="h-7 rounded-3xl bg-muted text-sm font-normal text-foreground/80 hover:bg-muted/70"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setData((prevData) => ({+ ...prevData,+ watermarkConfig: {+ ...(prevData.watermarkConfig || initialConfig),+ text: `${prevData.watermarkConfig?.text || ""} {{${item}}}`,+ },+ }));+ }}+ >{`{{${item}}}`}</Button>+ ))}+ </div>+ </div>+ </div>++ <div className="mt-2 flex w-full items-center justify-between">+ <p className="text-sm text-muted-foreground">+ {initialConfig.isTiled ? `tiled` : initialConfig.position},{" "}+ {initialConfig.rotation}º, {initialConfig.fontSize}px,{" "}+ {initialConfig.color.toUpperCase()},{" "}+ {(1 - initialConfig.opacity) * 100}% transparent+ </p>+ <Button+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setIsWatermarkConfigOpen(true);+ }}+ variant="outline"+ className="h-8"+ size="sm"+ >+ <SettingsIcon className="mr-2 h-4 w-4" />+ Configure+ </Button>+ </div>+ </motion.div>+ )}++ <WatermarkConfigSheet+ isOpen={isWatermarkConfigOpen}+ onOpenChange={setIsWatermarkConfigOpen}+ initialConfig={initialConfig}+ onSave={handleWatermarkConfigSave}+ />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Viewer Access Control</CardTitle>+ <CardDescription>Control who can access your documents</CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <LinkItem+ title="Allow specified viewers"+ tooltipContent="Restrict access to a selected group of viewers. Enter allowed emails or domains."+ enabled={data.enableAllowList}+ link="https://www.papermark.com/help/article/allow-list"+ action={() => handleToggle("enableAllowList")}+ isAllowed={true}+ requiredPlan="business"+ upgradeAction={() =>+ handleUpgradeStateChange({+ state: true,+ trigger: "link_sheet_allowlist_section",+ plan: "Business",+ })+ }+ />+ {data.enableAllowList && (+ <motion.div+ className="mt-1 block w-full"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <Textarea+ className="focus:ring-inset"+ rows={5}+ placeholder={`Enter allowed emails/domains, one per line, e.g.+ value={allowListInput}+ onChange={(e) => setAllowListInput(e.target.value)}+ />+ </motion.div>+ )}+ <LinkItem+ title="Block specified viewers"+ tooltipContent="Prevent certain users from accessing the content. Enter blocked emails or domains."+ enabled={data.enableDenyList}+ link="https://www.papermark.com/help/article/block-list"+ action={() => handleToggle("enableDenyList")}+ isAllowed={true}+ requiredPlan="business"+ upgradeAction={() =>+ handleUpgradeStateChange({+ state: true,+ trigger: "link_sheet_denylist_section",+ plan: "Business",+ })+ }+ />+ {data.enableDenyList && (+ <motion.div+ className="mt-1 block w-full"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <Textarea+ className="focus:ring-inset"+ rows={5}+ placeholder={`Enter blocked emails/domains, one per line, e.g.+ value={denyListInput}+ onChange={(e) => setDenyListInput(e.target.value)}+ />+ </motion.div>+ )}+ </CardContent>+ </Card>++ <UpgradePlanModal+ clickedPlan={upgradePlan}+ open={openUpgradeModal}+ setOpen={setOpenUpgradeModal}+ trigger={trigger}+ />+ </div >+ );+}\ No newline at end of filediff --git a/components/settings/presets/social-media-card-preset.tsx b/components/settings/presets/social-media-card-preset.tsxnew file mode 100644index 00000000..dc86fa42--- /dev/null+++ b/components/settings/presets/social-media-card-preset.tsx@@ -0,0 +1,364 @@+import { ChangeEvent, useCallback, useState } from "react";+import { Upload as ArrowUpTrayIcon, PlusIcon } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import { cn } from "@/lib/utils";+import { resizeImage } from "@/lib/utils/resize-image";+import { validateImageDimensions } from "@/lib/utils";+import { PresetData } from "@/pages/settings/presets";++interface SocialMediaCardPresetProps {+ data: PresetData;+ setData: React.Dispatch<React.SetStateAction<PresetData>>;+}++export default function SocialMediaCardPreset({+ data,+ setData,+}: SocialMediaCardPresetProps) {+ const [fileError, setFileError] = useState<string | null>(null);+ const [faviconFileError, setFaviconFileError] = useState<string | null>(null);+ const [dragActive, setDragActive] = useState(false);+ const [faviconDragActive, setFaviconDragActive] = useState(false);++ 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" &&+ file.type !== "image/jpg"+ ) {+ setFileError("File type not supported (.png or .jpg only)");+ } else {+ const image = await resizeImage(file);+ setData((prev) => ({+ ...prev,+ metaImage: image,+ }));+ }+ }+ },+ [setData],+ );++ const onChangeFavicon = useCallback(+ async (e: ChangeEvent<HTMLInputElement>) => {+ setFaviconFileError(null);+ const file = e.target.files && e.target.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 1) {+ setFaviconFileError("File size too big (max 1MB)");+ } else if (+ file.type !== "image/png" &&+ file.type !== "image/x-icon" &&+ file.type !== "image/svg+xml"+ ) {+ setFaviconFileError(+ "File type not supported (.png, .ico, .svg only)",+ );+ } else {+ const image = await resizeImage(file, {+ width: 36,+ height: 36,+ quality: 1,+ });+ const isValidDimensions = await validateImageDimensions(+ image,+ 16,+ 48,+ );+ if (!isValidDimensions) {+ setFaviconFileError(+ "Image dimensions must be between 16x16 and 48x48",+ );+ } else {+ setData((prev) => ({+ ...prev,+ metaFavicon: image,+ }));+ }+ }+ }+ },+ [setData],+ );++ return (+ <div className="relative mt-5 space-y-3 rounded-md px-5">+ <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="mainImage"+ className="group relative mt-1 flex aspect-[1200/630] h-full 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"+ >+ <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" &&+ file.type !== "image/jpg"+ ) {+ 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="h-full w-full rounded-md object-cover"+ />+ )}+ </label>+ <div className="mt-1 hidden rounded-md shadow-sm">+ <input+ id="mainImage"+ name="image"+ type="file"+ accept="image/png,image/jpeg,image/jpg"+ className="sr-only"+ onChange={onChangePicture}+ />+ </div>+ </div>+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <Label htmlFor="faviconIcon">+ Favicon Icon{" "}+ <span className="text-sm italic text-muted-foreground">+ (max 1 MB)+ </span>+ </Label>+ {faviconFileError ? (+ <p className="text-sm text-red-500">{faviconFileError}</p>+ ) : null}+ </div>+ <label+ htmlFor="faviconIcon"+ className="group relative mt-1 flex size-14 cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"+ style={{+ backgroundImage:+ "linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(135deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(135deg, transparent 75%, #ccc 75%)",+ backgroundSize: "20px 20px",+ backgroundPosition: "0 0, 10px 0, 10px -10px, 0px 10px",+ }}+ >+ <div+ className="absolute z-[5] h-full w-full rounded-md"+ onDragOver={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setFaviconDragActive(true);+ }}+ onDragEnter={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setFaviconDragActive(true);+ }}+ onDragLeave={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setFaviconDragActive(false);+ }}+ onDrop={async (e) => {+ e.preventDefault();+ e.stopPropagation();+ setFaviconDragActive(false);+ setFaviconFileError(null);+ const file =+ e.dataTransfer.files && e.dataTransfer.files[0];+ if (file) {+ if (file.size / 1024 / 1024 > 1) {+ setFaviconFileError("File size too big (max 1MB)");+ } else if (+ file.type !== "image/png" &&+ file.type !== "image/x-icon" &&+ file.type !== "image/svg+xml"+ ) {+ setFaviconFileError(+ "File type not supported (.png, .ico, .svg only)",+ );+ } else {+ const image = await resizeImage(file, {+ width: 36,+ height: 36,+ quality: 1,+ });+ const isValidDimensions =+ await validateImageDimensions(image, 16, 48);+ if (!isValidDimensions) {+ setFaviconFileError(+ "Image dimensions must be between 16x16 and 48x48",+ );+ } else {+ setData((prev) => ({+ ...prev,+ metaFavicon: image,+ }));+ }+ }+ }+ }}+ />+ <div+ className={`${faviconDragActive+ ? "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 ${data.metaFavicon+ ? "opacity-0 group-hover:opacity-100"+ : "group-hover:bg-gray-50"+ }`}+ >+ <PlusIcon+ className={`${faviconDragActive ? "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>+ {data.metaFavicon && (+ <img+ src={data.metaFavicon}+ alt="Preview"+ className="h-full w-full rounded-md object-contain"+ />+ )}+ </label>+ <div className="mt-1 hidden rounded-md shadow-sm">+ <input+ id="faviconIcon"+ name="favicon"+ type="file"+ accept="image/png,image/x-icon,image/svg+xml"+ className="sr-only"+ onChange={onChangeFavicon}+ />+ </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">+ <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">+ <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>+ );+}\ No newline at end of filediff --git a/lib/swr/use-agreements.ts b/lib/swr/use-agreements.tsindex 8c00b915..08b13ece 100644--- a/lib/swr/use-agreements.ts+++ b/lib/swr/use-agreements.ts@@ -8,7 +8,7 @@ export function useAgreements() {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const { data: agreements, error } = useSWR<Agreement[]>(+ const { data: agreements, error } = useSWR<(Agreement & { _count: { links: number } })[]>(teamId && `/api/teams/${teamId}/agreements`,fetcher,{@@ -17,7 +17,7 @@ export function useAgreements() {);return {- agreements,+ agreements: agreements || [],loading: !agreements && !error,error,};diff --git a/lib/zod/schemas/presets.ts b/lib/zod/schemas/presets.tsnew file mode 100644index 00000000..fbdfd504--- /dev/null+++ b/lib/zod/schemas/presets.ts@@ -0,0 +1,47 @@+import { z } from "zod";++export const customFieldDataSchema = z.object({+ type: z.enum(["SHORT_TEXT", "LONG_TEXT", "NUMBER", "URL"]),+ identifier: z.string(),+ label: z.string(),+ placeholder: z.string().nullable().optional(),+ required: z.boolean().default(false),+ disabled: z.boolean().default(false),+ orderIndex: z.number().default(0),+});++export const watermarkConfigSchema = z.object({+ text: z.string(),+ isTiled: z.boolean(),+ color: z.string(),+ fontSize: z.number(),+ opacity: z.number(),+ rotation: z.number(),+ position: z.string(),+}).nullable();++export const presetDataSchema = z.object({+ // Social Media Card+ enableCustomMetaTag: z.boolean(),+ name: z.string(),+ metaFavicon: z.string().nullable(),+ metaImage: z.string().nullable(),+ metaTitle: z.string().nullable(),+ metaDescription: z.string().nullable(),++ // Custom Fields+ enableCustomFields: z.boolean(),+ customFields: z.array(customFieldDataSchema).nullable(),++ // Watermark+ enableWatermark: z.boolean(),+ watermarkConfig: watermarkConfigSchema,++ // Viewer Access Control+ enableAllowList: z.boolean(),+ allowList: z.array(z.string()),+ enableDenyList: z.boolean(),+ denyList: z.array(z.string()),+});++export type PresetDataSchema = z.infer<typeof presetDataSchema>;\ No newline at end of filediff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 48c9cc91..ac961cc7 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -189,6 +189,9 @@ export default async function handler(},}),},+ include: {+ customFields: true,+ },});const linkWithView = {diff --git a/pages/api/teams/[teamId]/agreements/index.ts b/pages/api/teams/[teamId]/agreements/index.tsindex 660f39eb..0cdadbca 100644--- a/pages/api/teams/[teamId]/agreements/index.ts+++ b/pages/api/teams/[teamId]/agreements/index.ts@@ -34,7 +34,15 @@ export default async function handle(},},select: {- agreements: true,+ agreements: {+ include: {+ _count: {+ select: {+ links: true,+ },+ },+ },+ },},});diff --git a/pages/api/teams/[teamId]/presets/index.ts b/pages/api/teams/[teamId]/presets/index.tsindex a222ba4a..99076b04 100644--- a/pages/api/teams/[teamId]/presets/index.ts+++ b/pages/api/teams/[teamId]/presets/index.ts@@ -1,4 +1,5 @@import { NextApiRequest, NextApiResponse } from "next";+import { ZodError } from "zod";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth";@@ -6,6 +7,8 @@ import { getServerSession } from "next-auth";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+import presets, { PresetData } from "@/pages/settings/presets";+import { presetDataSchema } from "@/lib/zod/schemas/presets";export const config = {api: {@@ -64,75 +67,89 @@ export default async function handle(return res.status(200).json(presets[0]);} else if (req.method === "POST") {// POST /api/teams/:teamId/presets- const { metaImage, metaTitle, metaDescription, metaFavicon } = req.body as {- metaImage?: string;- metaTitle?: string;- metaDescription?: string;- metaFavicon?: string;- };-- // update team with new preset- const preset = await prisma.linkPreset.create({- data: {- metaImage,- metaTitle,- metaDescription,- metaFavicon,- enableCustomMetaTag: true,- name: "Default Link Metatag",- teamId: teamId,- },- });-- return res.status(200).json({ message: "Preset created successfully" });+ try {+ // Validate request body with Zod schema+ const validatedData = presetDataSchema.parse(req.body);++ // update team with new preset+ const preset = await prisma.linkPreset.create({+ data: {+ ...validatedData,+ teamId,+ name: "Default Link Metatag",+ customFields: validatedData.customFields ? JSON.stringify(validatedData.customFields) : undefined,+ watermarkConfig: validatedData.watermarkConfig ? JSON.stringify(validatedData.watermarkConfig) : undefined,+ },+ });+ return res.status(200).json({ message: "Preset created successfully" });+ } catch (error) {+ if (error instanceof ZodError) {+ return res.status(400).json({+ message: "Invalid preset data",+ errors: error.errors+ });+ }+ errorhandler(error, res);+ }} else if (req.method === "PUT") {// PUT /api/teams/:teamId/presets- const { metaImage, metaTitle, metaDescription, metaFavicon } = req.body as {- metaImage?: string;- metaTitle?: string;- metaDescription?: string;- metaFavicon?: 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,- metaFavicon,- },- });-- return res.status(200).json({ message: "Preset updated successfully" });+ try {+ // Validate request body with Zod schema+ const validatedData = presetDataSchema.parse(req.body);++ const presets = await prisma.linkPreset.findMany({+ where: {+ teamId: teamId,+ },+ });++ // if metaImage is different from previous one, delete the previous image++ await prisma.linkPreset.update({+ where: {+ teamId: teamId,+ id: presets[0].id,+ },+ data: {+ ...validatedData,+ // Convert objects to JSON strings for storage+ customFields: validatedData.customFields ? JSON.stringify(validatedData.customFields) : undefined,+ watermarkConfig: validatedData.watermarkConfig ? JSON.stringify(validatedData.watermarkConfig) : undefined,+ teamId: teamId,+ },+ });++ return res.status(200).json({ message: "Preset updated successfully" });+ } catch (error) {+ if (error instanceof ZodError) {+ return res.status(400).json({+ message: "Invalid preset data",+ errors: error.errors+ });+ }+ errorhandler(error, res);+ }} 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,- },- });+ try {+ const preset = await prisma.linkPreset.findFirst({+ where: {+ teamId: teamId,+ },+ select: { id: true },+ });++ await prisma.linkPreset.delete({+ where: {+ teamId: teamId,+ id: preset?.id,+ },+ });return res.status(204).end();+ } catch (error) {+ errorhandler(error, res);+ }} else {// We only allow GET and DELETE requestsres.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);diff --git a/pages/settings/presets.tsx b/pages/settings/presets.tsxindex 457584fe..fdbe89bc 100644--- a/pages/settings/presets.tsx+++ b/pages/settings/presets.tsx@@ -1,13 +1,9 @@-import { ChangeEvent, useCallback, useEffect, useState } from "react";+import { useEffect, useState } from "react";import { useTeam } from "@/context/team-context";import { PlanEnum } from "@/ee/stripe/constants";-import { LinkPreset } from "@prisma/client";-import {- Upload as ArrowUpTrayIcon,- CircleHelpIcon,- PlusIcon,-} from "lucide-react";+import { Agreement, CustomFieldType, LinkPreset } from "@prisma/client";+import { CircleHelpIcon, Loader2, PlusIcon } from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";import useSWRImmutable from "swr/immutable";@@ -15,207 +11,241 @@ 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 SocialMediaCardPreset from "@/components/settings/presets/social-media-card-preset";+import PresetOptions from "@/components/settings/presets/preset-options";import { SettingsHeader } from "@/components/settings/settings-header";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import LoadingSpinner from "@/components/ui/loading-spinner";-import { Textarea } from "@/components/ui/textarea";import { BadgeTooltip } from "@/components/ui/tooltip";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { usePlan } from "@/lib/swr/use-billing";import {- cn,convertDataUrlToFile,fetcher,+ sanitizeAllowDenyList,uploadImage,- validateImageDimensions,} from "@/lib/utils";-import { resizeImage } from "@/lib/utils/resize-image";+import { CustomFieldData } from "@/components/links/link-sheet/custom-fields-panel";+import { useAgreements } from "@/lib/swr/use-agreements";++export interface PresetData {+ enableCustomMetaTag: boolean;+ name: string;+ metaFavicon: string | null;+ metaImage: string | null;+ metaTitle: string | null;+ metaDescription: string | null;++ enableCustomFields: boolean;+ customFields: CustomFieldData[] | null;++ enableWatermark: boolean;+ watermarkConfig: {+ text: string;+ isTiled: boolean;+ color: string;+ fontSize: number;+ opacity: number;+ rotation: number;+ position: string;+ } | null;++ enableAllowList: boolean;+ allowList: string[];+ enableDenyList: boolean;+ denyList: string[];+}++export const defaultPresetData: PresetData = {+ enableCustomMetaTag: false,+ name: "",+ metaFavicon: null,+ metaImage: null,+ metaTitle: null,+ metaDescription: null,++ enableCustomFields: false,+ customFields: null,++ enableWatermark: false,+ watermarkConfig: null,++ enableAllowList: false,+ allowList: [],+ enableDenyList: false,+ denyList: []+};export default function Presets() {const teamInfo = useTeam();const { plan, isTrial } = usePlan();+ const [isLoading, setIsLoading] = useState(false);+ const { agreements } = useAgreements();const { data: presets, mutate: mutatePreset } = useSWRImmutable<LinkPreset>(`/api/teams/${teamInfo?.currentTeam?.id}/presets`,fetcher,);-- const [data, setData] = useState<{- metaFavicon: string | null;- metaImage: string | null;- metaTitle: string | null;- metaDescription: string | null;- enableCustomMetatag?: boolean;- }>({- metaImage: null,- metaTitle: null,- metaFavicon: null,- metaDescription: null,- enableCustomMetatag: false,- });-- const [fileError, setFileError] = useState<string | null>(null);- const [faviconFileError, setFaviconFileError] = useState<string | null>(null);- const [dragActive, setDragActive] = useState(false);- const [faviconDragActive, setFaviconDragActive] = useState(false);- const [isLoading, setIsLoading] = useState(false);+ const [data, setData] = useState<PresetData>(defaultPresetData);+ const [activeTab, setActiveTab] = useState("social-media");useEffect(() => {if (presets) {+ const customFields = presets.customFields ? JSON.parse(presets.customFields as string) as PresetData['customFields'] : null;+ const watermarkConfig = presets.watermarkConfig ? JSON.parse(presets.watermarkConfig as string) as PresetData['watermarkConfig'] : null;+setData({+ name: presets.name,+ metaFavicon: presets.metaFavicon,metaImage: presets.metaImage,metaTitle: presets.metaTitle,metaDescription: presets.metaDescription,- metaFavicon: presets.metaFavicon,+ enableCustomMetaTag: presets.enableCustomMetaTag || false,+ enableCustomFields: presets.enableCustomFields || false,+ customFields: customFields,+ enableWatermark: presets.enableWatermark || false,+ watermarkConfig: watermarkConfig,+ enableAllowList: presets.enableAllowList || false,+ allowList: presets.allowList,+ enableDenyList: presets.enableDenyList || false,+ denyList: presets.denyList});}}, [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" &&- file.type !== "image/jpg"- ) {- 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) => {+ const handleDelete = async (e: React.MouseEvent) => {e.preventDefault();setIsLoading(true);- // Upload meta image if it's a data URL- let blobUrlImage: string | null =- data.metaImage && data.metaImage.startsWith("data:")- ? null- : data.metaImage;- if (data.metaImage && data.metaImage.startsWith("data:")) {- const blobImage = convertDataUrlToFile({ dataUrl: data.metaImage });- blobUrlImage = await uploadImage(blobImage);- setData({- ...data,- metaImage: blobUrlImage,- });- }+ const isPresetEmpty =+ !data.enableCustomFields &&+ !data.enableWatermark &&+ !data.enableAllowList &&+ !data.enableDenyList;- // Upload meta favicon if it's a data URL- let blobUrlFavicon: string | null =- data.metaFavicon && data.metaFavicon.startsWith("data:")- ? null- : data.metaFavicon;- if (data.metaFavicon && data.metaFavicon.startsWith("data:")) {- const blobFavicon = convertDataUrlToFile({ dataUrl: data.metaFavicon });- blobUrlFavicon = await uploadImage(blobFavicon);- setData({+ const method = isPresetEmpty ? "DELETE" : "PUT";++ const payload = isPresetEmpty+ ? null+ : {...data,- metaFavicon: blobUrlFavicon,+ watermarkConfig: data.watermarkConfig || null,+ metaImage: null,+ metaTitle: null,+ metaDescription: null,+ metaFavicon: null,+ enableCustomMetaTag: false,+ };++ try {+ const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {+ method,+ headers: {+ "Content-Type": "application/json",+ },+ ...(payload ? { body: JSON.stringify(payload) } : {}),});- }- const res = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {- method: presets ? "PUT" : "POST",- body: JSON.stringify(data),- headers: {- "Content-Type": "application/json",- },- });+ if (!response.ok) {+ throw new Error(`Failed to ${method.toLowerCase()} preset`);+ }- if (res.ok) {- mutate(`/api/teams/${teamInfo?.currentTeam?.id}/presets`);+ if (method === "DELETE") {+ setData(defaultPresetData);+ } else {+ setData(prev => ({+ ...prev,+ metaImage: null,+ metaTitle: null,+ metaDescription: null,+ metaFavicon: null,+ enableCustomMetaTag: false,+ }));+ }+++ toast.success("Your Social Media preset has been successfully reset");+ } catch (error) {+ console.error("Error resetting preset:", error);+ toast.error(+ `Failed to reset preset: ${error instanceof Error ? error.message : "Unknown error"+ }`+ );+ } finally {+ if (method === "DELETE") {+ await mutatePreset(undefined, false);+ } else {+ await mutatePreset();+ }setIsLoading(false);- toast.success("Presets updated successfully");- mutatePreset();}};- const handleDelete = async () => {+ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();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,- metaFavicon: null,++ const isMetaDataPresent =+ data.enableCustomMetaTag ||+ !!(data.metaTitle || data.metaDescription || data.metaImage || data.metaFavicon);++ const isPresetEmpty =+ !isMetaDataPresent &&+ !data.enableCustomFields &&+ !data.enableWatermark &&+ !data.enableAllowList &&+ !data.enableDenyList;++ const method = isPresetEmpty+ ? "DELETE"+ : presets?.id+ ? "PUT"+ : "POST";+ const payload = !isPresetEmpty+ ? {+ ...data,+ enableCustomMetaTag: isMetaDataPresent,+ customFields: data.customFields || null,+ watermarkConfig: data.watermarkConfig || null,+ }+ : null;++ try {+ const response = await fetch(`/api/teams/${teamInfo?.currentTeam?.id}/presets`, {+ method,+ headers: {+ "Content-Type": "application/json",+ },+ ...(payload ? { body: JSON.stringify(payload) } : {}),});++ if (!response.ok) throw new Error("Failed to save preset");++ const successMessage =+ method === "PUT"+ ? "Your preset has been updated successfully"+ : method === "POST"+ ? "Your preset has been created successfully"+ : "Your preset has been removed successfully";++ toast.success(successMessage);+ } catch (error) {+ toast.error("Failed to save preset");+ } finally {+ if (method === "DELETE") {+ await mutatePreset(undefined, false);+ } else {+ await mutatePreset();+ }setIsLoading(false);- toast.success("Preset reset successfully");- mutatePreset();}};- const onChangeFavicon = useCallback(- async (e: ChangeEvent<HTMLInputElement>) => {- setFaviconFileError(null);- const file = e.target.files && e.target.files[0];- if (file) {- if (file.size / 1024 / 1024 > 1) {- setFaviconFileError("File size too big (max 1MB)");- } else if (- file.type !== "image/png" &&- file.type !== "image/x-icon" &&- file.type !== "image/svg+xml"- ) {- setFaviconFileError(- "File type not supported (.png, .ico, .svg only)",- );- } else {- const image = await resizeImage(file, {- width: 36,- height: 36,- quality: 1,- });- const isValidDimensions = await validateImageDimensions(- image,- 16,- 48,- );- if (!isValidDimensions) {- setFaviconFileError(- "Image dimensions must be between 16x16 and 48x48",- );- } else {- setData((prev) => ({- ...prev,- metaFavicon: image,- }));- }- }- }- },- [setData],- );-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="mb-6 flex items-center justify-between"><div className="space-y-1"><h3 className="flex flex-row items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">Link Presets@@ -232,337 +262,77 @@ export default function Presets() {</p></div></div>- <div className="grid w-full divide-x divide-border overflow-auto scrollbar-hide md:grid-cols-2 md:overflow-hidden">- <div className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">- <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">Social Media Card</h2>- </div>- <div className="relative mt-5 space-y-3 rounded-md px-5">- <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="mainImage"- className="group relative mt-1 flex aspect-[1200/630] h-full 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" &&- file.type !== "image/jpg"- ) {- 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="h-full w-full rounded-md object-cover"- />- )}- </label>- <div className="mt-1 hidden rounded-md shadow-sm">- <input- id="mainImage"- name="image"- type="file"- accept="image/png,image/jpeg,image/jpg"- className="sr-only"- onChange={onChangePicture}- />- </div>- </div>- <div className="flex flex-col gap-2">- <div className="flex items-center justify-between">- <Label htmlFor="faviconIcon">- Favicon Icon{" "}- <span className="text-sm italic text-muted-foreground">- (max 1 MB)- </span>- </Label>- {faviconFileError ? (- <p className="text-sm text-red-500">{faviconFileError}</p>- ) : null}- </div>- <label- htmlFor="faviconIcon"- className="group relative mt-1 flex size-14 cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"- style={{- backgroundImage:- "linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(135deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(135deg, transparent 75%, #ccc 75%)",- backgroundSize: "20px 20px",- backgroundPosition: "0 0, 10px 0, 10px -10px, 0px 10px",- }}- >- {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();- setFaviconDragActive(true);- }}- onDragEnter={(e) => {- e.preventDefault();- e.stopPropagation();- setFaviconDragActive(true);- }}- onDragLeave={(e) => {- e.preventDefault();- e.stopPropagation();- setFaviconDragActive(false);- }}- onDrop={async (e) => {- e.preventDefault();- e.stopPropagation();- setFaviconDragActive(false);- setFaviconFileError(null);- const file =- e.dataTransfer.files && e.dataTransfer.files[0];- if (file) {- if (file.size / 1024 / 1024 > 1) {- setFaviconFileError("File size too big (max 1MB)");- } else if (- file.type !== "image/png" &&- file.type !== "image/x-icon" &&- file.type !== "image/svg+xml"- ) {- setFaviconFileError(- "File type not supported (.png, .ico, .svg only)",- );- } else {- const image = await resizeImage(file, {- width: 36,- height: 36,- quality: 1,- });- const isValidDimensions =- await validateImageDimensions(image, 16, 48);- if (!isValidDimensions) {- setFaviconFileError(- "Image dimensions must be between 16x16 and 48x48",- );- } else {- setData((prev) => ({- ...prev,- metaFavicon: image,- }));- }- }- }- }}- />- <div- className={`${- faviconDragActive- ? "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 ${- data.metaFavicon- ? "opacity-0 group-hover:opacity-100"- : "group-hover:bg-gray-50"- }`}- >- <PlusIcon- className={`${- faviconDragActive ? "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>- {data.metaFavicon && (- <img- src={data.metaFavicon}- alt="Preview"- className="h-full w-full rounded-md object-contain"- />- )}- </label>- <div className="mt-1 hidden rounded-md shadow-sm">- <input- id="faviconIcon"- name="favicon"- type="file"- accept="image/png,image/x-icon,image/svg+xml"- className="sr-only"- onChange={onChangeFavicon}- />- </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>+ <Tabs defaultValue="social-media" className="w-full" onValueChange={setActiveTab}>+ <div className="flex items-center justify-between mb-4">+ <TabsList>+ <TabsTrigger value="social-media">Social Media</TabsTrigger>+ <TabsTrigger value="access-control">Link Presets</TabsTrigger>+ </TabsList>++ {activeTab === "access-control" && (+ <Button+ size="sm"+ className="flex items-center gap-1"+ onClick={handleSubmit}+ >+ {isLoading ? <><Loader2 className="h-4 w-4 animate-spin" /> <span>Saving...</span></> : <>+ <PlusIcon className="h-4 w-4" />+ <span>Save Preset</span></>+ }+ </Button>+ )}+ </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>+ <TabsContent value="social-media">+ <div className="grid w-full divide-x divide-border overflow-auto scrollbar-hide md:grid-cols-2 md:overflow-hidden">+ <div className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">+ <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">Social Media Card</h2></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>++ <SocialMediaCardPreset data={data} setData={setData} />++ <div className="flex justify-end px-5 py-4">+ {(plan === "free" || plan === "pro") && !isTrial ? (+ <UpgradePlanModal+ clickedPlan={PlanEnum.Business}+ trigger={"presets_page"}+ >+ <Button>Upgrade to Save Preset</Button>+ </UpgradePlanModal>+ ) : (+ <Button onClick={handleSubmit} loading={isLoading}>+ Save Social Media Preset+ </Button>)}- <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"- />++ {data.enableCustomMetaTag ? (+ <Button+ variant="link"+ onClick={handleDelete}+ className="ml-2"+ loading={isLoading}+ >+ Reset Social Media Preset+ </Button>+ ) : null}</div></div>-- <div className="flex justify-end">- {(plan === "free" || plan === "pro") && !isTrial ? (- <UpgradePlanModal- clickedPlan={PlanEnum.Business}- trigger={"presets_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 className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">+ <Preview data={data} setData={setData} /></div></div>- </div>- <div className="px-4 scrollbar-hide md:max-h-[95svh] md:overflow-auto">- <Preview data={data} setData={setData} />- </div>- </div>+ </TabsContent>+ <TabsContent value="access-control">+ <div className="grid w-full gap-6">+ <PresetOptions data={data} setData={setData} agreements={agreements} />+ </div>+ </TabsContent>+ </Tabs></div></main></AppLayout>);}+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 6f92e41a..eaca9a26 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -298,6 +298,15 @@ model LinkPreset {metaImage String? // This will be the meta image of the linkmetaFavicon String? // This will be the meta favicon of the link+ enableCustomFields Boolean? @default(false)+ customFields Json? //[{type: "SHORT_TEXT", identifier: "name", label: "Name", required: true}]+ enableWatermark Boolean? @default(false)+ watermarkConfig Json? //{text: "Confidential", isTiled: false, color: "#000000", fontSize: 12, opacity: 0.5, rotation: 30, position: "top-right"}+ enableAllowList Boolean? @default(false)+ allowList String[]+ enableDenyList Boolean? @default(false)+ denyList String[]+createdAt DateTime @default(now())updatedAt DateTime @updatedAt