Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Natural date and time input
Ashish Viradiya251defe39b71
diff --git a/components/links/link-sheet/expiration-section.tsx b/components/links/link-sheet/expiration-section.tsxindex 0b3c3c41..f505d545 100644--- a/components/links/link-sheet/expiration-section.tsx+++ b/components/links/link-sheet/expiration-section.tsx@@ -3,7 +3,11 @@ import { useCallback, useEffect, useState } from "react";import { motion } from "motion/react";import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";-import { WITH_CUSTOM_PRESET_OPTION, getDateTimeLocal } from "@/lib/utils";+import {+ WITH_CUSTOM_PRESET_OPTION,+ formatExpirationTime,+ getDateTimeLocal,+} from "@/lib/utils";import { Input } from "@/components/ui/input";import {@@ -21,9 +25,15 @@ export default function ExpirationSection({data,setData,}: {- data: DEFAULT_LINK_TYPE & { expiresIn?: number | null };+ data: DEFAULT_LINK_TYPE & {+ expiresIn?: { value: number; type: "natural" | "normal" } | null;+ };setData: React.Dispatch<- React.SetStateAction<DEFAULT_LINK_TYPE & { expiresIn?: number | null }>+ React.SetStateAction<+ DEFAULT_LINK_TYPE & {+ expiresIn?: { value: number; type: "natural" | "normal" } | null;+ }+ >>;}) {const { expiresAt } = data;@@ -102,31 +112,13 @@ export default function ExpirationSection({setError(null);};- const formatExpirationTime = useCallback((date: Date | string) => {+ const expirationTime = useCallback((date: Date | string) => {const now = new Date();const dateObj = typeof date === "string" ? new Date(date) : date;const diffInSeconds = Math.floor((dateObj.getTime() - now.getTime()) / 1000,);-- if (diffInSeconds < 60) {- return "Less than a minute";- } else if (diffInSeconds < 3600) {- const minutes = Math.floor(diffInSeconds / 60);- return `${minutes} minute${minutes > 1 ? "s" : ""}`;- } else if (diffInSeconds < 86400) {- const hours = Math.floor(diffInSeconds / 3600);- return `${hours} hour${hours > 1 ? "s" : ""}`;- } else {- const days = Math.floor(diffInSeconds / 86400);- const remainingHours = Math.floor((diffInSeconds % 86400) / 3600);-- if (remainingHours === 0) {- return `${days} day${days > 1 ? "s" : ""}`;- } else {- return `${days} day${days > 1 ? "s" : ""} and ${remainingHours} hour${remainingHours > 1 ? "s" : ""}`;- }- }+ return formatExpirationTime(diffInSeconds);}, []);const formatNaturalExpiration = useCallback((date: Date | string) => {@@ -191,7 +183,7 @@ export default function ExpirationSection({<div className="space-y-1 text-xs text-muted-foreground"><div>Link will expire {formatNaturalExpiration(expiresAt)} ( in{" "}- {formatExpirationTime(expiresAt)})+ {expirationTime(expiresAt)})</div></div>)}diff --git a/components/links/link-sheet/expirationIn-section.tsx b/components/links/link-sheet/expirationIn-section.tsxindex 160f1009..c87a2edf 100644--- a/components/links/link-sheet/expirationIn-section.tsx+++ b/components/links/link-sheet/expirationIn-section.tsx@@ -2,7 +2,6 @@ import { useEffect, useState } from "react";-import { PRESET_DATA } from "@/pages/settings/presets/[id]";import { motion } from "motion/react";import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";@@ -15,6 +14,7 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import { SmartDateTimePicker } from "@/components/ui/smart-date-time-picker";import { DEFAULT_LINK_TYPE } from ".";import LinkItem from "./link-item";@@ -23,60 +23,134 @@ export default function ExpirationInSection({data,setData,}: {- data: DEFAULT_LINK_TYPE & { expiresIn?: number | null };+ data: DEFAULT_LINK_TYPE & {+ expiresIn?: { value: number; type: "natural" | "normal" } | null;+ };setData: React.Dispatch<- React.SetStateAction<DEFAULT_LINK_TYPE & { expiresIn?: number | null }>+ React.SetStateAction<+ DEFAULT_LINK_TYPE & {+ expiresIn?: { value: number; type: "natural" | "normal" } | 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);+ // Initialize state based on existing expiresIn datauseEffect(() => {- setEnabled(!!data.expiresIn);+ if (!data.expiresIn) {+ setEnabled(false);+ setSelectedPreset("");+ setCustomDate(null);+ return;+ }++ setEnabled(true);- if (data.expiresIn) {+ if (data.expiresIn.type === "normal") {const matchingPreset = PRESET_OPTIONS.find(- (option: { value: number }) => option.value === data.expiresIn,+ (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") {+ const futureDate = new Date();+ futureDate.setSeconds(futureDate.getSeconds() + data.expiresIn.value);+ setSelectedPreset("");+ setCustomDate(futureDate);}}, [data.expiresIn]);const handleEnableExpiration = () => {if (enabled) {+ setData({+ ...data,+ expiresIn: null,+ expiresAt: null,+ });setSelectedPreset("");setError(null);+ setCustomDate(null);} else {+ // Enable with default 7 days expirationsetData({...data,- expiresIn: 604800,+ expiresIn: { value: 604800, type: "normal" },expiresAt: null,});setSelectedPreset("604800");setError(null);+ setCustomDate(null);}setEnabled(!enabled);};const handlePresetChange = (value: string) => {- setSelectedPreset(value);- setError(null);-const seconds = parseInt(value);if (!isNaN(seconds)) {setData({...data,- expiresIn: seconds,+ expiresIn: { value: seconds, type: "normal" },+ expiresAt: null,});+ setCustomDate(null);+ setSelectedPreset(value);+ setError(null);}};+ const handleCustomDateChange = (date: Date | null) => {+ if (!date) {+ setData({+ ...data,+ expiresIn: null,+ expiresAt: null,+ });+ setCustomDate(null);+ setSelectedPreset("");+ setError(null);+ return;+ }++ const now = new Date();+ const diffMs = date.getTime() - now.getTime();+ const diffSeconds = Math.ceil(diffMs / 1000);++ if (diffSeconds <= 0) {+ setError("Please enter a future duration");+ return;+ }++ setData({+ ...data,+ expiresIn: { value: diffSeconds, type: "natural" },+ expiresAt: null,+ });+ setCustomDate(date);+ setSelectedPreset("");+ setError(null);+ };++ // Custom formatter to show only the duration+ const formatValue = (date: Date | null) => {+ if (!date) return "";+ const now = new Date();+ const diffMs = date.getTime() - now.getTime();+ const diffSeconds = Math.ceil(diffMs / 1000);+ return "in " + formatExpirationTime(diffSeconds);+ };+return (<div className="pb-5"><LinkItem@@ -84,34 +158,50 @@ export default function ExpirationInSection({enabled={enabled}link="https://www.papermark.com/help/article/expiration-date"action={handleEnableExpiration}- tooltipContent="Set how long the link will remain active."+ tooltipContent="Set how long the link will remain active after creation."/>{enabled && (<motion.div className="mt-3 space-y-3" {...FADE_IN_ANIMATION_SETTINGS}>- <div className="flex flex-col space-y-2">+ <div className="flex flex-col space-y-4">+ <SmartDateTimePicker+ value={customDate}+ onChange={handleCustomDateChange}+ placeholder='E.g. "in 2 hours" or "in 2 days"'+ formatValue={formatValue}+ 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: { value: number; label: string }) => (- <SelectItem- key={option.value}- value={option.value.toString()}- >- {option.label}- </SelectItem>- ),- )}+ {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>- Links will expire in {formatExpirationTime(data.expiresIn)}+ Links will expire in{" "}+ {formatExpirationTime(data.expiresIn.value)} after creation</div></div>)}@@ -122,4 +212,4 @@ export default function ExpirationInSection({)}</div>);-}+}\ No newline at end of filediff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex ebee6fe2..12c518b3 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -227,7 +227,10 @@ export default function LinkSheet({let expiresAt = prev.expiresAt;if (preset.expiresIn) {const newExpiresAt = new Date();- newExpiresAt.setSeconds(newExpiresAt.getSeconds() + preset.expiresIn);+ newExpiresAt.setSeconds(+ newExpiresAt.getSeconds() ++ (preset.expiresIn as { value: number }).value,+ );expiresAt = newExpiresAt;} else {expiresAt = preset.expiresAt || prev.expiresAt;@@ -757,4 +760,4 @@ export default function LinkSheet({</SheetContent></Sheet>);-}+}\ No newline at end of filediff --git a/components/ui/smart-date-time-picker.tsx b/components/ui/smart-date-time-picker.tsxnew file mode 100644index 00000000..67aa2a9e--- /dev/null+++ b/components/ui/smart-date-time-picker.tsx@@ -0,0 +1,155 @@+import { useCallback, useEffect, useId, useRef } from "react";++import {+ cn,+ formatDateTime,+ getDateTimeLocal,+ parseDateTime,+} from "@/lib/utils";++interface SmartDateTimePickerProps {+ value: Date | null | undefined;+ onChange: (date: Date | null) => void;+ label?: string;+ placeholder?: string;+ className?: string;+ required?: boolean;+ autoFocus?: boolean;+ options?: Intl.DateTimeFormatOptions;+ formatValue?: (date: Date | null) => string;+ showCalendarIcon?: boolean;+}++export function SmartDateTimePicker({+ value,+ onChange,+ label,+ placeholder = 'E.g. "tomorrow at 5pm" or "in 2 hours"',+ className,+ required,+ autoFocus = false,+ options,+ formatValue,+ showCalendarIcon = true,+}: SmartDateTimePickerProps) {+ const id = useId();+ const inputRef = useRef<HTMLInputElement>(null);++ const formatDisplayValue = useCallback(+ (date: Date | null | undefined) => {+ if (!date) return "";+ return formatValue ? formatValue(date) : formatDateTime(date);+ },+ [formatValue],+ );++ const updateInputValue = useCallback(+ (date: Date | null | undefined) => {+ if (inputRef.current) {+ inputRef.current.value = formatDisplayValue(date);+ }+ },+ [formatDisplayValue],+ );++ const handleDateChange = useCallback(+ (date: Date | null) => {+ onChange(date);+ updateInputValue(date);+ },+ [onChange, updateInputValue],+ );++ const handleInputBlur = useCallback(+ (e: React.FocusEvent<HTMLInputElement>) => {+ if (e.target.value.length > 0) {+ const parsedDateTime = parseDateTime(e.target.value);+ if (parsedDateTime) {+ handleDateChange(parsedDateTime);+ }+ } else {+ handleDateChange(null);+ }+ },+ [handleDateChange],+ );++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter" && inputRef.current) {+ e.preventDefault();+ const parsedDateTime = parseDateTime(inputRef.current.value);+ if (parsedDateTime) {+ handleDateChange(parsedDateTime);+ }+ }+ },+ [handleDateChange],+ );++ const handleCalendarChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const date = new Date(e.target.value);+ if (!isNaN(date.getTime())) {+ handleDateChange(date);+ }+ },+ [handleDateChange],+ );++ // Handle autofocus+ useEffect(() => {+ if (inputRef.current && autoFocus) {+ setTimeout(() => {+ inputRef.current?.focus();+ }, 10);+ }+ }, [autoFocus]);++ useEffect(() => {+ updateInputValue(value);+ }, [value, updateInputValue]);++ return (+ <div className={className}>+ {label && (+ <div className="flex items-center gap-2">+ <label+ htmlFor={`${id}-datetime`}+ className="block text-sm font-medium text-neutral-700"+ >+ {label}+ </label>+ </div>+ )}+ <div+ className={cn(+ "mt-2 flex w-full items-center justify-between rounded-md border border-neutral-300",+ "bg-white shadow-sm transition-all focus-within:border-neutral-800",+ "focus-within:outline-none focus-within:ring-1 focus-within:ring-neutral-500",+ )}+ >+ <input+ ref={inputRef}+ id={`${id}-datetime`}+ type="text"+ placeholder={placeholder}+ defaultValue={formatDisplayValue(value)}+ onBlur={handleInputBlur}+ onKeyDown={handleKeyDown}+ className="flex-1 border-none bg-transparent text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"+ />+ {showCalendarIcon && (+ <input+ type="datetime-local"+ id={`${id}-datetime-local`}+ required={required}+ value={value ? getDateTimeLocal(value) : ""}+ onChange={handleCalendarChange}+ className="w-[40px] border-none bg-transparent text-neutral-500 focus:outline-none focus:ring-0 sm:text-sm"+ />+ )}+ </div>+ </div>+ );+}diff --git a/lib/utils.ts b/lib/utils.tsindex 44967c3e..b8ac0464 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -12,6 +12,7 @@ import { rgb } from "pdf-lib";import { ParsedUrlQuery } from "querystring";import { toast } from "sonner";import { twMerge } from "tailwind-merge";+import * as chrono from "chrono-node";export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));@@ -213,6 +214,22 @@ export const getDateTimeLocal = (timestamp?: Date): string => {.join(":");};+export const formatDateTime = (+ datetime: Date | string,+ options?: Intl.DateTimeFormatOptions,+) => {+ if (datetime.toString() === "Invalid Date") return "";+ return new Date(datetime).toLocaleTimeString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ hour: "numeric",+ minute: "numeric",+ hour12: true,+ ...options,+ });+};+export async function hashPassword(password: string): Promise<string> {const saltRounds = 10;const hashedPassword = await bcrypt.hash(password, saltRounds);@@ -608,24 +625,69 @@ export const WITH_CUSTOM_PRESET_OPTION: { label: string; value: number | string];export const formatExpirationTime = (seconds: number) => {- if (seconds < 60) {+ // Define constants for time units+ const MINUTE = 60;+ const HOUR = 3600;+ const DAY = 86400;+ const YEAR = 31536000;+++ seconds = Math.ceil(seconds / MINUTE) * MINUTE;++ if (seconds < MINUTE) {return "Less than a minute";- } else if (seconds < 3600) {- const minutes = Math.floor(seconds / 60);- return `${minutes} minute${minutes > 1 ? "s" : ""}`;- } else if (seconds < 86400) {- const hours = Math.floor(seconds / 3600);- return `${hours} hour${hours > 1 ? "s" : ""}`;- } else if (seconds < 2592000) {- // Less than a month- const days = Math.floor(seconds / 86400);- return `${days} day${days > 1 ? "s" : ""}`;- } else if (seconds < 31536000) {- // Less than a year- const months = Math.floor(seconds / 2592000);- return `${months} month${months > 1 ? "s" : ""}`;- } else {- const years = Math.floor(seconds / 31536000);- return `${years} year${years > 1 ? "s" : ""}`;}++ // Return exact unit match if possible+ if (seconds % YEAR === 0) {+ const years = seconds / YEAR;+ return `${years} year${years !== 1 ? "s" : ""}`;+ }++ if (seconds % DAY === 0) {+ const days = seconds / DAY;+ return `${days} day${days !== 1 ? "s" : ""}`;+ }++ if (seconds % HOUR === 0 && seconds < DAY) {+ const hours = seconds / HOUR;+ return `${hours} hour${hours !== 1 ? "s" : ""}`;+ }++ if (seconds % MINUTE === 0 && seconds < HOUR) {+ const minutes = seconds / MINUTE;+ return `${minutes} minute${minutes !== 1 ? "s" : ""}`;+ }++ // Mixed unit fallbacks+ if (seconds < HOUR) {+ const minutes = Math.floor(seconds / MINUTE);+ return `${minutes} minute${minutes !== 1 ? "s" : ""}`;+ }++ if (seconds < DAY) {+ const hours = Math.floor(seconds / HOUR);+ const minutes = Math.floor((seconds % HOUR) / MINUTE);+ return `${hours} hour${hours !== 1 ? "s" : ""}` ++ (minutes > 0 ? ` and ${minutes} minute${minutes !== 1 ? "s" : ""}` : "");+ }++ if (seconds < YEAR) {+ const days = Math.floor(seconds / DAY);+ const hours = Math.floor((seconds % DAY) / HOUR);+ return `${days} day${days !== 1 ? "s" : ""}` ++ (hours > 0 ? ` and ${hours} hour${hours !== 1 ? "s" : ""}` : "");+ }++ // Years + remaining days+ const years = Math.floor(seconds / YEAR);+ const days = Math.floor((seconds % YEAR) / DAY);+ return `${years} year${years !== 1 ? "s" : ""}` ++ (days > 0 ? ` and ${days} day${days !== 1 ? "s" : ""}` : "");+};++// from DUB.IO+export const parseDateTime = (str: Date | string) => {+ if (str instanceof Date) return str;+ return chrono.parseDate(str);};\ No newline at end of filediff --git a/lib/zod/schemas/presets.ts b/lib/zod/schemas/presets.tsindex 4501183c..a8cf4e98 100644--- a/lib/zod/schemas/presets.ts+++ b/lib/zod/schemas/presets.ts@@ -52,7 +52,10 @@ export const presetDataSchema = z.object({enablePassword: z.boolean(),password: z.string().nullable(),expiresAt: z.string().nullable(),- expiresIn: z.number().nullable(),+ expiresIn: z.object({+ value: z.number(),+ type: z.enum(["natural", "normal"]),+ }),});export type PresetDataSchema = z.infer<typeof presetDataSchema>;diff --git a/package.json b/package.jsonindex 111a33e4..8311e094 100644--- a/package.json+++ b/package.json@@ -77,6 +77,7 @@"base-x": "^5.0.1","bcryptjs": "^3.0.2","bottleneck": "^2.19.5",+ "chrono-node": "^2.8.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",diff --git a/pages/settings/presets/[id].tsx b/pages/settings/presets/[id].tsxindex ccfda998..22f56aa2 100644--- a/pages/settings/presets/[id].tsx+++ b/pages/settings/presets/[id].tsx@@ -46,7 +46,10 @@ export type PRESET_DATA = Partial<DEFAULT_LINK_TYPE> & {enableAllowList?: boolean;enableDenyList?: boolean;expiresAt?: Date | null;- expiresIn?: number | null;+ expiresIn?: {+ value: number;+ type: "natural" | "normal";+ } | null;pId?: string | null;};@@ -110,7 +113,10 @@ export default function EditPreset() {id: null,name: preset.name,expiresAt: preset.expiresAt,- expiresIn: preset.expiresIn,+ expiresIn: preset.expiresIn as {+ value: number;+ type: "natural" | "normal";+ },password: preset.password,emailProtected: preset.emailProtected ?? true,emailAuthenticated: preset.emailAuthenticated ?? false,@@ -460,4 +466,4 @@ export default function EditPreset() {/></AppLayout>);-}+}\ No newline at end of filediff --git a/pages/settings/presets/index.tsx b/pages/settings/presets/index.tsxindex 873008b3..29ebc08c 100644--- a/pages/settings/presets/index.tsx+++ b/pages/settings/presets/index.tsx@@ -1,6 +1,8 @@import Link from "next/link";import { useRouter } from "next/router";++import { useState } from "react";import { useTeam } from "@/context/team-context";@@ -11,11 +13,10 @@ import { CircleHelpIcon, CrownIcon, PlusIcon } from "lucide-react";import useSWR from "swr";import { usePlan } from "@/lib/swr/use-billing";-import { fetcher } from "@/lib/utils";+import { fetcher, formatExpirationTime } from "@/lib/utils";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import AppLayout from "@/components/layouts/app";-import { formatExpirationTime } from "@/components/links/link-sheet/expirationIn-section";import { SettingsHeader } from "@/components/settings/settings-header";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";@@ -150,7 +151,8 @@ export default function Presets() {)}{preset.expiresIn && (<Badge variant="time">- Expires in {formatExpirationTime(preset.expiresIn)}+ Expires in{" "}+ {formatExpirationTime((preset.expiresIn as { type: "natural" | "normal"; value: number }).value)}</Badge>)}</div>diff --git a/pages/settings/presets/new.tsx b/pages/settings/presets/new.tsxindex 562668bc..9294c6ba 100644--- a/pages/settings/presets/new.tsx+++ b/pages/settings/presets/new.tsx@@ -42,7 +42,9 @@ export default function NewPreset() {const [isLoading, setIsLoading] = useState(false);const [data, setData] = useState<- DEFAULT_LINK_TYPE & { expiresIn?: number | null }+ DEFAULT_LINK_TYPE & {+ expiresIn?: { value: number; type: "natural" | "normal" } | null;+ }>({...DEFAULT_LINK_PROPS(LinkType.DOCUMENT_LINK),name: "",diff --git a/prisma/migrations/20250429175856_update_expires_in/migration.sql b/prisma/migrations/20250429175856_update_expires_in/migration.sqlnew file mode 100644index 00000000..49754cd8--- /dev/null+++ b/prisma/migrations/20250429175856_update_expires_in/migration.sql@@ -0,0 +1,9 @@+/*+ Warnings:++ - The `expiresIn` column on the `LinkPreset` table would be dropped and recreated. This will lead to data loss if there is data in the column.++*/+-- AlterTable+ALTER TABLE "LinkPreset" DROP COLUMN "expiresIn",+ADD COLUMN "expiresIn" JSONB;diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prismaindex e5468d90..a172f5c0 100644--- a/prisma/schema/link.prisma+++ b/prisma/schema/link.prisma@@ -98,7 +98,7 @@ model LinkPreset {allowList String[]enableDenyList Boolean? @default(false)denyList String[]- expiresIn Int? // how many days from link creation until it expires in seconds+ expiresIn Json? // how many days from link creation until it expires in seconds {value: 604800, type: "natural | normal"}expiresAt DateTime?enablePassword Boolean? @default(false)password String?