Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add UTM templates to settings

Tim Wilsonafe4971f41a8
diff --git a/apps/web/app/api/utm-templates/[id]/route.ts b/apps/web/app/api/utm-templates/[id]/route.ts
index 9ba9af5cdb..039ce7aedd 100644
--- a/apps/web/app/api/utm-templates/[id]/route.ts
+++ b/apps/web/app/api/utm-templates/[id]/route.ts
@@ -1,8 +1,59 @@
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import { updateUTMTemplateBodySchema } from "@/lib/zod/schemas/utm-templates";
import { NextResponse } from "next/server";
+// PATCH /api/utm-templates/[id] – update a UTM template
+export const PATCH = withWorkspace(
+ async ({ req, params, workspace }) => {
+ const { id } = params;
+ const props = updateUTMTemplateBodySchema.parse(await req.json());
+
+ const template = await prisma.utmTemplate.findFirst({
+ where: {
+ id,
+ projectId: workspace.id,
+ },
+ });
+
+ if (!template) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Template not found.",
+ });
+ }
+
+ try {
+ const response = await prisma.utmTemplate.update({
+ where: {
+ id,
+ projectId: workspace.id,
+ },
+ data: {
+ ...props,
+ },
+ });
+
+ return NextResponse.json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A template with that name already exists.",
+ });
+ }
+
+ throw error;
+ }
+ },
+ {
+ requiredPermissions: ["links.write"],
+ },
+);
+
+export const PUT = PATCH;
+
// DELETE /api/utm-templates/[id] – delete a UTM template for a workspace
export const DELETE = withWorkspace(
async ({ params, workspace }) => {
diff --git a/apps/web/app/api/utm-templates/route.ts b/apps/web/app/api/utm-templates/route.ts
index a414ef8b8b..0a4057b3f9 100644
--- a/apps/web/app/api/utm-templates/route.ts
+++ b/apps/web/app/api/utm-templates/route.ts
@@ -1,3 +1,4 @@
+import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { createUTMTemplateBodySchema } from "@/lib/zod/schemas/utm-templates";
@@ -13,6 +14,9 @@ export const GET = withWorkspace(
orderBy: {
updatedAt: "desc",
},
+ include: {
+ user: true,
+ },
take: 50,
});
@@ -28,21 +32,26 @@ export const POST = withWorkspace(
async ({ req, workspace, session, headers }) => {
const props = createUTMTemplateBodySchema.parse(await req.json());
- const response = await prisma.utmTemplate.upsert({
+ const existingTemplate = await prisma.utmTemplate.findFirst({
where: {
- projectId_name: {
- projectId: workspace.id,
- name: props.name,
- },
+ projectId: workspace.id,
+ name: props.name,
},
- create: {
+ });
+
+ if (existingTemplate) {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A template with that name already exists.",
+ });
+ }
+
+ const response = await prisma.utmTemplate.create({
+ data: {
projectId: workspace.id,
userId: session?.user.id,
...props,
},
- update: {
- ...props,
- },
});
return NextResponse.json(response, {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page-client.tsx
new file mode 100644
index 0000000000..a6f11f832f
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page-client.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { UtmTemplateWithUserProps } from "@/lib/types";
+import { useAddEditUtmTemplateModal } from "@/ui/modals/add-edit-utm-template.modal";
+import EmptyState from "@/ui/shared/empty-state";
+import { CardList } from "@dub/ui";
+import { DiamondTurnRight } from "@dub/ui/src";
+import { fetcher } from "@dub/utils";
+import { Dispatch, SetStateAction, createContext, useState } from "react";
+import useSWR from "swr";
+import { TemplateCard } from "./template-card";
+import { TemplateCardPlaceholder } from "./template-card-placeholder";
+
+export const TemplatesListContext = createContext<{
+ openMenuTemplateId: string | null;
+ setOpenMenuTemplateId: Dispatch<SetStateAction<string | null>>;
+}>({
+ openMenuTemplateId: null,
+ setOpenMenuTemplateId: () => {},
+});
+
+export default function WorkspaceUtmTemplatesClient() {
+ const { id: workspaceId } = useWorkspace();
+
+ const { data: templates, isLoading } = useSWR<UtmTemplateWithUserProps[]>(
+ workspaceId && `/api/utm-templates?workspaceId=${workspaceId}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ const [openMenuTemplateId, setOpenMenuTemplateId] = useState<string | null>(
+ null,
+ );
+
+ const { AddEditUtmTemplateModal, AddUtmTemplateButton } =
+ useAddEditUtmTemplateModal();
+
+ return (
+ <>
+ <div className="grid gap-5">
+ <div className="flex flex-wrap justify-between gap-6">
+ <div className="flex items-center gap-x-2">
+ <h1 className="text-2xl font-semibold tracking-tight text-black">
+ UTM Templates
+ </h1>
+ </div>
+ <div className="flex w-full flex-wrap items-center gap-3 sm:w-auto">
+ <AddUtmTemplateButton />
+ </div>
+ </div>
+ {workspaceId && <AddEditUtmTemplateModal />}
+
+ {isLoading || templates?.length ? (
+ <TemplatesListContext.Provider
+ value={{ openMenuTemplateId, setOpenMenuTemplateId }}
+ >
+ <CardList variant="compact" loading={isLoading}>
+ {templates?.length
+ ? templates.map((template) => (
+ <TemplateCard key={template.id} template={template} />
+ ))
+ : Array.from({ length: 6 }).map((_, idx) => (
+ <TemplateCardPlaceholder key={idx} />
+ ))}
+ </CardList>
+ </TemplatesListContext.Provider>
+ ) : (
+ <div className="flex flex-col items-center gap-4 rounded-xl border border-gray-200 py-10">
+ <EmptyState
+ icon={DiamondTurnRight}
+ title="No templates found for this workspace"
+ />
+ <AddUtmTemplateButton />
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page.tsx
new file mode 100644
index 0000000000..56a5d78fd6
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/page.tsx
@@ -0,0 +1,10 @@
+import { Suspense } from "react";
+import WorkspaceUtmTemplatesClient from "./page-client";
+
+export default function WorkspaceUtmTemplates() {
+ return (
+ <Suspense>
+ <WorkspaceUtmTemplatesClient />
+ </Suspense>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card-placeholder.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card-placeholder.tsx
new file mode 100644
index 0000000000..301f4cc899
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card-placeholder.tsx
@@ -0,0 +1,18 @@
+import { CardList } from "@dub/ui";
+
+export function TemplateCardPlaceholder() {
+ return (
+ <CardList.Card>
+ <div className="flex h-8 items-center justify-between gap-5 sm:gap-8 md:gap-12">
+ <div className="flex items-center gap-3">
+ <div className="h-5 w-5 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-5 w-16 animate-pulse rounded-md bg-gray-200 sm:w-32" />
+ </div>
+ <div className="flex items-center gap-5 sm:gap-8 md:gap-12">
+ <div className="h-5 w-16 animate-pulse rounded-md bg-gray-200" />
+ <div className="w-8" />
+ </div>
+ </div>
+ </CardList.Card>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card.tsx
new file mode 100644
index 0000000000..0577c59545
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/utm-templates/template-card.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { UtmTemplateWithUserProps } from "@/lib/types";
+import { useAddEditUtmTemplateModal } from "@/ui/modals/add-edit-utm-template.modal";
+import { Delete, ThreeDots } from "@/ui/shared/icons";
+import {
+ Avatar,
+ Button,
+ CardList,
+ Popover,
+ Tooltip,
+ useKeyboardShortcut,
+} from "@dub/ui";
+import {
+ DiamondTurnRight,
+ LoadingSpinner,
+ PenWriting,
+} from "@dub/ui/src/icons";
+import { cn, formatDate } from "@dub/utils";
+import { useContext, useState } from "react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { TemplatesListContext } from "./page-client";
+
+export function TemplateCard({
+ template,
+}: {
+ template: UtmTemplateWithUserProps;
+}) {
+ const { id } = useWorkspace();
+
+ const { openMenuTemplateId, setOpenMenuTemplateId } =
+ useContext(TemplatesListContext);
+ const openPopover = openMenuTemplateId === template.id;
+ const setOpenPopover = (open: boolean) => {
+ setOpenMenuTemplateId(open ? template.id : null);
+ };
+
+ const [processing, setProcessing] = useState(false);
+
+ const { AddEditUtmTemplateModal, setShowAddEditUtmTemplateModal } =
+ useAddEditUtmTemplateModal({
+ props: template,
+ });
+
+ const handleDelete = async () => {
+ if (!confirm("Are you sure you want to delete this template?")) return;
+
+ setProcessing(true);
+ fetch(`/api/utm-templates/${template.id}?workspaceId=${id}`, {
+ method: "DELETE",
+ })
+ .then(async (res) => {
+ if (res.ok) {
+ await mutate(`/api/utm-templates?workspaceId=${id}`);
+ toast.success("Template deleted");
+ } else {
+ const { error } = await res.json();
+ toast.error(error.message);
+ }
+ })
+ .finally(() => setProcessing(false));
+ };
+
+ return (
+ <>
+ <AddEditUtmTemplateModal />
+
+ <CardList.Card
+ onClick={() => setShowAddEditUtmTemplateModal(true)}
+ innerClassName={cn(
+ "flex items-center justify-between gap-5 sm:gap-8 md:gap-12 text-sm transition-opacity",
+ processing && "opacity-50",
+ )}
+ >
+ <div className="flex min-w-0 grow items-center gap-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <DiamondTurnRight className="size-5 shrink-0 text-gray-500" />
+ <span className="min-w-0 truncate whitespace-nowrap font-medium text-gray-800">
+ {template.name}
+ </span>
+ </div>
+ <UserAvatar template={template} />
+ </div>
+
+ <div className="text-sm text-gray-500">
+ {formatDate(template.updatedAt, { month: "short" })}
+ </div>
+
+ <div className="flex items-center gap-5 sm:gap-8 md:gap-12">
+ <Popover
+ content={
+ <div className="grid w-full gap-px p-2 sm:w-48">
+ <Button
+ text="Edit"
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddEditUtmTemplateModal(true);
+ }}
+ icon={<PenWriting className="h-4 w-4" />}
+ shortcut="E"
+ className="h-9 px-2 font-medium"
+ />
+ <Button
+ text="Delete"
+ variant="danger-outline"
+ onClick={handleDelete}
+ icon={<Delete className="h-4 w-4" />}
+ shortcut="X"
+ className="h-9 px-2 font-medium"
+ />
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ variant="secondary"
+ className={cn(
+ "h-8 px-1.5 outline-none transition-all duration-200",
+ "border-transparent data-[state=open]:border-gray-500 sm:group-hover/card:data-[state=closed]:border-gray-200",
+ )}
+ icon={
+ processing ? (
+ <LoadingSpinner className="h-5 w-5 shrink-0" />
+ ) : (
+ <ThreeDots className="h-5 w-5 shrink-0" />
+ )
+ }
+ onClick={() => {
+ setOpenPopover(!openPopover);
+ }}
+ />
+ </Popover>
+ </div>
+
+ {/* Use consumer + separate component to use hovered state from CardList.Card context */}
+ <CardList.Card.Context.Consumer>
+ {({ hovered }) => (
+ <TemplateCardKeyboardShortcuts
+ enabled={openPopover || (hovered && openMenuTemplateId === null)}
+ onKeyDown={(e) => {
+ setOpenPopover(false);
+ switch (e.key) {
+ case "e":
+ setShowAddEditUtmTemplateModal(true);
+ break;
+ case "x":
+ handleDelete();
+ break;
+ }
+ }}
+ />
+ )}
+ </CardList.Card.Context.Consumer>
+ </CardList.Card>
+ </>
+ );
+}
+
+function TemplateCardKeyboardShortcuts({
+ enabled,
+ onKeyDown,
+}: {
+ enabled: boolean;
+ onKeyDown: (e: KeyboardEvent) => void;
+}) {
+ useKeyboardShortcut(["e", "x"], onKeyDown, {
+ enabled,
+ });
+
+ return null;
+}
+
+function UserAvatar({ template }: { template: UtmTemplateWithUserProps }) {
+ const { user } = template;
+
+ return (
+ <Tooltip
+ content={
+ <div className="w-full p-3">
+ <Avatar user={user} className="h-8 w-8" />
+ <div className="mt-2 flex items-center gap-1.5">
+ <p className="text-sm font-semibold text-gray-700">
+ {user?.name || user?.email || "Anonymous User"}
+ </p>
+ </div>
+ <div className="flex flex-col gap-1 text-xs text-gray-500">
+ {user?.name && user.email && <p>{user.email}</p>}
+ </div>
+ </div>
+ }
+ >
+ <div>
+ <Avatar user={user} className="h-4 w-4" />
+ </div>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index eb63907600..821272200e 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,7 +1,7 @@
import z from "@/lib/zod";
import { metaTagsSchema } from "@/lib/zod/schemas/metatags";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
-import { Link, Project, UTMTemplate, Webhook } from "@prisma/client";
+import { Link, Project, UtmTemplate, Webhook } from "@prisma/client";
import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";
import { trackCustomerResponseSchema } from "./zod/schemas/customers";
import { integrationSchema } from "./zod/schemas/integration";
@@ -60,7 +60,10 @@ export interface TagProps {
export type TagColorProps = (typeof tagColors)[number];
-export type UTMTemplateProps = UTMTemplate;
+export type UtmTemplateProps = UtmTemplate;
+export type UtmTemplateWithUserProps = UtmTemplateProps & {
+ user?: UserProps;
+};
export type PlanProps = (typeof plans)[number];
diff --git a/apps/web/lib/zod/schemas/utm-templates.ts b/apps/web/lib/zod/schemas/utm-templates.ts
index 3956fadfbb..60539ac47d 100644
--- a/apps/web/lib/zod/schemas/utm-templates.ts
+++ b/apps/web/lib/zod/schemas/utm-templates.ts
@@ -33,3 +33,5 @@ export const createUTMTemplateBodySchema = z.object({
.transform((v) => v ?? null)
.describe("The ref of the short link."),
});
+
+export const updateUTMTemplateBodySchema = createUTMTemplateBodySchema;
diff --git a/apps/web/ui/layout/sidebar/items.ts b/apps/web/ui/layout/sidebar/items.ts
index c3017aef68..9efcfe43bd 100644
--- a/apps/web/ui/layout/sidebar/items.ts
+++ b/apps/web/ui/layout/sidebar/items.ts
@@ -4,6 +4,7 @@ import {
CircleInfo,
ConnectedDots,
CubeSettings,
+ DiamondTurnRight,
Gear2,
Gift,
Globe,
@@ -115,6 +116,11 @@ export const ITEMS: Record<
},
]
: []),
+ {
+ name: "UTM Templates",
+ icon: DiamondTurnRight,
+ href: `/${slug}/settings/utm-templates`,
+ },
],
},
{
diff --git a/apps/web/ui/links/utm-builder.tsx b/apps/web/ui/links/utm-builder.tsx
new file mode 100644
index 0000000000..8f822c6753
--- /dev/null
+++ b/apps/web/ui/links/utm-builder.tsx
@@ -0,0 +1,144 @@
+"use client";
+
+import { Tooltip, useMediaQuery } from "@dub/ui";
+import {
+ Flag6,
+ Gift,
+ GlobePointer,
+ InputSearch,
+ Page2,
+ SatelliteDish,
+} from "@dub/ui/src/icons";
+import { cn } from "@dub/utils";
+import { useEffect, useId, useRef, useState } from "react";
+
+export const UTM_PARAMETERS = [
+ {
+ key: "utm_source",
+ icon: GlobePointer,
+ label: "Source",
+ placeholder: "google",
+ description: "Where the traffic is coming from",
+ },
+ {
+ key: "utm_medium",
+ icon: SatelliteDish,
+ label: "Medium",
+ placeholder: "cpc",
+ description: "How the traffic is coming",
+ },
+ {
+ key: "utm_campaign",
+ icon: Flag6,
+ label: "Campaign",
+ placeholder: "summer_sale",
+ description: "The name of the campaign",
+ },
+ {
+ key: "utm_term",
+ icon: InputSearch,
+ label: "Term",
+ placeholder: "running shoes",
+ description: "The term of the campaign",
+ },
+ {
+ key: "utm_content",
+ icon: Page2,
+ label: "Content",
+ placeholder: "logolink",
+ description: "The content of the campaign",
+ },
+ {
+ key: "ref",
+ icon: Gift,
+ label: "Referral",
+ placeholder: "yoursite.com",
+ description: "The referral of the campaign",
+ },
+] as const;
+
+export function UTMBuilder({
+ values,
+ onChange,
+ disabled,
+ autoFocus,
+}: {
+ values: Record<
+ (typeof UTM_PARAMETERS)[number]["key"],
+ string | null | undefined
+ >;
+ onChange: (
+ key: (typeof UTM_PARAMETERS)[number]["key"],
+ value: string,
+ ) => void;
+ disabled?: boolean;
+ autoFocus?: boolean;
+}) {
+ const { isMobile } = useMediaQuery();
+
+ const id = useId();
+ const [showParams, setShowParams] = useState(false);
+
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Hacky fix to focus the input automatically in modals where normally it doesn't work
+ useEffect(() => {
+ if (inputRef.current && !isMobile && autoFocus)
+ setTimeout(() => inputRef.current?.focus(), 10);
+ }, []);
+
+ return (
+ <div className="grid gap-y-3">
+ {UTM_PARAMETERS.map(
+ ({ key, icon: Icon, label, placeholder, description }, idx) => {
+ return (
+ <div key={key} className="group relative">
+ <div className="relative z-10 flex">
+ <Tooltip
+ content={
+ <div className="p-3 text-center text-xs">
+ <p className="text-gray-600">{description}</p>
+ <span className="font-mono text-gray-400">{key}</span>
+ </div>
+ }
+ sideOffset={4}
+ disableHoverableContent
+ >
+ <div
+ className={cn(
+ "flex items-center gap-1.5 rounded-l-md border-y border-l border-gray-300 bg-gray-50 px-3 py-1.5 text-gray-700",
+ showParams ? "sm:min-w-36" : "sm:min-w-28",
+ )}
+ onClick={() => setShowParams((s) => !s)}
+ >
+ <Icon className="size-4 shrink-0" />
+ <label
+ htmlFor={`${id}-${key}`}
+ className="select-none text-sm"
+ >
+ {showParams ? (
+ <span className="font-mono text-xs">{key}</span>
+ ) : (
+ label
+ )}
+ </label>
+ </div>
+ </Tooltip>
+ <input
+ type="text"
+ id={`${id}-${key}`}
+ ref={idx === 0 ? inputRef : undefined}
+ placeholder={placeholder}
+ disabled={disabled}
+ className="h-full min-w-0 grow rounded-r-md border border-gray-300 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500 disabled:cursor-not-allowed sm:text-sm"
+ value={values[key] || ""}
+ onChange={(e) => onChange(key, e.target.value)}
+ />
+ </div>
+ </div>
+ );
+ },
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/modals/add-edit-utm-template.modal.tsx b/apps/web/ui/modals/add-edit-utm-template.modal.tsx
new file mode 100644
index 0000000000..8660b3fc45
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-utm-template.modal.tsx
@@ -0,0 +1,212 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { UtmTemplateProps } from "@/lib/types";
+import { Button, Modal, useMediaQuery } from "@dub/ui";
+import posthog from "posthog-js";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { UTMBuilder } from "../links/utm-builder";
+
+function AddEditUtmTemplateModal({
+ showAddEditUtmTemplateModal,
+ setShowAddEditUtmTemplateModal,
+ props,
+}: {
+ showAddEditUtmTemplateModal: boolean;
+ setShowAddEditUtmTemplateModal: Dispatch<SetStateAction<boolean>>;
+ props?: UtmTemplateProps;
+}) {
+ const { id } = props || {};
+ const { id: workspaceId } = useWorkspace();
+ const { isMobile } = useMediaQuery();
+
+ const {
+ register,
+ handleSubmit,
+ setValue,
+ setError,
+ formState: { isSubmitting, isSubmitSuccessful, dirtyFields },
+ watch,
+ } = useForm<
+ Pick<
+ UtmTemplateProps,
+ | "name"
+ | "utm_campaign"
+ | "utm_content"
+ | "utm_medium"
+ | "utm_source"
+ | "utm_term"
+ | "ref"
+ >
+ >({
+ values: props,
+ });
+
+ const values = watch();
+
+ const endpoint = useMemo(
+ () =>
+ id
+ ? {
+ method: "PATCH",
+ url: `/api/utm-templates/${id}?workspaceId=${workspaceId}`,
+ successMessage: "Successfully updated template!",
+ }
+ : {
+ method: "POST",
+ url: `/api/utm-templates?workspaceId=${workspaceId}`,
+ successMessage: "Successfully added template!",
+ },
+ [id],
+ );
+
+ return (
+ <Modal
+ showModal={showAddEditUtmTemplateModal}
+ setShowModal={setShowAddEditUtmTemplateModal}
+ >
+ <form
+ onSubmit={handleSubmit(async (data) => {
+ try {
+ const res = await fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!res.ok) {
+ const { error } = await res.json();
+ toast.error(error.message);
+ setError("root", { message: error.message });
+ return;
+ }
+
+ posthog.capture(
+ props ? "utm-template_edited" : "utm-template_created",
+ {
+ utmTemplateId: id,
+ utmTemplateName: data.name,
+ },
+ );
+ await mutate(`/api/utm-templates?workspaceId=${workspaceId}`);
+ toast.success(endpoint.successMessage);
+ setShowAddEditUtmTemplateModal(false);
+ } catch (e) {
+ toast.error("Failed to save template");
+ setError("root", { message: "Failed to save template" });
+ }
+ })}
+ className="px-5 py-4"
+ >
+ <div className="flex items-center gap-2">
+ <h3 className="text-lg font-medium">
+ {props ? "Edit UTM Template" : "Add UTM Template"}
+ </h3>
+ </div>
+ <div className="mt-6">
+ <label htmlFor="name">
+ <span className="block text-sm font-medium text-gray-700">
+ Template Name
+ </span>
+ <div className="mt-2 flex rounded-md shadow-sm">
+ <input
+ type="text"
+ autoFocus={!isMobile}
+ autoComplete="off"
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="New Template"
+ {...register("name", { required: true })}
+ />
+ </div>
+ </label>
+ </div>
+
+ <div className="mt-6">
+ <span className="mb-2 block text-sm font-medium text-gray-700">
+ Parameters
+ </span>
+ <UTMBuilder
+ values={values}
+ onChange={(key, value) => {
+ setValue(key, value, { shouldDirty: true });
+ }}
+ />
+ </div>
+
+ <div className="mt-6 flex justify-end">
+ <Button
+ // Check all dirty fields because `isDirty` doesn't seem to register for `ref`
+ disabled={!Object.entries(dirtyFields).some(([_, dirty]) => dirty)}
+ loading={isSubmitting || isSubmitSuccessful}
+ text={props ? "Save changes" : "Create Template"}
+ className="h-9 w-fit"
+ />
+ </div>
+ </form>
+ </Modal>
+ );
+}
+
+function AddUtmTemplateButton({
+ setShowAddEditUtmTemplateModal,
+}: {
+ setShowAddEditUtmTemplateModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ return (
+ <div>
+ <Button
+ variant="primary"
+ text="Add Template"
+ className="h-9 rounded-lg"
+ onClick={() => setShowAddEditUtmTemplateModal(true)}
+ />
+ </div>
+ );
+}
+
+export function useAddEditUtmTemplateModal({
+ props,
+}: { props?: UtmTemplateProps } = {}) {
+ const [showAddEditUtmTemplateModal, setShowAddEditUtmTemplateModal] =
+ useState(false);
+
+ const AddEditUtmTemplateModalCallback = useCallback(() => {
+ return (
+ <AddEditUtmTemplateModal
+ showAddEditUtmTemplateModal={showAddEditUtmTemplateModal}
+ setShowAddEditUtmTemplateModal={setShowAddEditUtmTemplateModal}
+ props={props}
+ />
+ );
+ }, [showAddEditUtmTemplateModal, setShowAddEditUtmTemplateModal]);
+
+ const AddUtmTemplateButtonCallback = useCallback(() => {
+ return (
+ <AddUtmTemplateButton
+ setShowAddEditUtmTemplateModal={setShowAddEditUtmTemplateModal}
+ />
+ );
+ }, [setShowAddEditUtmTemplateModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddEditUtmTemplateModal,
+ AddEditUtmTemplateModal: AddEditUtmTemplateModalCallback,
+ AddUtmTemplateButton: AddUtmTemplateButtonCallback,
+ }),
+ [
+ setShowAddEditUtmTemplateModal,
+ AddEditUtmTemplateModalCallback,
+ AddUtmTemplateButtonCallback,
+ ],
+ );
+}
diff --git a/apps/web/ui/modals/link-builder/constants.ts b/apps/web/ui/modals/link-builder/constants.ts
index 50537a502f..c7e8d2364f 100644
--- a/apps/web/ui/modals/link-builder/constants.ts
+++ b/apps/web/ui/modals/link-builder/constants.ts
@@ -2,14 +2,8 @@ import { LinkWithTagsProps } from "@/lib/types";
import {
CircleHalfDottedClock,
Crosshairs3,
- Flag6,
- Gift,
- GlobePointer,
Incognito,
InputPassword,
- InputSearch,
- Page2,
- SatelliteDish,
SquareChart,
WindowSearch,
} from "@dub/ui/src/icons";
@@ -105,48 +99,3 @@ export const MOBILE_MORE_ITEMS = [
type: "modal",
},
];
-
-export const UTM_PARAMETERS = [
- {
- key: "utm_source",
- icon: GlobePointer,
- label: "Source",
- placeholder: "google",
- description: "Where the traffic is coming from",
- },
- {
- key: "utm_medium",
- icon: SatelliteDish,
- label: "Medium",
- placeholder: "cpc",
- description: "How the traffic is coming",
- },
- {
- key: "utm_campaign",
- icon: Flag6,
- label: "Campaign",
- placeholder: "summer_sale",
- description: "The name of the campaign",
- },
- {
- key: "utm_term",
- icon: InputSearch,
- label: "Term",
- placeholder: "running shoes",
- description: "The term of the campaign",
- },
- {
- key: "utm_content",
- icon: Page2,
- label: "Content",
- placeholder: "logolink",
- description: "The content of the campaign",
- },
- {
- key: "ref",
- icon: Gift,
- label: "Referral",
- placeholder: "yoursite.com",
- description: "The referral of the campaign",
- },
-] as const;
diff --git a/apps/web/ui/modals/link-builder/targeting-modal.tsx b/apps/web/ui/modals/link-builder/targeting-modal.tsx
index a54318fc70..d8def93a33 100644
--- a/apps/web/ui/modals/link-builder/targeting-modal.tsx
+++ b/apps/web/ui/modals/link-builder/targeting-modal.tsx
@@ -1,3 +1,4 @@
+import { UTM_PARAMETERS } from "@/ui/links/utm-builder";
import { ProBadgeTooltip } from "@/ui/shared/pro-badge-tooltip";
import {
Button,
@@ -26,7 +27,6 @@ import {
} from "react";
import { useForm, useFormContext } from "react-hook-form";
import { LinkFormData } from ".";
-import { UTM_PARAMETERS } from "./constants";
function TargetingModal({
showTargetingModal,
diff --git a/apps/web/ui/modals/link-builder/utm-modal.tsx b/apps/web/ui/modals/link-builder/utm-modal.tsx
index 1ee9bd7d7f..b8d9d6dc9f 100644
--- a/apps/web/ui/modals/link-builder/utm-modal.tsx
+++ b/apps/web/ui/modals/link-builder/utm-modal.tsx
@@ -1,3 +1,4 @@
+import { UTM_PARAMETERS, UTMBuilder } from "@/ui/links/utm-builder";
import {
Button,
InfoTooltip,
@@ -5,7 +6,6 @@ import {
SimpleTooltipContent,
Tooltip,
useKeyboardShortcut,
- useMediaQuery,
} from "@dub/ui";
import { DiamondTurnRight } from "@dub/ui/src";
import {
@@ -18,15 +18,11 @@ import {
Dispatch,
SetStateAction,
useCallback,
- useEffect,
- useId,
useMemo,
- useRef,
useState,
} from "react";
import { FormProvider, useForm, useFormContext } from "react-hook-form";
import { LinkFormData } from ".";
-import { UTM_PARAMETERS } from "./constants";
import { UTMTemplatesButton } from "./utm-templates-button";
type UTMModalProps = {
@@ -47,9 +43,6 @@ function UTMModal(props: UTMModalProps) {
}
function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
- const { isMobile } = useMediaQuery();
- const id = useId();
-
const { getValues: getValuesParent, setValue: setValueParent } =
useFormContext<LinkFormData>();
@@ -85,20 +78,6 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
const url = watch("url");
const enabledParams = useMemo(() => getParamsFromURL(url), [url]);
- const inputRef = useRef<HTMLInputElement>(null);
-
- // Hacky fix to focus the input automatically, not sure why autoFocus doesn't work here
- useEffect(() => {
- if (inputRef.current && !isMobile) {
- setTimeout(() => {
- inputRef.current?.focus();
- }, 10);
- }
- }, []);
-
- // Whether to display actual URL parameters instead of labels
- const [showParams, setShowParams] = useState(false);
-
// Update targeting URL params if they previously matched the same params of the destination URL
const updateTargeting = useCallback(
(
@@ -217,69 +196,24 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
</div>
</div>
- <div className="grid gap-y-3 py-4">
- {UTM_PARAMETERS.map(
- ({ key, icon: Icon, label, placeholder, description }, idx) => {
- return (
- <div key={key} className="group relative">
- <div className="relative z-10 flex">
- <Tooltip
- content={
- <div className="p-3 text-center text-xs">
- <p className="text-gray-600">{description}</p>
- <span className="font-mono text-gray-400">{key}</span>
- </div>
- }
- sideOffset={4}
- disableHoverableContent
- >
- <div
- className={cn(
- "flex items-center gap-1.5 rounded-l-md border-y border-l border-gray-300 bg-gray-50 px-3 py-1.5 text-gray-700",
- showParams ? "sm:min-w-36" : "sm:min-w-28",
- )}
- onClick={() => setShowParams((s) => !s)}
- >
- <Icon className="size-4 shrink-0" />
- <label
- htmlFor={`${id}-${key}`}
- className="select-none text-sm"
- >
- {showParams ? (
- <span className="font-mono text-xs">{key}</span>
- ) : (
- label
- )}
- </label>
- </div>
- </Tooltip>
- <input
- type="text"
- id={`${id}-${key}`}
- ref={idx === 0 ? inputRef : undefined}
- placeholder={placeholder}
- disabled={!isValidUrl(url)}
- className="h-full min-w-0 grow rounded-r-md border border-gray-300 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500 disabled:cursor-not-allowed sm:text-sm"
- value={enabledParams[key] || ""}
- onChange={(e) => {
- if (key !== "ref")
- setValue(key, e.target.value, { shouldDirty: true });
-
- setValue(
- "url",
- constructURLFromUTMParams(url, {
- ...enabledParams,
- [key]: e.target.value,
- }),
- { shouldDirty: true },
- );
- }}
- />
- </div>
- </div>
+ <div className="py-4">
+ <UTMBuilder
+ values={enabledParams}
+ onChange={(key, value) => {
+ if (key !== "ref") setValue(key, value, { shouldDirty: true });
+
+ setValue(
+ "url",
+ constructURLFromUTMParams(url, {
+ ...enabledParams,
+ [key]: value,
+ }),
+ { shouldDirty: true },
);
- },
- )}
+ }}
+ disabled={!isValidUrl(url)}
+ autoFocus
+ />
</div>
{isValidUrl(url) && (
diff --git a/apps/web/ui/modals/link-builder/utm-templates-button.tsx b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
index 380b5fb5b7..a656f7169f 100644
--- a/apps/web/ui/modals/link-builder/utm-templates-button.tsx
+++ b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
@@ -1,7 +1,7 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
-import { UTMTemplateProps } from "@/lib/types";
+import { UtmTemplateProps } from "@/lib/types";
import { AnimatedSizeContainer, Button, Popover, Xmark } from "@dub/ui";
import {
Book2,
@@ -25,7 +25,7 @@ export function UTMTemplatesButton({
const { isMobile } = useMediaQuery();
const { id: workspaceId } = useWorkspace();
- let { data, isLoading } = useSWR<UTMTemplateProps[]>(
+ const { data, isLoading } = useSWR<UtmTemplateProps[]>(
workspaceId && `/api/utm-templates?workspaceId=${workspaceId}`,
fetcher,
{
@@ -200,7 +200,7 @@ function UTMTemplateList({
onLoad,
onDelete,
}: {
- data: UTMTemplateProps[];
+ data: UtmTemplateProps[];
onLoad: (params: Record<string, string>) => void;
onDelete: () => void;
}) {
@@ -262,7 +262,7 @@ function UTMTemplateOption({
onClick,
onDelete,
}: {
- template: UTMTemplateProps;
+ template: UtmTemplateProps;
onClick: () => void;
onDelete: () => Promise<void>;
}) {