The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
made advanced options...optional, with <Switch/>. also fixed edit link reassign user bug
Steven Tey6c1e7b714b62
diff --git a/components/app/links/link-filters/index.tsx b/components/app/links/link-filters/index.tsxindex 882b76267d..108f87db98 100644--- a/components/app/links/link-filters/index.tsx+++ b/components/app/links/link-filters/index.tsx@@ -2,7 +2,7 @@ import { useRouter } from "next/router";import { useState } from "react";import { AnimatePresence, motion } from "framer-motion";import { ChevronDown, Filter } from "@/components/shared/icons";-import { ANIMATION_SETTINGS } from "@/lib/constants";+import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";import LinkSort from "./link-sort";import StatusFilter from "./status-filter";import UserFilter from "./user-filter";@@ -32,7 +32,7 @@ export default function LinkFilters() {{showFilters && (<motion.divclassName="flex w-full flex-col space-y-2 border-t border-gray-200 py-5 sm:hidden"- {...ANIMATION_SETTINGS}+ {...SWIPE_REVEAL_ANIMATION_SETTINGS}><LinkSort /><StatusFilter />diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex 01dca999a8..83d199573e 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -31,6 +31,16 @@ import PasswordSection from "./password-section";import UTMSection from "./utm-section";import Preview from "./preview";+function process(data: LinkProps) {+ const { ogEnabled, ...rest } = data;+ return {+ ...rest,+ title: ogEnabled ? rest.title : null,+ description: ogEnabled ? rest.description : null,+ image: ogEnabled ? rest.image : null,+ };+}+function AddEditLinkModal({showAddEditLinkModal,setShowAddEditLinkModal,@@ -52,24 +62,32 @@ function AddEditLinkModal({const [saving, setSaving] = useState(false);const [data, setData] = useState<LinkProps>(- props || {- domain: domain || "",- key: "",- url: "",- archived: false,- expiresAt: null,- password: null,+ props+ ? {+ ...props,+ ogEnabled:+ props.title && props.description && props.image ? true : false,+ }+ : {+ domain: domain || "",+ key: "",+ url: "",+ archived: false,+ expiresAt: null,+ password: null,- title: null,- description: null,- image: null,+ title: null,+ description: null,+ image: null,- clicks: 0,- userId: "",- createdAt: new Date(),- },+ clicks: 0,+ userId: "",+ createdAt: new Date(),++ ogEnabled: false,+ },);- const { key, url, password, expiresAt } = data;+ const { key, url, password, title, description, image, ogEnabled } = data;const [debouncedKey] = useDebounce(key, 500);useEffect(() => {@@ -134,11 +152,12 @@ function AddEditLinkModal({}));return;}- if (- // only generate metatags if:- showAddEditLinkModal && // modal is open- (!props?.image || debouncedUrl !== props?.url.split("?")[0]) // there's no image or the url has changed- ) {+ /**+ * Only generate metatags if:+ * - modal is open+ * - there's no image or the url has changed+ **/+ if (showAddEditLinkModal && !ogEnabled) {// using a setTimeout to delay until the loading screen fades in (0.2 delay in framer motion as well)setTimeout(() => {setData((prev) => ({@@ -153,11 +172,11 @@ function AddEditLinkModal({new URL(debouncedUrl);setGeneratingMetatags(true);fetch(`/api/edge/metatags?url=${debouncedUrl}`).then(async (res) => {+ setGeneratingMetatags(false);if (res.status === 200) {const results = await res.json();setData((prev) => ({ ...prev, ...results }));}- setGeneratingMetatags(false);});} catch (e) {console.log("not a valid url");@@ -193,8 +212,6 @@ function AddEditLinkModal({}}, [props]);- const expired = expiresAt && new Date() > new Date(expiresAt);-const [scrolled, setScrolled] = useState(false);const handleScroll = (event: UIEvent<HTMLElement>) => {if (event.currentTarget.scrollTop > 144) {@@ -204,6 +221,30 @@ function AddEditLinkModal({}};+ const saveDisabled = useMemo(() => {+ /*+ Disable save if:+ - modal is not open+ - saving is in progress+ - key is invalid+ - url is invalid+ - for an existing link, there's no changes+ */+ if (!showAddEditLinkModal) {+ return true;+ } else if (+ saving ||+ keyExistsError ||+ urlError ||+ (props &&+ Object.entries(props).every(([key, value]) => value === data[key]))+ ) {+ return true;+ } else {+ return false;+ }+ }, [saving, keyExistsError, urlError, props, data, showAddEditLinkModal]);+return (<ModalshowModal={showAddEditLinkModal}@@ -249,16 +290,6 @@ function AddEditLinkModal({)}</div>- {/* {id && (- <div className="absolute -mt-3.5 flex w-full justify-center space-x-2 [&>*]:flex [&>*]:h-7 [&>*]:items-center [&>*]:rounded-full [&>*]:px-4 [&>*]:text-xs [&>*]:uppercase [&>*]:text-white">- {expired ? (- <span className="bg-amber-500">Expired</span>- ) : (- <span className="bg-green-500">Active</span>- )}- {archived && <span className="bg-gray-400">Archived</span>}- </div>- )} */}<formonSubmit={async (e) => {e.preventDefault();@@ -268,7 +299,7 @@ function AddEditLinkModal({headers: {"Content-Type": "application/json",},- body: JSON.stringify(data),+ body: JSON.stringify(process(data)),}).then((res) => {setSaving(false);if (res.status === 200) {@@ -419,21 +450,21 @@ function AddEditLinkModal({</div></div>- <div className="grid gap-8 px-4 sm:px-16">+ <div className="grid gap-5 px-4 sm:px-16"><OGSection{...{ data, setData }}generatingMetatags={generatingMetatags}/>- <UTMSection {...{ data, setData }} />+ <UTMSection {...{ props, data, setData }} /><PasswordSection {...{ data, setData }} /><ExpirationSection {...{ data, setData }} /></div><div className="sticky bottom-0 bg-gray-50 px-4 py-8 sm:px-16"><button- disabled={saving || keyExistsError}+ disabled={saveDisabled}className={`${- saving || keyExistsError+ saveDisabled? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400": "border-black bg-black text-white hover:bg-white hover:text-black"} flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}diff --git a/components/app/modals/add-edit-link-modal/og-section.tsx b/components/app/modals/add-edit-link-modal/og-section.tsxindex 36ca56db61..b3b20ef87e 100644--- a/components/app/modals/add-edit-link-modal/og-section.tsx+++ b/components/app/modals/add-edit-link-modal/og-section.tsx@@ -2,20 +2,10 @@ import { Dispatch, SetStateAction, useCallback, useState } from "react";import { motion } from "framer-motion";import TextareaAutosize from "react-textarea-autosize";import BlurImage from "@/components/shared/blur-image";-import {- LoadingCircle,- QuestionCircle,- UploadCloud,-} from "@/components/shared/icons";+import { LoadingCircle, UploadCloud } from "@/components/shared/icons";import { LinkProps } from "@/lib/types";-import Tooltip from "@/components/shared/tooltip";--const ANIMATION_SETTINGS = {- initial: { opacity: 0 },- animate: { opacity: 1 },- exit: { opacity: 0 },- transition: { duration: 0.2 },-};+import Switch from "@/components/shared/switch";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";export default function OGSection({data,@@ -26,7 +16,7 @@ export default function OGSection({setData: Dispatch<SetStateAction<LinkProps>>;generatingMetatags: boolean;}) {- const { title, description, image } = data;+ const { title, description, image, ogEnabled } = data;const [fileSizeTooBig, setFileSizeTooBig] = useState(false);@@ -52,152 +42,158 @@ export default function OGSection({const randomIdx = Math.floor(Math.random() * 100);return (- <div className="grid gap-5">- <div className="flex items-center">+ <div className="grid gap-5 border-b border-gray-200 pb-5">+ <div className="flex items-center justify-between"><h2 className="text-sm font-medium text-gray-900">Custom Social Media Cards</h2>- <Tooltip- content={- <div className="max-w-sm p-3">- <p className="mt-2 block text-sm text-gray-500">- If you use custom social previews,{" "}- <span className="font-semibold text-black">- be sure to set all 3 sections (title, description, image)- </span>- , or the default OG tags of the target URL will be used.- </p>- </div>- }- >- <div className="flex h-4 w-8 justify-center">- <QuestionCircle className="h-4 w-4 text-gray-600" />- </div>- </Tooltip>+ <Switch+ fn={() => setData((prev) => ({ ...prev, ogEnabled: !ogEnabled }))}+ checked={ogEnabled}+ /></div>+ {/* <p className="mt-2 block text-sm text-gray-500">+ If you use custom social previews,{" "}+ <span className="font-semibold text-black">+ be sure to set all 3 sections (title, description, image)+ </span>+ , or the default OG tags of the target URL will be used.+ </p> */}- <div>- <div className="flex items-center justify-between">- <p className="block text-sm font-medium text-gray-700">Image</p>- {fileSizeTooBig && (- <p className="text-sm text-red-500">File size too big (max 1MB)</p>- )}- </div>- <label- htmlFor={`image-${randomIdx}`}- className="group relative mt-1 flex h-[14rem] cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"+ {ogEnabled && (+ <motion.div+ key="og-options"+ {...FADE_IN_ANIMATION_SETTINGS}+ className="grid gap-5">- {generatingMetatags && (- <motion.div- className="absolute flex h-full w-full items-center justify-center rounded-md bg-white"- {...ANIMATION_SETTINGS}+ <div>+ <div className="flex items-center justify-between">+ <p className="block text-sm font-medium text-gray-700">Image</p>+ {fileSizeTooBig && (+ <p className="text-sm text-red-500">+ File size too big (max 1MB)+ </p>+ )}+ </div>+ <label+ htmlFor={`image-${randomIdx}`}+ className="group relative mt-1 flex h-[14rem] cursor-pointer flex-col items-center justify-center rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50">- <LoadingCircle />- </motion.div>- )}- {image ? (- image.startsWith("https://res.cloudinary.com") ? (- <BlurImage- src={image}- alt="Preview"- width={1200}- height={627}- className="h-full w-full rounded-md object-cover transition-all hover:brightness-95"+ {generatingMetatags && (+ <motion.div+ className="absolute flex h-full w-full items-center justify-center rounded-md bg-white"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <LoadingCircle />+ </motion.div>+ )}+ {image ? (+ image.startsWith("https://res.cloudinary.com") ? (+ <BlurImage+ src={image}+ alt="Preview"+ width={1200}+ height={627}+ className="h-full w-full rounded-md object-cover transition-all hover:brightness-95"+ />+ ) : (+ <img+ src={image}+ alt="Preview"+ className="h-full w-full rounded-md object-cover transition-all hover:brightness-95"+ />+ )+ ) : (+ <>+ <UploadCloud className="h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95" />+ <p className="mt-2 text-sm text-gray-500">+ Recommended: 1200 x 627 pixels+ </p>+ <span className="sr-only">OG Image upload</span>+ </>+ )}+ </label>+ <div className="mt-1 flex rounded-md shadow-sm">+ <input+ id={`image-${randomIdx}`}+ name="image"+ type="file"+ accept="image/*"+ className="sr-only"+ onChange={onChangePicture}/>- ) : (- <img- src={image}- alt="Preview"- className="h-full w-full rounded-md object-cover transition-all hover:brightness-95"- />- )- ) : (- <>- <UploadCloud className="h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95" />- <p className="mt-2 text-sm text-gray-500">- Recommended: 1200 x 627 pixels- </p>- <span className="sr-only">OG Image upload</span>- </>- )}- </label>- <div className="mt-1 flex rounded-md shadow-sm">- <input- id={`image-${randomIdx}`}- name="image"- type="file"- accept="image/*"- className="sr-only"- onChange={onChangePicture}- />- </div>- </div>+ </div>+ </div>- <div>- <label- htmlFor={`title-${randomIdx}`}- className="block text-sm font-medium text-gray-700"- >- Title- </label>- <div className="relative mt-1 flex rounded-md shadow-sm">- {generatingMetatags && (- <motion.div- className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"- {...ANIMATION_SETTINGS}+ <div>+ <label+ htmlFor={`title-${randomIdx}`}+ className="block text-sm font-medium text-gray-700">- <LoadingCircle />- </motion.div>- )}- <TextareaAutosize- name="title"- id={`title-${randomIdx}`}- minRows={3}- className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"- placeholder="Dub - Open Source Bitly Alternative"- value={title || ""}- onChange={(e) => {- setData({ ...data, title: e.target.value });- }}- aria-invalid="true"- />- </div>- </div>+ Title+ </label>+ <div className="relative mt-1 flex rounded-md shadow-sm">+ {generatingMetatags && (+ <motion.div+ className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <LoadingCircle />+ </motion.div>+ )}+ <TextareaAutosize+ name="title"+ id={`title-${randomIdx}`}+ minRows={3}+ maxLength={60}+ className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"+ placeholder="Dub - Open Source Bitly Alternative"+ value={title || ""}+ onChange={(e) => {+ setData({ ...data, title: e.target.value });+ }}+ aria-invalid="true"+ />+ </div>+ </div>- <div>- <label- htmlFor={`description-${randomIdx}`}- className="block text-sm font-medium text-gray-700"- >- Description- </label>- <div className="relative mt-1 flex rounded-md shadow-sm">- {generatingMetatags && (- <motion.div- className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"- {...ANIMATION_SETTINGS}+ <div>+ <label+ htmlFor={`description-${randomIdx}`}+ className="block text-sm font-medium text-gray-700">- <LoadingCircle />- </motion.div>- )}- <TextareaAutosize- name="description"- id={`description-${randomIdx}`}- minRows={3}- className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"- placeholder="Dub is open-source link management tool for modern marketing teams to create, share, and track short links."- value={description || ""}- onChange={(e) => {- setData({- ...data,- description:- e.target.value.length > 0 ? e.target.value : undefined,- });- }}- aria-invalid="true"- />- </div>- </div>+ Description+ </label>+ <div className="relative mt-1 flex rounded-md shadow-sm">+ {generatingMetatags && (+ <motion.div+ className="absolute flex h-full w-full items-center justify-center rounded-md border border-gray-300 bg-white"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <LoadingCircle />+ </motion.div>+ )}+ <TextareaAutosize+ name="description"+ id={`description-${randomIdx}`}+ minRows={3}+ maxLength={200}+ className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"+ placeholder="Dub is open-source link management tool for modern marketing teams to create, share, and track short links."+ value={description || ""}+ onChange={(e) => {+ setData({+ ...data,+ description:+ e.target.value.length > 0 ? e.target.value : undefined,+ });+ }}+ aria-invalid="true"+ />+ </div>+ </div>+ </motion.div>+ )}</div>);}diff --git a/components/app/modals/add-edit-link-modal/utm-section.tsx b/components/app/modals/add-edit-link-modal/utm-section.tsxindex e291334938..a6e8e8074f 100644--- a/components/app/modals/add-edit-link-modal/utm-section.tsx+++ b/components/app/modals/add-edit-link-modal/utm-section.tsx@@ -1,6 +1,9 @@-import { Dispatch, SetStateAction, useMemo } from "react";+import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";import { LinkProps } from "@/lib/types";+import { motion } from "framer-motion";import { constructURLFromUTMParams, getParamsFromURL } from "@/lib/utils";+import Switch from "@/components/shared/switch";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";const paramsMetadata = [{ display: "UTM Source", key: "utm_source", examples: "twitter, facebook" },@@ -11,9 +14,11 @@ const paramsMetadata = [];export default function UTMSection({+ props,data,setData,}: {+ props: LinkProps;data: LinkProps;setData: Dispatch<SetStateAction<LinkProps>>;}) {@@ -31,38 +36,60 @@ export default function UTMSection({return getParamsFromURL(url);}, [url]);+ const [enabled, setEnabled] = useState(+ paramsMetadata.some((param) => params[param.key]),+ );++ useEffect(() => {+ if (enabled) {+ // if enabling, add all params from props if exists+ setData((prev) => ({+ ...prev,+ url: props?.url || url,+ }));+ } else {+ // if disabling, remove all params+ setData((prev) => ({ ...prev, url: prev.url.split("?")[0] }));+ }+ }, [enabled]);+return (- <div>- <h2 className="text-sm font-medium text-gray-900">UTM Builder</h2>- <div className="mt-1 grid gap-2">- {paramsMetadata.map(({ display, key, examples }) => (- <div key={key} className="relative mt-1 flex rounded-md shadow-sm">- <span className="flex w-60 items-center justify-center whitespace-nowrap rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-sm text-gray-500">- {display}- </span>- <input- type="text"- name={key}- id={key}- disabled={!isValidUrl}- className={`${- isValidUrl ? "" : "cursor-not-allowed bg-gray-100"- } block w-full rounded-r-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500`}- placeholder={examples}- value={params[key] || ""}- onChange={(e) => {- setData({- ...data,- url: constructURLFromUTMParams(url, {- ...params,- [key]: e.target.value,- }),- });- }}- />- </div>- ))}+ <div className="border-b border-gray-200 pb-5">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-gray-900">UTM Builder</h2>+ <Switch fn={() => setEnabled(!enabled)} checked={enabled} /></div>+ {enabled && (+ <motion.div className="mt-1 grid gap-2" {...FADE_IN_ANIMATION_SETTINGS}>+ {paramsMetadata.map(({ display, key, examples }) => (+ <div key={key} className="relative mt-1 flex rounded-md shadow-sm">+ <span className="flex w-60 items-center justify-center whitespace-nowrap rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-sm text-gray-500">+ {display}+ </span>+ <input+ type="text"+ name={key}+ id={key}+ disabled={!isValidUrl}+ className={`${+ isValidUrl ? "" : "cursor-not-allowed bg-gray-100"+ } block w-full rounded-r-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500`}+ placeholder={examples}+ value={params[key] || ""}+ onChange={(e) => {+ setData({+ ...data,+ url: constructURLFromUTMParams(url, {+ ...params,+ [key]: e.target.value,+ }),+ });+ }}+ />+ </div>+ ))}+ </motion.div>+ )}</div>);}diff --git a/lib/constants/index.ts b/lib/constants/index.tsindex d8e3a62783..691c3370c9 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -13,13 +13,20 @@ export const FRAMER_MOTION_LIST_ITEM_VARIANTS = {show: { scale: 1, opacity: 1, transition: { type: "spring" } },};-export const ANIMATION_SETTINGS = {+export const SWIPE_REVEAL_ANIMATION_SETTINGS = {initial: { height: 0 },animate: { height: "auto" },exit: { height: 0 },transition: { duration: 0.2, bounce: 0 },};+export const FADE_IN_ANIMATION_SETTINGS = {+ initial: { opacity: 0 },+ animate: { opacity: 1 },+ exit: { opacity: 0 },+ transition: { duration: 0.2 },+};+export const HOME_HOSTNAMES = new Set([// comment for better diffs"dub.sh",diff --git a/lib/swr/use-metatags.ts b/lib/swr/use-metatags.tsnew file mode 100644index 0000000000..1e360094d0--- /dev/null+++ b/lib/swr/use-metatags.ts@@ -0,0 +1,16 @@+import useSWR from "swr";+import { MetatagsProps } from "@/lib/types";+import { fetcher } from "@/lib/utils";+import { useDebounce } from "use-debounce";++export default function useMetatags(debouncedUrl: string, generate: boolean) {+ const { data, isValidating } = useSWR<MetatagsProps>(+ generate && `/api/edge/metatags?url=${debouncedUrl}`,+ fetcher,+ );++ return {+ metatags: data,+ generatingMetatags: isValidating,+ };+}diff --git a/lib/types.ts b/lib/types.tsindex 890693f142..a1a5f9552b 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -20,6 +20,9 @@ export interface LinkProps {userId: string;createdAt: Date;++ // only used on client-side+ ogEnabled?: boolean;}export interface ProjectProps {diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.tsindex 7611aa8885..8b0e3f71d7 100644--- a/pages/api/edge/metatags.ts+++ b/pages/api/edge/metatags.ts@@ -69,7 +69,6 @@ const getMetadataFromUrl = async (url: string) => {);console.log(obj);return {- hostname: new URL(url).hostname,title: obj["title"] || obj["og:title"] || obj["twitter:title"],description:obj["description"] ||diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.tsindex 4bcd487a9e..a6a3404f93 100644--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts@@ -26,7 +26,6 @@ export default withProjectAuth({domain,...req.body,- userId: session.user.id,},oldKey,slug,