The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add intelligent datetime parser
Steven Tey5c8689937530
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.tsindex 232512c2b1..604268029e 100644--- a/apps/web/app/api/domains/[domain]/route.ts+++ b/apps/web/app/api/domains/[domain]/route.ts@@ -25,6 +25,7 @@ export const GET = withAuth(type: true,placeholder: true,clicks: true,+ expiredUrl: true,},});if (!data) {diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.tsindex 1a724a95b4..53915a53e2 100644--- a/apps/web/app/api/domains/route.ts+++ b/apps/web/app/api/domains/route.ts@@ -23,6 +23,7 @@ export const GET = withAuth(async ({ workspace }) => {type: true,placeholder: true,clicks: true,+ expiredUrl: true,},});return NextResponse.json(domains);diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex 65faa1e058..c85494768d 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -34,6 +34,7 @@ export async function processLink({password,rewrite,expiresAt,+ expiredUrl,ios,android,geo,@@ -217,6 +218,13 @@ export async function processLink({code: "unprocessable_entity",};}+ if (expiredUrl && !isValidUrl(getUrlFromString(expiredUrl))) {+ return {+ link: payload,+ error: "Invalid expired URL.",+ code: "unprocessable_entity",+ };+ }}// remove polyfill attributes from payloaddiff --git a/apps/web/lib/upstash.ts b/apps/web/lib/upstash.tsindex ea5f4fead0..67701c4054 100644--- a/apps/web/lib/upstash.ts+++ b/apps/web/lib/upstash.ts@@ -72,6 +72,7 @@ export async function formatRedisLink(proxy,rewrite,expiresAt,+ expiredUrl,ios,android,geo,@@ -89,6 +90,7 @@ export async function formatRedisLink(iframeable: await isIframeable({ url, requestDomain: domain }),}),...(expiresAt && { expiresAt: new Date(expiresAt) }),+ ...(expiredUrl && { expiredUrl }),...(ios && { ios }),...(android && { android }),...(geo && { geo: geo as object }),diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 31c9fd98ee..2f1228c5d8 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -6,6 +6,7 @@ import { TagSchema } from "./tags";export const getUrlQuerySchema = z.object({url: z.string()+ .describe("The destination URL of the short link.").transform((v) => getUrlFromString(v)).refine((v) => isValidUrl(v), { message: "Invalid URL" }),});@@ -126,21 +127,14 @@ export const createLinkBodySchema = z.object({.describe("Whether the short link is archived."),expiresAt: z.string()- .datetime({- message: "Invalid expiry date. Expiry date must be in ISO-8601 format.",- }).nullish().describe("The date and time when the short link will expire in ISO-8601 format. Must be in the future.",- )- .refine(- (expiresAt) => {- return expiresAt ? new Date(expiresAt) > new Date() : true;- },- {- message: "Expiry date must be in the future.",- },),+ expiredUrl: z+ .string()+ .nullish()+ .describe("The URL to redirect to when the short link has expired."),password: z.string().nullish()@@ -244,6 +238,11 @@ export const LinkSchema = z.describe("The date and time when the short link will expire in ISO-8601 format. Must be in the future.",),+ expiredUrl: z+ .string()+ .url()+ .nullable()+ .describe("The URL to redirect to when the short link has expired."),password: z.string().nullable()diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsxindex 32dec80cf8..61cec26490 100644--- a/apps/web/ui/domains/domain-card.tsx+++ b/apps/web/ui/domains/domain-card.tsx@@ -28,7 +28,6 @@ import DomainConfiguration from "./domain-configuration";import { useRef, useState } from "react";import { useDeleteDomainModal } from "../modals/delete-domain-modal";import { useArchiveDomainModal } from "../modals/archive-domain-modal";-import { toast } from "sonner";import { usePrimaryDomainModal } from "../modals/primary-domain-modal";export default function DomainCard({ props }: { props: DomainProps }) {diff --git a/apps/web/ui/modals/add-edit-domain-modal/index.tsx b/apps/web/ui/modals/add-edit-domain-modal/index.tsxindex 40f32d832e..6787e7816a 100644--- a/apps/web/ui/modals/add-edit-domain-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-domain-modal/index.tsx@@ -54,11 +54,10 @@ function AddEditDomainModal({type: "redirect",clicks: 0,projectId: id || "",- expiredUrl: "",},);- const { slug: domain, primary, target, type, placeholder, expiredUrl } = data;+ const { slug: domain, target, type, placeholder, expiredUrl } = data;const [lockDomain, setLockDomain] = useState(true);const [saving, setSaving] = useState(false);@@ -194,19 +193,7 @@ function AddEditDomainModal({<h2 className="text-sm font-medium text-gray-900">Landing Page</h2><InfoTooltip content="The page your users will get redirected to when they visit your domain." /></label>- {plan !== "free" ? (- <div className="relative mt-2 rounded-md shadow-sm">- <input- type="url"- name="target"- id="target"- className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- placeholder="https://example.com"- value={target}- onChange={(e) => setData({ ...data, target: e.target.value })}- />- </div>- ) : (+ {plan === "free" ? (<Tooltipcontent={<TooltipContent@@ -227,6 +214,18 @@ function AddEditDomainModal({https://yourdomain.com</div></Tooltip>+ ) : (+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ type="url"+ name="target"+ id="target"+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ placeholder="https://example.com"+ value={target}+ onChange={(e) => setData({ ...data, target: e.target.value })}+ />+ </div>)}</div>{target && (@@ -281,21 +280,7 @@ function AddEditDomainModal({<InfoTooltip content="URL to redirect your users to to when a link with this domain has expired." /></label><div className="relative mt-2 rounded-md shadow-sm">- {plan !== "free" ? (- <div className="relative mt-2 rounded-md shadow-sm">- <input- type="url"- name="expiredUrl"- id="expiredUrl"- className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- placeholder="https://yourwebsite.com"- value={expiredUrl}- onChange={(e) =>- setData({ ...data, expiredUrl: e.target.value })- }- />- </div>- ) : (+ {plan === "free" ? (<Tooltipcontent={<TooltipContent@@ -316,6 +301,20 @@ function AddEditDomainModal({https://yourwebsite.com</div></Tooltip>+ ) : (+ <div className="relative mt-2 rounded-md shadow-sm">+ <input+ type="url"+ name="expiredUrl"+ id="expiredUrl"+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"+ placeholder="https://yourwebsite.com"+ value={expiredUrl}+ onChange={(e) =>+ setData({ ...data, expiredUrl: e.target.value })+ }+ />+ </div>)}</div></div>diff --git a/apps/web/ui/modals/add-edit-link-modal/expiration-section.tsx b/apps/web/ui/modals/add-edit-link-modal/expiration-section.tsxindex 70ccc2f5ba..b1eb4ec961 100644--- a/apps/web/ui/modals/add-edit-link-modal/expiration-section.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/expiration-section.tsx@@ -1,6 +1,8 @@import useWorkspace from "@/lib/swr/use-workspace";import { LinkProps } from "@/lib/types";+import { AlertCircleFill } from "@/ui/shared/icons";import {+ ExpandingArrow,InfoTooltip,SimpleTooltipContent,Switch,@@ -10,10 +12,12 @@ import { TooltipContent } from "@dub/ui/src/tooltip";import {FADE_IN_ANIMATION_SETTINGS,HOME_DOMAIN,+ formatDateTime,getDateTimeLocal,+ parseDateTime,} from "@dub/utils";import { motion } from "framer-motion";-import { Dispatch, SetStateAction, useEffect, useState } from "react";+import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";export default function ExpirationSection({props,@@ -26,27 +30,32 @@ export default function ExpirationSection({}) {const { plan } = useWorkspace();const { queryParams } = useRouterStuff();+ const inputRef = useRef<HTMLInputElement>(null);- const { expiresAt } = data;- const [enabled, setEnabled] = useState(!!expiresAt);+ const { expiresAt, expiredUrl } = data;+ // const [enabled, setEnabled] = useState(!!expiresAt);+ const [enabled, setEnabled] = useState(true);useEffect(() => {if (enabled) {// if enabling, add previous expiration date if existssetData({...data,expiresAt: props?.expiresAt || expiresAt,+ expiredUrl: props?.expiredUrl || null,});} else {- // if disabling, remove expiration date- setData({ ...data, expiresAt: null });+ // if disabling, remove expiration date and expired URL+ setData({ ...data, expiresAt: null, expiredUrl: null });}}, [enabled]);+ const [expiredUrlError, setExpiredUrlError] = useState<string | null>(null);+return (<div className="relative border-b border-gray-200 pb-5"><div className="flex items-center justify-between"><div className="flex items-center justify-between space-x-2">- <h2 className="text-sm font-medium text-gray-900">Expiration Date</h2>+ <h2 className="text-sm font-medium text-gray-900">Link Expiration</h2><InfoTooltipcontent={<SimpleTooltipContent@@ -87,18 +96,97 @@ export default function ExpirationSection({</div>{enabled && (<motion.div className="mt-3" {...FADE_IN_ANIMATION_SETTINGS}>- <input- type="datetime-local"- id="expiresAt"- name="expiresAt"- min={getDateTimeLocal()}- value={expiresAt ? getDateTimeLocal(expiresAt) : ""}- step="60" // need to add step to prevent weird date bug (https://stackoverflow.com/q/19284193/10639526)- onChange={(e) => {- setData({ ...data, expiresAt: new Date(e.target.value) });- }}- className="flex w-full items-center justify-center space-x-2 rounded-md border border-gray-300 px-3 py-2 text-gray-500 shadow-sm transition-all hover:border-gray-800 focus:border-gray-800 focus:outline-none focus:ring-gray-500 sm:text-sm"- />+ <div className="flex w-full items-center justify-between rounded-md border border-gray-300 bg-white shadow-sm transition-all focus-within:border-gray-800 focus-within:outline-none focus-within:ring-1 focus-within:ring-gray-500">+ <input+ ref={inputRef}+ type="text"+ placeholder='E.g. "tomorrow at 5pm" or "in 2 hours"'+ onBlur={(e) => {+ if (e.target.value.length > 0) {+ const parsedDateTime = parseDateTime(e.target.value);+ if (parsedDateTime) {+ setData({ ...data, expiresAt: parsedDateTime });+ e.target.value = formatDateTime(parsedDateTime);+ }+ }+ }}+ className="flex-1 border-none bg-transparent text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-0 sm:text-sm"+ />+ <input+ type="datetime-local"+ id="expiresAt"+ name="expiresAt"+ value={expiresAt ? getDateTimeLocal(expiresAt) : ""}+ onChange={(e) => {+ const expiryDate = new Date(e.target.value);+ setData({ ...data, expiresAt: expiryDate });+ if (inputRef.current) {+ inputRef.current.value = formatDateTime(expiryDate);+ }+ }}+ className="w-[40px] border-none bg-transparent text-gray-500 focus:outline-none focus:ring-0 sm:text-sm"+ />+ </div>+ <div className="mt-4">+ <div className="flex items-center justify-between">+ <label+ htmlFor="expiredUrl"+ className="flex items-center space-x-2"+ >+ <p className="text-sm font-medium text-gray-700">Expired URL</p>+ <InfoTooltip+ content={+ <SimpleTooltipContent+ title="Redirect users to a specific URL when the link has expired."+ cta="Learn more."+ href={`${HOME_DOMAIN}/help/article/link-expiration`}+ />+ }+ />+ </label>+ {expiredUrlError && (+ <p className="text-sm text-red-600" id="key-error">+ Invalid url.+ </p>+ )}+ </div>+ <div className="relative mt-3 flex rounded-md shadow-sm">+ <input+ name="expiredUrl"+ id="expiredUrl"+ tabIndex={0}+ placeholder="https://yourwebsite.com"+ value={expiredUrl || ""}+ autoComplete="off"+ onChange={(e) => {+ setExpiredUrlError(null);+ setData({ ...data, expiredUrl: e.target.value });+ }}+ className={`${+ expiredUrlError+ ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500"+ } block w-full rounded-md focus:outline-none sm:text-sm`}+ aria-invalid="true"+ />+ {expiredUrlError && (+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">+ <AlertCircleFill+ className="h-5 w-5 text-red-500"+ aria-hidden="true"+ />+ </div>+ )}+ </div>+ <a+ href={`${HOME_DOMAIN}/help/article/link-expiration`}+ target="_blank"+ className="group mt-3 flex items-center text-sm text-gray-500 hover:text-gray-700"+ >+ <p>Or set a default expired URL for your domain</p>+ <ExpandingArrow />+ </a>+ </div></motion.div>)}</div>diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex 1875cc95a2..ae4b08ad5c 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -31,6 +31,7 @@},"dependencies": {"@sindresorhus/slugify": "^2.2.1",+ "chrono-node": "^2.7.5","clsx": "^2.1.0","ms": "^2.1.3","nanoid": "^5.0.1",diff --git a/packages/utils/src/functions/datetime.ts b/packages/utils/src/functions/datetime.tsindex 21128ed485..46880b4963 100644--- a/packages/utils/src/functions/datetime.ts+++ b/packages/utils/src/functions/datetime.ts@@ -1,3 +1,5 @@+import * as chrono from "chrono-node";+export const getDateTimeLocal = (timestamp?: Date): string => {const d = timestamp ? new Date(timestamp) : new Date();if (d.toString() === "Invalid Date") return "";@@ -8,6 +10,11 @@ export const getDateTimeLocal = (timestamp?: Date): string => {.join(":");};+// Function to parse a date string into a Date object+export const parseDateTime = (text: string) => {+ return chrono.parseDate(text);+};+export const formatDate = (dateString: string) => {return new Date(dateString).toLocaleDateString("en-US", {day: "numeric",@@ -17,6 +24,17 @@ export const formatDate = (dateString: string) => {});};+export const formatDateTime = (datetime: Date | string) => {+ return new Date(datetime).toLocaleTimeString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ hour: "numeric",+ minute: "numeric",+ hour12: true,+ });+};+export const getFirstAndLastDay = (day: number) => {const today = new Date();const currentDay = today.getDate();diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 27a74a62e9..f03092ed8d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -483,6 +483,9 @@ importers:'@sindresorhus/slugify':specifier: ^2.2.1version: 2.2.1+ chrono-node:+ specifier: ^2.7.5+ version: 2.7.5clsx:specifier: ^2.1.0version: 2.1.0@@ -8195,6 +8198,13 @@ packages:engines: {node: '>=6.0'}dev: false+ resolution: {integrity: sha512-VJWqFN5rWmXVvXAxOD4i0jX8Tb4cLswaslyaAFhxM45zNXPsZleygPbgiaYBD7ORb9fj07zBgJb0Q6eKL+0iJg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ dependencies:+ dayjs: 1.11.10+ dev: false+resolution: {integrity: sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==}dev: false