Skip to content

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

refactor: rework the expiresIn component

Marc Seitzd37611d65ca9
diff --git a/components/links/link-sheet/expiration-section.tsx b/components/links/link-sheet/expiration-section.tsx
index a89ef1a2..5f2ca5f1 100644
--- a/components/links/link-sheet/expiration-section.tsx
+++ b/components/links/link-sheet/expiration-section.tsx
@@ -1,22 +1,11 @@
import { useCallback, useEffect, useState } from "react";
+import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import {
- WITH_CUSTOM_PRESET_OPTION,
- formatExpirationTime,
- getDateTimeLocal,
-} from "@/lib/utils";
-
-import { Input } from "@/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+import { formatExpirationTime } from "@/lib/utils";
+
import { SmartDateTimePicker } from "@/components/ui/smart-date-time-picker";
import { DEFAULT_LINK_TYPE } from ".";
@@ -25,94 +14,41 @@ import LinkItem from "./link-item";
export default function ExpirationSection({
data,
setData,
+ presets,
}: {
- data: DEFAULT_LINK_TYPE & {
- expiresIn?: { value: number; type: "natural" | "normal" } | null;
- };
- setData: React.Dispatch<
- React.SetStateAction<
- DEFAULT_LINK_TYPE & {
- expiresIn?: { value: number; type: "natural" | "normal" } | null;
- }
- >
- >;
+ data: DEFAULT_LINK_TYPE;
+ setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
+ presets: LinkPreset | null;
}) {
const { expiresAt } = data;
const [enabled, setEnabled] = useState<boolean>(false);
- const [selectedPreset, setSelectedPreset] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [customDate, setCustomDate] = useState<Date | null>(null);
- const [dataWasJustEnabled, setDataWasJustEnabled] = useState<boolean>(false);
useEffect(() => {
- setEnabled(!!expiresAt && !data.expiresIn);
-
- if (expiresAt && !data.expiresIn) {
- const now = new Date();
- const expirationDate =
- typeof expiresAt === "string" ? new Date(expiresAt) : expiresAt;
- const diffInSeconds = Math.floor(
- (expirationDate.getTime() - now.getTime()) / 1000,
- );
-
- const matchingPreset = WITH_CUSTOM_PRESET_OPTION.find(
- (option: { value: number | string }) =>
- option.value !== "custom" &&
- Math.abs(parseInt(option.value.toString()) - diffInSeconds) < 60,
- );
-
- if (matchingPreset) {
- setSelectedPreset(matchingPreset.value.toString());
- setCustomDate(null);
- } else {
- if (!dataWasJustEnabled) {
- setSelectedPreset("custom");
- setCustomDate(expirationDate);
- } else {
- setSelectedPreset("");
- setCustomDate(null);
- }
- }
- }
- }, [data, expiresAt, dataWasJustEnabled]);
+ setEnabled(!!expiresAt);
+ setCustomDate(expiresAt);
+ }, [expiresAt]);
useEffect(() => {
- if (dataWasJustEnabled) {
- setDataWasJustEnabled(false);
+ if (presets?.expiresIn) {
+ setEnabled(true);
+ handlePresetChange(presets.expiresIn);
}
- }, [dataWasJustEnabled]);
+ }, [presets]);
const handleEnableExpiration = () => {
if (enabled) {
+ // if expiration is currently set and we're toggling it off
setData({ ...data, expiresAt: null });
- setSelectedPreset("");
- setError(null);
- setCustomDate(null);
- setEnabled(false);
- setDataWasJustEnabled(false);
- } else {
- const defaultExpiration = new Date();
- defaultExpiration.setDate(defaultExpiration.getDate() + 7); // Default to 7 days
- setData({
- ...data,
- expiresIn: null,
- expiresAt: defaultExpiration,
- });
- setSelectedPreset("86400"); // 1 day in seconds
- setCustomDate(defaultExpiration);
- setEnabled(true);
- setDataWasJustEnabled(true);
}
+ setEnabled(!enabled);
};
- const handlePresetChange = (value: string) => {
- setSelectedPreset(value);
+ const handlePresetChange = (value: number) => {
setError(null);
- if (value === "custom") {
- return;
- }
- const seconds = parseInt(value);
+ const seconds = value;
if (!isNaN(seconds)) {
const newExpiresAt = new Date();
newExpiresAt.setSeconds(newExpiresAt.getSeconds() + seconds);
@@ -129,14 +65,19 @@ export default function ExpirationSection({
const now = new Date();
if (date <= now) {
- setData({ ...data, expiresAt: new Date(now.getTime() + 86400) }); // 1 day
- setError("Expiration time must be in the future");
+ console.log("date <= now", now, date);
+
+ // Always add 1 day (86400000 milliseconds) to current time
+ const newDate = new Date(now.getTime() + 86400 * 1000);
+
+ setData({ ...data, expiresAt: newDate });
+ setCustomDate(newDate);
+ setError("Expiration time must be in the future. Set to tomorrow.");
return;
}
setData({ ...data, expiresAt: date });
setCustomDate(date);
- setSelectedPreset("custom");
setError(null);
};
@@ -190,65 +131,25 @@ export default function ExpirationSection({
{enabled && (
<motion.div className="mt-3 space-y-3" {...FADE_IN_ANIMATION_SETTINGS}>
- <div className="flex flex-col space-y-4">
- <div className="flex flex-col space-y-2">
- <SmartDateTimePicker
- value={customDate}
- onChange={handleCustomDateChange}
- placeholder='e.g. "in 2 days", "next Friday at 3pm", "December 25th at 9am"'
- />
- <div className="relative">
- <div className="absolute inset-0 flex items-center">
- <div className="w-full border-t border-neutral-300" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-white px-2 text-neutral-500">Or</span>
- </div>
- </div>
- <Select value={selectedPreset} onValueChange={handlePresetChange}>
- <SelectTrigger>
- <SelectValue placeholder="Select from preset times" />
- </SelectTrigger>
- <SelectContent>
- {WITH_CUSTOM_PRESET_OPTION.map((option) => (
- <SelectItem
- key={option.value}
- value={option.value.toString()}
- >
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {selectedPreset === "custom" ? (
- <Input
- type="datetime-local"
- id="expiresAt"
- name="expiresAt"
- min={getDateTimeLocal()}
- value={expiresAt ? getDateTimeLocal(expiresAt) : ""}
- step="60"
- onChange={(e) =>
- handleCustomDateChange(new Date(e.target.value))
- }
- className="focus:ring-inset"
- />
- ) : null}
- </div>
+ <div className="flex flex-col space-y-2">
+ <SmartDateTimePicker
+ value={customDate}
+ onChange={handleCustomDateChange}
+ placeholder='e.g. "in 2 days", "next Friday at 3pm"'
+ />
{expiresAt && (
- <div className="space-y-1 text-xs text-muted-foreground">
+ <div className="text-xs text-muted-foreground">
<div>
- Link will expire {formatNaturalExpiration(expiresAt)} ( in{" "}
+ Link will expire {formatNaturalExpiration(expiresAt)} (in{" "}
{expirationTime(expiresAt)})
</div>
</div>
)}
-
{error && <div className="text-xs text-red-500">{error}</div>}
</div>
</motion.div>
)}
</div>
);
-}
\ No newline at end of file
+}
diff --git a/components/links/link-sheet/expirationIn-section.tsx b/components/links/link-sheet/expirationIn-section.tsx
index fc64ea09..233f7b8d 100644
--- a/components/links/link-sheet/expirationIn-section.tsx
+++ b/components/links/link-sheet/expirationIn-section.tsx
@@ -3,15 +3,8 @@ import { useCallback, useEffect, useState } from "react";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { PRESET_OPTIONS, formatExpirationTime } from "@/lib/utils";
-
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+import { formatExpirationTime } from "@/lib/utils";
+
import { SmartDateTimePicker } from "@/components/ui/smart-date-time-picker";
import { DEFAULT_LINK_TYPE } from ".";
@@ -22,23 +15,21 @@ export default function ExpirationInSection({
setData,
}: {
data: DEFAULT_LINK_TYPE & {
- expiresIn?: { value: number; type: "natural" | "normal" } | null;
+ expiresIn?: number | null;
};
setData: React.Dispatch<
React.SetStateAction<
DEFAULT_LINK_TYPE & {
- expiresIn?: { value: number; type: "natural" | "normal" } | null;
+ expiresIn?: number | null;
}
>
>;
}) {
const [enabled, setEnabled] = useState<boolean>(false);
- const [selectedPreset, setSelectedPreset] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [customDate, setCustomDate] = useState<Date | null>(null);
const resetStates = useCallback(() => {
- setSelectedPreset("");
setError(null);
setCustomDate(null);
}, []);
@@ -53,24 +44,9 @@ export default function ExpirationInSection({
setEnabled(true);
- if (data.expiresIn.type === "normal") {
- const matchingPreset = PRESET_OPTIONS.find(
- (option) => option.value === data.expiresIn?.value,
- );
-
- if (matchingPreset) {
- setSelectedPreset(matchingPreset.value.toString());
- setCustomDate(null);
- } else {
- const futureDate = new Date();
- futureDate.setSeconds(futureDate.getSeconds() + data.expiresIn.value);
- setSelectedPreset("");
- setCustomDate(futureDate);
- }
- } else if (data.expiresIn.type === "natural") {
+ if (data.expiresIn) {
const futureDate = new Date();
- futureDate.setSeconds(futureDate.getSeconds() + data.expiresIn.value);
- setSelectedPreset("");
+ futureDate.setSeconds(futureDate.getSeconds() + data.expiresIn);
setCustomDate(futureDate);
}
}, [data.expiresIn]);
@@ -80,50 +56,25 @@ export default function ExpirationInSection({
setData({
...data,
expiresIn: null,
- expiresAt: null,
});
resetStates();
} else {
// Enable with default 7 days expiration
setData({
...data,
- expiresIn: { value: 604800, type: "normal" },
- expiresAt: null,
+ expiresIn: 604800,
});
- setSelectedPreset("604800");
setError(null);
setCustomDate(null);
}
setEnabled(!enabled);
}, [enabled, data, resetStates]);
- const handlePresetChange = useCallback(
- (value: string) => {
- const seconds = parseInt(value);
- if (!isNaN(seconds)) {
- setData({
- ...data,
- expiresIn: { value: seconds, type: "normal" },
- expiresAt: null,
- });
- setCustomDate(null);
- setSelectedPreset(value);
- setError(null);
- }
- },
- [data],
- );
resetStates;
const handleCustomDateChange = useCallback(
(date: Date | null) => {
if (!date) {
- setData({
- ...data,
- expiresIn: null,
- expiresAt: null,
- });
- resetStates();
return;
}
@@ -138,13 +89,12 @@ export default function ExpirationInSection({
setData({
...data,
- expiresIn: { value: diffSeconds, type: "natural" },
- expiresAt: null,
+ expiresIn: diffSeconds,
});
setCustomDate(date);
- resetStates();
+ setError(null);
},
- [data, resetStates],
+ [data, setData],
);
// Custom formatter to show only the duration
@@ -168,7 +118,7 @@ export default function ExpirationInSection({
{enabled && (
<motion.div className="mt-3 space-y-3" {...FADE_IN_ANIMATION_SETTINGS}>
- <div className="flex flex-col space-y-4">
+ <div className="flex flex-col space-y-2">
<SmartDateTimePicker
value={customDate}
onChange={handleCustomDateChange}
@@ -177,36 +127,11 @@ export default function ExpirationInSection({
showCalendarIcon={false}
/>
- <div className="relative">
- <div className="absolute inset-0 flex items-center">
- <div className="w-full border-t border-neutral-300" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-white px-2 text-neutral-500">Or</span>
- </div>
- </div>
-
- <Select value={selectedPreset} onValueChange={handlePresetChange}>
- <SelectTrigger>
- <SelectValue placeholder="Select expiration time" />
- </SelectTrigger>
- <SelectContent>
- {PRESET_OPTIONS.map((option) => (
- <SelectItem
- key={option.value}
- value={option.value.toString()}
- >
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
{data.expiresIn && (
- <div className="space-y-1 text-xs text-muted-foreground">
+ <div className="text-xs text-muted-foreground">
<div>
- Links will expire in{" "}
- {formatExpirationTime(data.expiresIn.value)} after creation
+ Links will expire in {formatExpirationTime(data.expiresIn)}{" "}
+ after creation
</div>
</div>
)}
@@ -217,4 +142,4 @@ export default function ExpirationInSection({
)}
</div>
);
-}
\ No newline at end of file
+}
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index b8710c2e..7f66ad1f 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -227,19 +227,6 @@ export default function LinkSheet({
if (!preset) return;
setData((prev) => {
- // Calculate expiresAt if expiresIn is provided
- let expiresAt = prev.expiresAt;
- if (preset.expiresIn) {
- const newExpiresAt = new Date();
- newExpiresAt.setSeconds(
- newExpiresAt.getSeconds() +
- (JSON.parse(preset.expiresIn as string) as { value: number }).value,
- );
- expiresAt = newExpiresAt;
- } else {
- expiresAt = preset.expiresAt || prev.expiresAt;
- }
-
return {
...prev,
name: prev.name, // Keep existing name
@@ -258,7 +245,6 @@ export default function LinkSheet({
metaImage: preset.metaImage || prev.metaImage,
metaFavicon: preset.metaFavicon || prev.metaFavicon,
allowDownload: preset.allowDownload || prev.allowDownload,
- expiresAt,
enableScreenshotProtection:
preset.enableScreenshotProtection || prev.enableScreenshotProtection,
};
@@ -780,4 +766,4 @@ export default function LinkSheet({
</SheetContent>
</Sheet>
);
-}
\ No newline at end of file
+}
diff --git a/components/links/link-sheet/link-options.tsx b/components/links/link-sheet/link-options.tsx
index 06ff86b3..ee40c88f 100644
--- a/components/links/link-sheet/link-options.tsx
+++ b/components/links/link-sheet/link-options.tsx
@@ -85,7 +85,7 @@ export const LinkOptions = ({
<EmailProtectionSection {...{ data, setData }} />
<AllowNotificationSection {...{ data, setData }} />
<AllowDownloadSection {...{ data, setData }} />
- <ExpirationSection {...{ data, setData }} />
+ <ExpirationSection {...{ data, setData }} presets={currentPreset} />
{limits?.dataroomUpload &&
linkType === LinkType.DATAROOM_LINK &&
targetId ? (
diff --git a/components/ui/smart-date-time-picker.tsx b/components/ui/smart-date-time-picker.tsx
index aabe63f5..3d0367e6 100644
--- a/components/ui/smart-date-time-picker.tsx
+++ b/components/ui/smart-date-time-picker.tsx
@@ -143,6 +143,9 @@ export function SmartDateTimePicker({
defaultValue={formatDisplayValue(value)}
onBlur={handleInputBlur}
onKeyDown={handleKeyDown}
+ onChange={(e) => {
+ inputRef.current!.value = e.target.value;
+ }}
className="flex-1 border-none bg-transparent text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
/>
{showCalendarIcon && (
@@ -158,4 +161,4 @@ export function SmartDateTimePicker({
</div>
</div>
);
-}
\ No newline at end of file
+}
diff --git a/lib/zod/schemas/presets.ts b/lib/zod/schemas/presets.ts
index e1919b80..2c7f1698 100644
--- a/lib/zod/schemas/presets.ts
+++ b/lib/zod/schemas/presets.ts
@@ -52,11 +52,7 @@ export const presetDataSchema = z.object({
enablePassword: z.boolean(),
password: z.string().nullable(),
expiresAt: z.string().nullable(),
- expiresIn: z.object({
- value: z.number(),
- type: z.enum(["natural", "normal"]),
- })
- .nullable(),
+ expiresIn: z.number().nullable().optional(),
// Screenshot Protection
enableScreenshotProtection: z.boolean(),
diff --git a/pages/api/teams/[teamId]/presets/[id].ts b/pages/api/teams/[teamId]/presets/[id].ts
index 9648a3a0..c50b8a9d 100644
--- a/pages/api/teams/[teamId]/presets/[id].ts
+++ b/pages/api/teams/[teamId]/presets/[id].ts
@@ -101,8 +101,6 @@ export default async function handle(
watermarkConfig: validatedData.watermarkConfig
? JSON.stringify(validatedData.watermarkConfig)
: Prisma.JsonNull,
- expiresIn: validatedData.expiresIn
- ? JSON.stringify(validatedData.expiresIn)
: Prisma.JsonNull,
},
});
diff --git a/pages/api/teams/[teamId]/presets/index.ts b/pages/api/teams/[teamId]/presets/index.ts
index 6db283d3..9e90cc62 100644
--- a/pages/api/teams/[teamId]/presets/index.ts
+++ b/pages/api/teams/[teamId]/presets/index.ts
@@ -82,10 +82,7 @@ export default async function handle(
pId: newId("preset"),
watermarkConfig: validatedData.watermarkConfig
? JSON.stringify(validatedData.watermarkConfig)
- : undefined,
- expiresIn: validatedData.expiresIn
- ? JSON.stringify(validatedData.expiresIn)
- : undefined,
+ : Prisma.JsonNull,
},
});
return res
diff --git a/pages/settings/presets/[id].tsx b/pages/settings/presets/[id].tsx
index c5252a85..1305c640 100644
--- a/pages/settings/presets/[id].tsx
+++ b/pages/settings/presets/[id].tsx
@@ -54,10 +54,7 @@ export type PRESET_DATA = Partial<DEFAULT_LINK_TYPE> & {
enableAllowList?: boolean;
enableDenyList?: boolean;
expiresAt?: Date | null;
- expiresIn?: {
- value: number;
- type: "natural" | "normal";
- } | null;
+ expiresIn?: number | null;
pId?: string | null;
};
@@ -117,18 +114,12 @@ export default function EditPreset() {
? (JSON.parse(preset.watermarkConfig as string) as WatermarkConfig)
: null;
- const expiresIn = preset.expiresIn
- ? (JSON.parse(preset.expiresIn as string) as {
- value: number;
- type: "natural" | "normal";
- })
- : null;
setData({
id: null,
name: preset.name,
expiresAt: preset.expiresAt,
- expiresIn: expiresIn,
+ expiresIn: preset.expiresIn,
password: preset.password,
emailProtected: preset.emailProtected ?? true,
emailAuthenticated: preset.emailAuthenticated ?? false,
@@ -398,10 +389,7 @@ export default function EditPreset() {
}
handleUpgradeStateChange={handleUpgradeStateChange}
/>
- <ExpirationSection
- data={data as any}
- setData={setData as any}
- />
+
<ExpirationInSection
data={data as any}
setData={setData as any}
diff --git a/pages/settings/presets/new.tsx b/pages/settings/presets/new.tsx
index abe6e1b8..c9f3ec06 100644
--- a/pages/settings/presets/new.tsx
+++ b/pages/settings/presets/new.tsx
@@ -22,7 +22,6 @@ import AllowListSection from "@/components/links/link-sheet/allow-list-section";
import DenyListSection from "@/components/links/link-sheet/deny-list-section";
import EmailAuthenticationSection from "@/components/links/link-sheet/email-authentication-section";
import EmailProtectionSection from "@/components/links/link-sheet/email-protection-section";
-import ExpirationSection from "@/components/links/link-sheet/expiration-section";
import ExpirationInSection from "@/components/links/link-sheet/expirationIn-section";
import { LinkUpgradeOptions } from "@/components/links/link-sheet/link-options";
import OGSection from "@/components/links/link-sheet/og-section";
@@ -44,7 +43,8 @@ export default function NewPreset() {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState<
DEFAULT_LINK_TYPE & {
- expiresIn?: { value: number; type: "natural" | "normal" } | null;
+ expiresIn?: number | null;
+ customFields?: CustomFieldData[];
}
>({
...DEFAULT_LINK_PROPS(LinkType.DOCUMENT_LINK),
@@ -227,7 +227,7 @@ export default function NewPreset() {
}
handleUpgradeStateChange={handleUpgradeStateChange}
/>
- <ExpirationSection data={data} setData={setData} />
+
<ExpirationInSection data={data} setData={setData} />
</div>