The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add combobox for UTM templates
Tim Wilson97f67ac3af52
diff --git a/apps/web/ui/modals/link-builder/index.tsx b/apps/web/ui/modals/link-builder/index.tsxindex 6ec239787f..60135be315 100644--- a/apps/web/ui/modals/link-builder/index.tsx+++ b/apps/web/ui/modals/link-builder/index.tsx@@ -393,7 +393,6 @@ function LinkBuilderInner({<div className="-mb-1 h-6">{isValidUrl(url) && (<UTMTemplatesButton- variant="load-icon"onLoad={(params) => {setValue("url",diff --git a/apps/web/ui/modals/link-builder/utm-modal.tsx b/apps/web/ui/modals/link-builder/utm-modal.tsxindex b8d9d6dc9f..355b2ccad5 100644--- a/apps/web/ui/modals/link-builder/utm-modal.tsx+++ b/apps/web/ui/modals/link-builder/utm-modal.tsx@@ -23,7 +23,7 @@ import {} from "react";import { FormProvider, useForm, useFormContext } from "react-hook-form";import { LinkFormData } from ".";-import { UTMTemplatesButton } from "./utm-templates-button";+import { UTMTemplatesCombo } from "./utm-templates-combo";type UTMModalProps = {showUTMModal: boolean;@@ -228,19 +228,19 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {)}<div className="mt-6 flex items-center justify-between gap-2">- {isValidUrl(url) ? (- <FormProvider {...form}>- <UTMTemplatesButton- onLoad={(params) => {- setValue("url", constructURLFromUTMParams(url, params), {- shouldDirty: true,- });- }}- />- </FormProvider>- ) : (- <div />- )}+ <div>+ {isValidUrl(url) && (+ <FormProvider {...form}>+ <UTMTemplatesCombo+ onLoad={(params) => {+ setValue("url", constructURLFromUTMParams(url, params), {+ shouldDirty: true,+ });+ }}+ />+ </FormProvider>+ )}+ </div><div className="flex items-center gap-2"><Buttontype="button"diff --git a/apps/web/ui/modals/link-builder/utm-templates-button.tsx b/apps/web/ui/modals/link-builder/utm-templates-button.tsxindex d993127acc..32a908890e 100644--- a/apps/web/ui/modals/link-builder/utm-templates-button.tsx+++ b/apps/web/ui/modals/link-builder/utm-templates-button.tsx@@ -4,31 +4,19 @@ import useWorkspace from "@/lib/swr/use-workspace";import { UtmTemplateProps } from "@/lib/types";import {AnimatedSizeContainer,- Button,ButtonTooltip,Popover,- Xmark,-} from "@dub/ui";-import {- Book2,- DiamondTurnRight,- Download,- LoadingSpinner,- SquareLayoutGrid6,useMediaQuery,-} from "@dub/ui/src";-import { fetcher, getParamsFromURL } from "@dub/utils";-import { ChevronUp } from "lucide-react";-import { useEffect, useRef, useState } from "react";+} from "@dub/ui";+import { DiamondTurnRight, LoadingSpinner, Note } from "@dub/ui/src/icons";+import { fetcher } from "@dub/utils";+import { useState } from "react";import { useFormContext } from "react-hook-form";-import { toast } from "sonner";-import useSWR, { mutate } from "swr";+import useSWR from "swr";export function UTMTemplatesButton({- variant = "default",onLoad,}: {- variant?: "default" | "load-icon";onLoad: (params: Record<string, string>) => void;}) {const { isMobile } = useMediaQuery();@@ -43,18 +31,12 @@ export function UTMTemplatesButton({);const [openPopover, setOpenPopover] = useState(false);- const [state, setState] = useState<"default" | "load" | "save">(- variant === "load-icon" ? "load" : "default",- );- useEffect(() => {- if (!openPopover) setState(variant === "load-icon" ? "load" : "default");- }, [openPopover, variant]);- return variant === "default" || (data && data.length > 0) ? (+ return data && data.length > 0 ? (<PopoveropenPopover={openPopover}setOpenPopover={setOpenPopover}- side={variant === "default" ? "top" : "bottom"}+ side="bottom"align="start"onWheel={(e) => {// Allows scrolling to work when the popover's in a modal@@ -64,49 +46,15 @@ export function UTMTemplatesButton({<AnimatedSizeContainer width={!isMobile} height>{data ? (<div className="text-sm">- {state === "default" && (- <div className="grid p-1">- {data.length > 0 && (- <button- onClick={() => setState("load")}- className="flex w-full items-center gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200"- >- <Download className="size-4 text-gray-900" />- Load template- </button>- )}- <button- onClick={() => setState("save")}- className="flex w-full items-center gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200"- >- <Book2 className="size-4 text-gray-900" />- Save template- </button>- </div>- )}- {state === "save" && (- <div className="max-w-64 p-2">- <SaveUTMTemplateForm- onSuccess={() => setOpenPopover(false)}- />- </div>- )}- {state === "load" && (- <div className="max-w-64">- <UTMTemplateList- data={data}- onLoad={(params) => {- setOpenPopover(false);- onLoad(params);- }}- onDelete={- variant === "default"- ? () => setOpenPopover(false)- : undefined- }- />- </div>- )}+ <div className="max-w-64">+ <UTMTemplateList+ data={data}+ onLoad={(params) => {+ setOpenPopover(false);+ onLoad(params);+ }}+ />+ </div></div>) : isLoading ? (<div className="flex w-full items-center justify-center py-4 md:w-32">@@ -120,145 +68,30 @@ export function UTMTemplatesButton({</AnimatedSizeContainer>}>- {variant === "default" ? (- <Button- type="button"- variant="secondary"- className="h-10 w-fit px-3"- textWrapperClassName="flex items-center justify-start"- text={- <>- Templates- <ChevronUp- className={`ml-1 size-4 shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180`}- />- </>- }- />- ) : (- <div>- <ButtonTooltip- tabIndex={-1}- tooltipProps={{- content: "Load a UTM template",- }}- className="animate-fade-in size-6"- >- <DiamondTurnRight className="size-4" />- </ButtonTooltip>- </div>- )}+ <div>+ <ButtonTooltip+ tabIndex={-1}+ tooltipProps={{+ content: "Load a UTM template",+ }}+ className="animate-fade-in size-6"+ >+ <DiamondTurnRight className="size-4" />+ </ButtonTooltip>+ </div></Popover>) : null;}-function SaveUTMTemplateForm({ onSuccess }: { onSuccess: () => void }) {- const { isMobile } = useMediaQuery();- const { id: workspaceId } = useWorkspace();-- const { getValues } = useFormContext();-- const [name, setName] = useState("");- const [saving, setSaving] = useState(false);-- // Manual name input autofocus to prevent scroll (which screws up the AnimatedSizeContainer)- const inputRef = useRef<HTMLInputElement>(null);- useEffect(() => {- if (!isMobile && inputRef.current)- inputRef.current.focus({ preventScroll: true });- }, [isMobile]);-- return (- <form- onSubmit={async (e) => {- e.preventDefault();- e.stopPropagation();- setSaving(true);- try {- const res = await fetch(- `/api/utm-templates?workspaceId=${workspaceId}`,- {- method: "POST",- body: JSON.stringify({- name,- ...getParamsFromURL(getValues("url")),- }),- },- );- if (!res.ok) {- const { error } = await res.json();- toast.error(error.message);- return;- }-- mutate(`/api/utm-templates?workspaceId=${workspaceId}`);- toast.success("Template saved successfully");- onSuccess();- } catch (e) {- console.error(e);- toast.error("Failed to save UTM template");- } finally {- setSaving(false);- }- }}- >- <div className="flex items-center gap-2">- <input- ref={inputRef}- type="text"- className="h-9 min-w-0 grow rounded-md border border-gray-300 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500 sm:text-sm"- placeholder="Template name"- value={name}- onChange={(e) => setName(e.target.value)}- />- <Button- type="submit"- variant="primary"- text="Save"- className="h-9 w-fit"- onClick={() => {}}- disabled={!name}- loading={saving}- />- </div>- <p className="mt-2 text-xs text-gray-500">- Your saved template will be available to all users in this workspace.- </p>- </form>- );-}-function UTMTemplateList({data,onLoad,- onDelete,}: {data: UtmTemplateProps[];onLoad: (params: Record<string, string>) => void;- onDelete?: () => void;}) {- const { id: workspaceId } = useWorkspace();const { setValue } = useFormContext();- const handleDelete = async (id: string) => {- try {- const res = await fetch(- `/api/utm-templates/${id}?workspaceId=${workspaceId}`,- {- method: "DELETE",- },- );- if (!res.ok) throw new Error("UTM template delete failed");-- mutate(`/api/utm-templates?workspaceId=${workspaceId}`);- toast.success("Template deleted successfully");- onDelete?.();- } catch (e) {- console.error(e);- toast.error("Failed to delete template");- }- };-return data.length ? (<div className="scrollbar-hide grid max-h-64 overflow-y-auto p-1 md:min-w-48"><span className="block pb-2 pl-2.5 pt-2 text-xs font-medium text-gray-500">@@ -279,9 +112,6 @@ function UTMTemplateList({onLoad(Object.fromEntries(paramEntries));}}- onDelete={- onDelete ? async () => await handleDelete(template.id) : undefined- }/>))}</div>@@ -295,11 +125,9 @@ function UTMTemplateList({function UTMTemplateOption({template,onClick,- onDelete,}: {template: UtmTemplateProps;onClick: () => void;- onDelete?: () => Promise<void>;}) {const [deleting, setDeleting] = useState(false);@@ -309,38 +137,11 @@ function UTMTemplateOption({onClick={onClick}className="flex w-full items-center justify-between gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200 group-hover:bg-gray-100">- <span className="flex items-center gap-1.5">- <SquareLayoutGrid6 className="text-gray-500" />+ <span className="flex items-center gap-2">+ <Note className="size-4 text-gray-500" />{template.name}</span>- <div>- {onDelete !== undefined && <div className="size-[1.375rem]" />}- </div></button>- {onDelete !== undefined && (- <button- type="button"- onClick={async (e) => {- e.stopPropagation();- if (- !window.confirm("Are you sure you want to delete this template?")- )- return;-- setDeleting(true);- await onDelete();- setDeleting(false);- }}- className="absolute right-1.5 top-2 rounded-md p-1 text-gray-400 outline-none transition-colors hover:text-gray-500 focus-visible:ring-2 focus-visible:ring-gray-500"- title="Delete template"- >- {deleting ? (- <LoadingSpinner className="size-3.5" />- ) : (- <Xmark className="size-3.5" />- )}- </button>- )}</div>);}diff --git a/apps/web/ui/modals/link-builder/utm-templates-combo.tsx b/apps/web/ui/modals/link-builder/utm-templates-combo.tsxnew file mode 100644index 0000000000..09fcf7a4bc--- /dev/null+++ b/apps/web/ui/modals/link-builder/utm-templates-combo.tsx@@ -0,0 +1,88 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import { UtmTemplateProps } from "@/lib/types";+import { Combobox } from "@dub/ui";+import { Note } from "@dub/ui/src/icons";+import { fetcher, getParamsFromURL } from "@dub/utils";+import { useFormContext } from "react-hook-form";+import { toast } from "sonner";+import useSWR, { mutate } from "swr";++export function UTMTemplatesCombo({+ onLoad,+}: {+ onLoad: (params: Record<string, string>) => void;+}) {+ const { id: workspaceId } = useWorkspace();++ const { setValue, getValues } = useFormContext();++ const { data } = useSWR<UtmTemplateProps[]>(+ workspaceId && `/api/utm-templates?workspaceId=${workspaceId}`,+ fetcher,+ {+ dedupingInterval: 60000,+ },+ );++ return data && data.length > 0 ? (+ <Combobox+ selected={null}+ setSelected={(option) => {+ if (!option) return;+ const template = data.find((template) => template.id === option.value);+ if (!template) return;++ const paramEntries = Object.entries(template)+ .filter(([key]) => key === "ref" || key.startsWith("utm_"))+ .map(([key, value]) => [key, (value || "").toString()]);++ paramEntries.forEach(([key, value]) =>+ setValue(key, value, { shouldDirty: true }),+ );++ onLoad(Object.fromEntries(paramEntries));+ }}+ options={data.map((template) => ({+ label: template.name,+ value: template.id,+ }))}+ placeholder="Templates"+ searchPlaceholder="Load or save a template..."+ icon={Note}+ createLabel={(search) => `Save new template: "${search}"`}+ onCreate={async (search) => {+ try {+ const res = await fetch(+ `/api/utm-templates?workspaceId=${workspaceId}`,+ {+ method: "POST",+ body: JSON.stringify({+ name: search,+ ...getParamsFromURL(getValues("url")),+ }),+ },+ );+ if (!res.ok) {+ const { error } = await res.json();+ toast.error(error.message);+ return false;+ }++ mutate(`/api/utm-templates?workspaceId=${workspaceId}`);+ toast.success("Template saved successfully");+ return true;+ } catch (e) {+ console.error(e);+ toast.error("Failed to save UTM template");+ }++ return false;+ }}+ buttonProps={{ className: "w-fit px-2" }}+ optionClassName="sm:min-w-[200px] sm:max-w-[350px] animate-fade-in"+ caret+ />+ ) : null;+}diff --git a/packages/ui/src/combobox/index.tsx b/packages/ui/src/combobox/index.tsxindex dac4ab2a92..af7694aa71 100644--- a/packages/ui/src/combobox/index.tsx+++ b/packages/ui/src/combobox/index.tsx@@ -39,8 +39,8 @@ export type ComboboxProps<? ComboboxOption<TMeta>[]: ComboboxOption<TMeta> | null;setSelected: TMultiple extends true- ? (tags: ComboboxOption<TMeta>[]) => void- : (tag: ComboboxOption<TMeta> | null) => void;+ ? (options: ComboboxOption<TMeta>[]) => void+ : (option: ComboboxOption<TMeta> | null) => void;options?: ComboboxOption<TMeta>[];icon?: Icon | ReactNode;placeholder?: ReactNode;@@ -307,7 +307,7 @@ export function Combobox({isReactNode(Icon) ? (Icon) : (- <Icon className="size-4" />+ <Icon className="size-4 shrink-0" />)) : undefined}diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.tsindex 9f3fb7ba2b..783f279d76 100644--- a/packages/ui/src/icons/nucleo/index.ts+++ b/packages/ui/src/icons/nucleo/index.ts@@ -70,6 +70,7 @@ export * from "./magnifier";export * from "./map-position";export * from "./menu3";export * from "./mobile-phone";+export * from "./note";export * from "./office-building";export * from "./page2";export * from "./paintbrush";diff --git a/packages/ui/src/icons/nucleo/note.tsx b/packages/ui/src/icons/nucleo/note.tsxnew file mode 100644index 0000000000..88c506b86f--- /dev/null+++ b/packages/ui/src/icons/nucleo/note.tsx@@ -0,0 +1,62 @@+import { SVGProps } from "react";++export function Note(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ height="18"+ width="18"+ viewBox="0 0 18 18"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <g fill="currentColor">+ <rect+ height="12.5"+ width="14.5"+ fill="none"+ rx="2"+ ry="2"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x="1.75"+ y="2.75"+ />+ <line+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x1="5"+ x2="13"+ y1="6.25"+ y2="6.25"+ />+ <line+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x1="5"+ x2="9.25"+ y1="11.75"+ y2="11.75"+ />+ <line+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ x1="5"+ x2="13"+ y1="9"+ y2="9"+ />+ </g>+ </svg>+ );+}