The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Scope link.clicked webhooks with shared trigger selector and nextWebhook PATCH
Kiran Kd4892a25a4f6
diff --git a/apps/web/app/api/integrations/uninstall/route.ts b/apps/web/app/api/integrations/uninstall/route.tsindex 4333901b8b..a46ddb7f9b 100644--- a/apps/web/app/api/integrations/uninstall/route.ts+++ b/apps/web/app/api/integrations/uninstall/route.ts@@ -3,7 +3,7 @@ import { withWorkspace } from "@/lib/auth";import { slackOAuthProvider } from "@/lib/integrations/slack/oauth";import { prisma } from "@/lib/prisma";import { webhookCache } from "@/lib/webhook/cache";-import { isLinkLevelWebhook } from "@/lib/webhook/utils";+import { hasLinkClickTrigger } from "@/lib/webhook/utils";import { SLACK_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -58,7 +58,7 @@ export const DELETE = withWorkspace(: []),...webhooks.map((webhook) =>- isLinkLevelWebhook(webhook) ? webhookCache.delete(webhook.id) : null,+ hasLinkClickTrigger(webhook) ? webhookCache.delete(webhook.id) : null,),]),);diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.tsindex 71fc65ba9b..c95118ed03 100644--- a/apps/web/app/api/webhooks/[webhookId]/route.ts+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts@@ -2,7 +2,8 @@ import { DubApiError } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";-import { LINK_CLICK_WEBHOOK_TRIGGER } from "@/lib/webhook/constants";+import { NewWebhook } from "@/lib/types";+import { WebhookTrigger } from "@/lib/webhook/constants";import { syncWorkspaceWebhookStatus } from "@/lib/webhook/update-webhook";import { validateWebhook } from "@/lib/webhook/validate-webhook";import { updateWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";@@ -66,16 +67,19 @@ export const PATCH = withWorkspace(});}+ const nextWebhook: Partial<NewWebhook> = {+ ...existingWebhook,+ ...input,+ triggers: (triggers ?? existingWebhook.triggers) as WebhookTrigger[],+ };+await validateWebhook({- input,+ input: nextWebhook,workspace,webhook: existingWebhook,user: session.user,});- const hasLinkClicked =- triggers?.includes(LINK_CLICK_WEBHOOK_TRIGGER) ?? false;- const newScope = hasLinkClicked ? scope ?? null : null;const existingLinkIds = existingWebhook.links.map((link) => link.linkId);const existingFolderIds = existingWebhook.folders.map((folder) => folder.folderId,@@ -83,17 +87,17 @@ export const PATCH = withWorkspace(const scopeChanged =(triggers !== undefined || scope !== undefined) &&- newScope !== existingWebhook.scope;+ nextWebhook.scope !== existingWebhook.scope;const shouldSyncLinks =- (newScope !== "links" && existingLinkIds.length > 0) ||- (newScope === "links" &&+ (nextWebhook.scope !== "links" && existingLinkIds.length > 0) ||+ (nextWebhook.scope === "links" &&linkIds !== undefined &&!arrayEqual(existingLinkIds, linkIds ?? []));const shouldSyncFolders =- (newScope !== "folders" && existingFolderIds.length > 0) ||- (newScope === "folders" &&+ (nextWebhook.scope !== "folders" && existingFolderIds.length > 0) ||+ (nextWebhook.scope === "folders" &&folderIds !== undefined &&!arrayEqual(existingFolderIds, folderIds ?? []));@@ -106,7 +110,7 @@ export const PATCH = withWorkspace(...(name !== undefined && { name }),...(url !== undefined && { url }),...(triggers !== undefined && { triggers }),- ...(scopeChanged && { scope: newScope }),+ ...(scopeChanged && { scope: nextWebhook.scope }),},});@@ -117,7 +121,7 @@ export const PATCH = withWorkspace(},});- if (newScope === "links" && linkIds?.length) {+ if (nextWebhook.scope === "links" && linkIds?.length) {await tx.linkWebhook.createMany({data: linkIds.map((linkId) => ({linkId,@@ -134,7 +138,7 @@ export const PATCH = withWorkspace(},});- if (newScope === "folders" && folderIds?.length) {+ if (nextWebhook.scope === "folders" && folderIds?.length) {await tx.folderWebhook.createMany({data: folderIds.map((folderId) => ({folderId,diff --git a/apps/web/lib/integrations/common/ui/configure-webhook.tsx b/apps/web/lib/integrations/common/ui/configure-webhook.tsxindex 612bd833f6..16b42ec1b1 100644--- a/apps/web/lib/integrations/common/ui/configure-webhook.tsx+++ b/apps/web/lib/integrations/common/ui/configure-webhook.tsx@@ -2,19 +2,22 @@import { clientAccessCheck } from "@/lib/client-access-check";import useWorkspace from "@/lib/swr/use-workspace";-import { WebhookProps, WebhookTrigger } from "@/lib/types";+import { WebhookProps } from "@/lib/types";import {- LINK_LEVEL_WEBHOOK_TRIGGERS,+ LINK_CLICK_WEBHOOK_TRIGGER,PROGRAM_LEVEL_WEBHOOK_TRIGGERS,- WEBHOOK_TRIGGER_DESCRIPTIONS,+ WebhookTrigger,WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,} from "@/lib/webhook/constants";import { Link } from "@/ui/shared/icons";-import { LinksSelector } from "@/ui/webhooks/link-selector";-import { Button, Checkbox } from "@dub/ui";+import {+ isWebhookTriggerSelectionInvalid,+ WebhookTriggerSelector,+ WebhookTriggerSelectorValue,+} from "@/ui/webhooks/webhook-trigger-selector";+import { Button } from "@dub/ui";import { fetcher } from "@dub/utils";-import { cn } from "@dub/utils/src/functions";-import { FormEvent, useEffect, useState } from "react";+import { FormEvent, useEffect, useMemo, useState } from "react";import { toast } from "sonner";import useSWR, { mutate } from "swr";@@ -33,50 +36,37 @@ export function ConfigureWebhook({fetcher,);- const [data, setData] = useState<Pick<WebhookProps, "triggers">>({- triggers: [],- });- const [linkIds, setLinkIds] = useState<string[]>([]);- const [linkIdsInitialized, setLinkIdsInitialized] = useState(false);+ const [triggerSelection, setTriggerSelection] =+ useState<WebhookTriggerSelectorValue>({+ triggers: [],+ scope: "all",+ linkIds: [],+ folderIds: [],+ });useEffect(() => {if (webhook) {- setData({+ setTriggerSelection((prev) => ({+ ...prev,triggers: webhook.triggers,- });+ scope: webhook.scope ?? "all",+ }));}}, [webhook]);- const { triggers } = data;-- const hasLinkLevelWebhook = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>- triggers.includes(trigger),- );-- const { data: fetchedLinkIds, isLoading: isLoadingLinks } = useSWR<string[]>(- hasLinkLevelWebhook &&- `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`,- fetcher,- );-- useEffect(() => {- if (fetchedLinkIds && !linkIdsInitialized) {- setLinkIds(fetchedLinkIds);- setLinkIdsInitialized(true);- }- }, [fetchedLinkIds, linkIdsInitialized]);-const { error: permissionsError } = clientAccessCheck({action: "webhooks.write",role,});- // Save the form dataconst onSubmit = async (e: FormEvent) => {e.preventDefault();setSaving(true);+ const { triggers, scope, linkIds, folderIds } = triggerSelection;+ const hasLinkClicked = triggers.includes(LINK_CLICK_WEBHOOK_TRIGGER);+const response = await fetch(`/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,{@@ -84,7 +74,14 @@ export function ConfigureWebhook({headers: {"Content-Type": "application/json",},- body: JSON.stringify({ ...data, linkIds }),+ body: JSON.stringify({+ triggers,+ ...(hasLinkClicked && {+ scope,+ ...(scope === "links" && { linkIds }),+ ...(scope === "folders" && { folderIds }),+ }),+ }),},);@@ -98,20 +95,34 @@ export function ConfigureWebhook({}mutate(`/api/webhooks/${webhookId}?workspaceId=${workspaceId}`, result);- mutate(- `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`,- linkIds,- );+ await Promise.all([+ mutate(+ `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`,+ result.scope === "links" ? linkIds : [],+ { revalidate: true },+ ),+ mutate(+ `/api/webhooks/${webhookId}/folders?workspaceId=${workspaceId}`,+ result.scope === "folders" ? folderIds : [],+ { revalidate: true },+ ),+ ]);toast.success("Webhook preferences saved!");};const canManageWebhook =!permissionsError || plan === "free" || plan === "pro";- const availableWebhookTriggers = [- ...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,- ...(defaultProgramId ? PROGRAM_LEVEL_WEBHOOK_TRIGGERS : []),- ];+ const availableTriggers = useMemo(+ () =>+ [+ ...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,+ ...(defaultProgramId ? PROGRAM_LEVEL_WEBHOOK_TRIGGERS : []),+ ].filter((trigger) => supportedEvents.includes(trigger)),+ [defaultProgramId, supportedEvents],+ );++ const selectionInvalid = isWebhookTriggerSelectionInvalid(triggerSelection);return (<form onSubmit={onSubmit}>@@ -122,114 +133,14 @@ export function ConfigureWebhook({</div><div className="p-4">- <div>- <label htmlFor="triggers" className="flex flex-col gap-1">- <h2 className="text-sm font-medium text-neutral-900">- Workspace level events- </h2>- <span className="text-xs text-neutral-500">- These events are triggered at the workspace level.- </span>- </label>- <div className="mt-3 flex flex-col gap-2">- {availableWebhookTriggers- .filter(- (trigger) =>- canManageWebhook && supportedEvents.includes(trigger),- )- .map((trigger) => (- <div key={trigger} className="group flex gap-2">- <Checkbox- value={trigger}- id={trigger}- checked={triggers.includes(trigger)}- disabled={- !canManageWebhook || !supportedEvents.includes(trigger)- }- onCheckedChange={(checked) => {- setData({- ...data,- triggers: checked- ? [...triggers, trigger]- : triggers.filter((t) => t !== trigger),- });- }}- title={- !supportedEvents.includes(trigger)- ? "Not supported"- : undefined- }- />- <label- htmlFor={trigger}- className={cn(- "select-none text-sm text-neutral-600",- supportedEvents.includes(trigger)- ? "group-hover:text-neutral-800"- : "opacity-50",- )}- >- {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}- </label>- </div>- ))}- </div>- </div>-- <div className="mt-6">- <label htmlFor="triggers" className="flex flex-col gap-1">- <h2 className="text-sm font-medium text-neutral-900">- Link level events{" "}- <span className="rounded bg-yellow-100 px-1 py-0.5 text-xs font-medium text-yellow-800">- High traffic- </span>- </h2>- <span className="text-xs text-neutral-500">- These events are triggered at the link level.- </span>- </label>- <div className="mt-3 flex flex-col gap-2">- {LINK_LEVEL_WEBHOOK_TRIGGERS.map((trigger) => (- <div key={trigger} className="group flex gap-2">- <Checkbox- value={trigger}- id={trigger}- checked={triggers.includes(trigger)}- disabled={!canManageWebhook}- onCheckedChange={(checked) => {- setData({- ...data,- triggers: checked- ? [...triggers, trigger]- : triggers.filter((t) => t !== trigger),- });- }}- />- <label- htmlFor={trigger}- className="flex select-none items-center gap-2 text-sm text-neutral-600 group-hover:text-neutral-800"- >- {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}- </label>- </div>- ))}- </div>-- {hasLinkLevelWebhook && linkIds.length < 1000 ? (- <div className="mt-4">- <h2 className="text-sm font-medium text-neutral-900">- Choose links we should send events for- </h2>- <div className="mt-3">- <LinksSelector- selectedLinkIds={linkIds}- setSelectedLinkIds={setLinkIds}- disabled={!canManageWebhook}- />- </div>- </div>- ) : null}- </div>+ <WebhookTriggerSelector+ value={triggerSelection}+ onChange={setTriggerSelection}+ availableTriggers={availableTriggers}+ disabled={!canManageWebhook}+ webhookId={webhookId}+ savedScope={webhook?.scope}+ /></div><div className="flex items-center justify-end rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-4 py-3">@@ -241,12 +152,7 @@ export function ConfigureWebhook({{...(permissionsError && {disabledTooltip: permissionsError,})}- disabled={- !canManageWebhook ||- isLoading ||- isLoadingLinks ||- !linkIdsInitialized- }+ disabled={!canManageWebhook || isLoading || selectionInvalid}className="h-8"/></div>diff --git a/apps/web/lib/webhook/cache.ts b/apps/web/lib/webhook/cache.tsindex c2eee72c10..ececec4731 100644--- a/apps/web/lib/webhook/cache.ts+++ b/apps/web/lib/webhook/cache.ts@@ -1,6 +1,6 @@import { redis } from "@/lib/upstash";import { WebhookCacheProps } from "../types";-import { isLinkLevelWebhook } from "./utils";+import { hasLinkClickTrigger } from "./utils";const WEBHOOK_CACHE_KEY_PREFIX = "webhook";@@ -21,7 +21,7 @@ class WebhookCache {async set(webhook: WebhookCacheProps) {// We only cache the link level webhooks for now- if (!isLinkLevelWebhook(webhook)) {+ if (!hasLinkClickTrigger(webhook)) {return;}diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.tsindex c1f55f846c..8320373106 100644--- a/apps/web/lib/webhook/constants.ts+++ b/apps/web/lib/webhook/constants.ts@@ -14,6 +14,7 @@ export const WORKSPACE_LEVEL_WEBHOOK_TRIGGERS = ["link.deleted","lead.created","sale.created",+ "link.clicked",] as const;export const PROGRAM_LEVEL_WEBHOOK_TRIGGERS = [@@ -27,14 +28,6 @@ export const PROGRAM_LEVEL_WEBHOOK_TRIGGERS = [export const LINK_CLICK_WEBHOOK_TRIGGER = "link.clicked" as const;-export const LINK_LEVEL_WEBHOOK_TRIGGERS = ["link.clicked"] as const;--export const WEBHOOK_SCOPE_DESCRIPTIONS: Record<WebhookScope, string> = {- all: "All links",- folders: "Specific folders",- links: "Specific links",-} as const;-export const WEBHOOK_SCOPE_OPTIONS = [{value: "all",@@ -61,7 +54,6 @@ export const WEBHOOK_SCOPE_OPTIONS = [export const WEBHOOK_TRIGGERS = [...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,...PROGRAM_LEVEL_WEBHOOK_TRIGGERS,- ...LINK_LEVEL_WEBHOOK_TRIGGERS,] as const;export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];diff --git a/apps/web/lib/webhook/utils.ts b/apps/web/lib/webhook/utils.tsindex 0b89cfb090..55fe7684da 100644--- a/apps/web/lib/webhook/utils.ts+++ b/apps/web/lib/webhook/utils.ts@@ -1,5 +1,5 @@import { Webhook, WebhookReceiver } from "@prisma/client";-import { LINK_LEVEL_WEBHOOK_TRIGGERS } from "./constants";+import { LINK_CLICK_WEBHOOK_TRIGGER, WebhookTrigger } from "./constants";const webhookReceivers: Record<string, WebhookReceiver> = {"zapier.com": "zapier",@@ -9,17 +9,14 @@ const webhookReceivers: Record<string, WebhookReceiver> = {"api.segment.io": "segment",};-export const isLinkLevelWebhook = (webhook: Pick<Webhook, "triggers">) => {+export const hasLinkClickTrigger = (webhook: Pick<Webhook, "triggers">) => {if (!webhook.triggers) {return false;}- const triggers =- webhook.triggers as (typeof LINK_LEVEL_WEBHOOK_TRIGGERS)[number][];+ const triggers = webhook.triggers as WebhookTrigger[];- return triggers.some((trigger) =>- LINK_LEVEL_WEBHOOK_TRIGGERS.includes(trigger),- );+ return triggers.includes(LINK_CLICK_WEBHOOK_TRIGGER);};export const identifyWebhookReceiver = (url: string): WebhookReceiver => {diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsxindex 6bf8167f74..6110f8b13f 100644--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx@@ -6,30 +6,20 @@ import useWorkspace from "@/lib/swr/use-workspace";import { NewWebhook, WebhookProps } from "@/lib/types";import {LINK_CLICK_WEBHOOK_TRIGGER,- LINK_LEVEL_WEBHOOK_TRIGGERS,PROGRAM_LEVEL_WEBHOOK_TRIGGERS,- WEBHOOK_SCOPE_OPTIONS,- WEBHOOK_TRIGGER_DESCRIPTIONS,WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,} from "@/lib/webhook/constants";-import {- Button,- Checkbox,- CircleCheckFill,- CopyButton,- InfoTooltip,- RadioGroup,- RadioGroupItem,-} from "@dub/ui";-import { cn, fetcher } from "@dub/utils";-import { WebhookScope } from "@prisma/client";+import { Button, CopyButton, InfoTooltip } from "@dub/ui";+import { cn } from "@dub/utils";import { useRouter } from "next/navigation";-import { useEffect, useMemo } from "react";-import { FormProvider, useForm, useFormContext } from "react-hook-form";+import { useMemo } from "react";+import { FormProvider, useForm } from "react-hook-form";import { toast } from "sonner";-import useSWR, { mutate } from "swr";-import { FoldersSelector } from "./folder-selector";-import { LinksSelector } from "./link-selector";+import { mutate } from "swr";+import {+ isWebhookTriggerSelectionInvalid,+ WebhookTriggerSelector,+} from "./webhook-trigger-selector";export default function AddEditWebhookForm({webhook,@@ -60,6 +50,7 @@ export default function AddEditWebhookForm({handleSubmit,watch,setValue,+ reset,formState: { isSubmitting },} = methods;@@ -126,23 +117,38 @@ export default function AddEditWebhookForm({router.push(`/${workspaceSlug}/settings/webhooks/${result.id}/edit`);} else {mutate(`/api/webhooks/${result.id}?workspaceId=${workspaceId}`, result);- mutate(- `/api/webhooks/${result.id}/links?workspaceId=${workspaceId}`,- data.scope === "links" ? data.linkIds : [],- );- mutate(- `/api/webhooks/${result.id}/folders?workspaceId=${workspaceId}`,- data.scope === "folders" ? data.folderIds : [],- );+ await Promise.all([+ mutate(+ `/api/webhooks/${result.id}/links?workspaceId=${workspaceId}`,+ result.scope === "links" ? data.linkIds ?? [] : [],+ { revalidate: true },+ ),+ mutate(+ `/api/webhooks/${result.id}/folders?workspaceId=${workspaceId}`,+ result.scope === "folders" ? data.folderIds ?? [] : [],+ { revalidate: true },+ ),+ ]);++ reset({+ name: result.name,+ url: result.url,+ triggers: result.triggers,+ scope: result.scope ?? "all",+ linkIds: result.scope === "links" ? data.linkIds ?? [] : [],+ folderIds: result.scope === "folders" ? data.folderIds ?? [] : [],+ });}toast.success(endpoint.successMessage);};- const scopeInvalid =- hasLinkClicked &&- ((scope === "links" && linkIds?.length === 0) ||- (scope === "folders" && folderIds?.length === 0));+ const scopeInvalid = isWebhookTriggerSelectionInvalid({+ triggers,+ scope: scope ?? "all",+ linkIds: linkIds ?? [],+ folderIds: folderIds ?? [],+ });const buttonDisabled =!name || !url || !triggers.length || isSubmitting || scopeInvalid;@@ -167,25 +173,10 @@ export default function AddEditWebhookForm({EXTERNAL_PAYOUTS_PROGRAM_IDS.includes(defaultProgramId),): []),- ...LINK_LEVEL_WEBHOOK_TRIGGERS,],[defaultProgramId],);- const toggleTrigger = (- trigger: NewWebhook["triggers"][number],- checked: boolean | "indeterminate",- ) => {- if (checked === "indeterminate") {- return;- }-- setValue(- "triggers",- checked ? [...triggers, trigger] : triggers.filter((t) => t !== trigger),- );- };-return (<FormProvider {...methods}><form@@ -260,41 +251,25 @@ export default function AddEditWebhookForm({Webhook events</h2></label>- <div className="mt-3 flex flex-col gap-2">- {allWebhookTriggers.map((trigger) => (- <div key={trigger}>- <div className="group flex gap-2">- <Checkbox- value={trigger}- id={trigger}- checked={triggers.includes(trigger)}- disabled={updateDisabled}- onCheckedChange={(checked) =>- toggleTrigger(trigger, checked)- }- />- <label- htmlFor={trigger}- className="flex select-none items-center gap-2 text-sm text-neutral-600 group-hover:text-neutral-800"- >- {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}- {trigger === LINK_CLICK_WEBHOOK_TRIGGER ? (- <span className="rounded bg-yellow-100 px-1 py-0.5 text-xs font-medium text-yellow-800">- High traffic- </span>- ) : null}- </label>- </div>-- {trigger === LINK_CLICK_WEBHOOK_TRIGGER && hasLinkClicked ? (- <LinkClickScopeFields- disabled={updateDisabled}- webhook={webhook}- workspaceId={workspaceId}- />- ) : null}- </div>- ))}+ <div className="mt-3">+ <WebhookTriggerSelector+ value={{+ triggers,+ scope: scope ?? "all",+ linkIds: linkIds ?? [],+ folderIds: folderIds ?? [],+ }}+ onChange={(next) => {+ setValue("triggers", next.triggers);+ setValue("scope", next.scope);+ setValue("linkIds", next.linkIds);+ setValue("folderIds", next.folderIds);+ }}+ availableTriggers={allWebhookTriggers}+ disabled={updateDisabled}+ webhookId={webhook?.id}+ savedScope={webhook?.scope}+ /></div></div>@@ -311,119 +286,3 @@ export default function AddEditWebhookForm({</FormProvider>);}--function LinkClickScopeFields({- disabled,- webhook,- workspaceId,-}: {- disabled: boolean;- webhook: WebhookProps | null;- workspaceId: string | undefined;-}) {- const { watch, setValue } = useFormContext<NewWebhook>();-- const [scope = "all", linkIds = [], folderIds = []] = watch([- "scope",- "linkIds",- "folderIds",- ]);-- const { data: fetchedLinkIds } = useSWR<string[]>(- webhook && webhook.scope === "links"- ? `/api/webhooks/${webhook.id}/links?workspaceId=${workspaceId}`- : null,- fetcher,- );-- const { data: fetchedFolderIds } = useSWR<string[]>(- webhook && webhook.scope === "folders"- ? `/api/webhooks/${webhook.id}/folders?workspaceId=${workspaceId}`- : null,- fetcher,- );-- useEffect(() => {- if (webhook?.scope === "links" && fetchedLinkIds) {- setValue("linkIds", fetchedLinkIds);- } else if (webhook?.scope === "folders" && fetchedFolderIds) {- setValue("folderIds", fetchedFolderIds);- }- }, [fetchedLinkIds, fetchedFolderIds, webhook?.scope, setValue]);-- return (- <div className="ml-6 mt-3 rounded-md border border-neutral-200 bg-neutral-50 p-4">- <RadioGroup- value={scope}- onValueChange={(value) => setValue("scope", value as WebhookScope)}- className="flex flex-col gap-2"- disabled={disabled}- >- {WEBHOOK_SCOPE_OPTIONS.map((option) => {- const isSelected = scope === option.value;-- return (- <div key={option.value}>- <label- className={cn(- "relative flex w-full cursor-pointer items-start gap-3 rounded-md border border-neutral-200 bg-white p-3 text-neutral-600 hover:bg-neutral-50",- "transition-all duration-150",- isSelected &&- "border-black bg-neutral-50 text-neutral-900 ring-1 ring-black",- disabled && "cursor-not-allowed opacity-60",- )}- >- <RadioGroupItem- value={option.value}- id={`scope-${option.value}`}- className="mt-0.5"- disabled={disabled}- />- <div className="flex grow flex-col text-sm">- <span className="font-medium">{option.label}</span>- <span className="text-neutral-500">{option.description}</span>- </div>- <CircleCheckFill- className={cn(- "-mr-px -mt-px flex size-4 scale-75 items-center justify-center rounded-full opacity-0 transition-[transform,opacity] duration-150",- isSelected && "scale-100 opacity-100",- )}- />- </label>-- {isSelected && option.value === "folders" ? (- <div className="mt-3 pl-7">- <h3 className="text-sm font-medium text-neutral-900">- Included folders- </h3>- <div className="mt-2">- <FoldersSelector- selectedFolderIds={folderIds ?? []}- setSelectedFolderIds={(ids) => setValue("folderIds", ids)}- disabled={disabled}- />- </div>- </div>- ) : null}-- {isSelected && option.value === "links" ? (- <div className="mt-3 pl-7">- <h3 className="text-sm font-medium text-neutral-900">- Included links- </h3>- <div className="mt-2">- <LinksSelector- selectedLinkIds={linkIds ?? []}- setSelectedLinkIds={(ids) => setValue("linkIds", ids)}- disabled={disabled}- />- </div>- </div>- ) : null}- </div>- );- })}- </RadioGroup>- </div>- );-}diff --git a/apps/web/ui/webhooks/webhook-trigger-selector.tsx b/apps/web/ui/webhooks/webhook-trigger-selector.tsxnew file mode 100644index 0000000000..adc2f9bef1--- /dev/null+++ b/apps/web/ui/webhooks/webhook-trigger-selector.tsx@@ -0,0 +1,255 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import {+ LINK_CLICK_WEBHOOK_TRIGGER,+ WEBHOOK_SCOPE_OPTIONS,+ WEBHOOK_TRIGGER_DESCRIPTIONS,+ WebhookTrigger,+} from "@/lib/webhook/constants";+import { Checkbox, CircleCheckFill, RadioGroup, RadioGroupItem } from "@dub/ui";+import { arrayEqual, cn, fetcher } from "@dub/utils";+import { WebhookScope } from "@prisma/client";+import { useEffect } from "react";+import useSWR from "swr";+import { FoldersSelector } from "./folder-selector";+import { LinksSelector } from "./link-selector";++export type WebhookTriggerSelectorValue = {+ triggers: WebhookTrigger[];+ scope: WebhookScope;+ linkIds: string[];+ folderIds: string[];+};++export function isWebhookTriggerSelectionInvalid(+ value: WebhookTriggerSelectorValue,+): boolean {+ const hasLinkClicked = value.triggers.includes(LINK_CLICK_WEBHOOK_TRIGGER);++ if (!hasLinkClicked) {+ return false;+ }++ return (+ (value.scope === "links" && value.linkIds.length === 0) ||+ (value.scope === "folders" && value.folderIds.length === 0)+ );+}++export function WebhookTriggerSelector({+ value,+ onChange,+ availableTriggers,+ disabled,+ webhookId,+ savedScope,+}: {+ value: WebhookTriggerSelectorValue;+ onChange: (value: WebhookTriggerSelectorValue) => void;+ availableTriggers: WebhookTrigger[];+ disabled?: boolean;+ webhookId?: string;+ savedScope?: WebhookScope | null;+}) {+ const { id: workspaceId } = useWorkspace();++ const { triggers, scope, linkIds, folderIds } = value;+ const hasLinkClicked = triggers.includes(LINK_CLICK_WEBHOOK_TRIGGER);++ const { data: fetchedLinkIds } = useSWR<string[]>(+ webhookId && savedScope === "links"+ ? `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`+ : null,+ fetcher,+ );++ const { data: fetchedFolderIds } = useSWR<string[]>(+ webhookId && savedScope === "folders"+ ? `/api/webhooks/${webhookId}/folders?workspaceId=${workspaceId}`+ : null,+ fetcher,+ );++ useEffect(() => {+ if (scope === "links" && fetchedLinkIds) {+ if (!arrayEqual(linkIds, fetchedLinkIds)) {+ onChange({+ triggers,+ scope,+ linkIds: fetchedLinkIds,+ folderIds,+ });+ }+ } else if (scope !== "links" && linkIds.length > 0) {+ onChange({+ triggers,+ scope,+ linkIds: [],+ folderIds,+ });+ }+ // Only sync from server when scope or fetched ids change — not on manual selection+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [scope, fetchedLinkIds]);++ useEffect(() => {+ if (scope === "folders" && fetchedFolderIds) {+ if (!arrayEqual(folderIds, fetchedFolderIds)) {+ onChange({+ triggers,+ scope,+ linkIds,+ folderIds: fetchedFolderIds,+ });+ }+ } else if (scope !== "folders" && folderIds.length > 0) {+ onChange({+ triggers,+ scope,+ linkIds,+ folderIds: [],+ });+ }+ // Only sync from server when scope or fetched ids change — not on manual selection+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [scope, fetchedFolderIds]);++ const toggleTrigger = (+ trigger: WebhookTrigger,+ checked: boolean | "indeterminate",+ ) => {+ if (checked === "indeterminate") {+ return;+ }++ onChange({+ ...value,+ triggers: checked+ ? [...triggers, trigger]+ : triggers.filter((t) => t !== trigger),+ });+ };++ const handleScopeChange = (nextScope: WebhookScope) => {+ onChange({+ ...value,+ scope: nextScope,+ linkIds: nextScope === "links" ? linkIds : [],+ folderIds: nextScope === "folders" ? folderIds : [],+ });+ };++ return (+ <div className="flex flex-col gap-2">+ {availableTriggers.map((trigger) => (+ <div key={trigger}>+ <div className="group flex gap-2">+ <Checkbox+ value={trigger}+ id={trigger}+ checked={triggers.includes(trigger)}+ disabled={disabled}+ onCheckedChange={(checked) => toggleTrigger(trigger, checked)}+ />+ <label+ htmlFor={trigger}+ className="flex select-none items-center gap-2 text-sm text-neutral-600 group-hover:text-neutral-800"+ >+ {WEBHOOK_TRIGGER_DESCRIPTIONS[trigger]}+ {trigger === LINK_CLICK_WEBHOOK_TRIGGER ? (+ <span className="rounded bg-yellow-100 px-1 py-0.5 text-xs font-medium text-yellow-800">+ High traffic+ </span>+ ) : null}+ </label>+ </div>++ {trigger === LINK_CLICK_WEBHOOK_TRIGGER && hasLinkClicked ? (+ <div className="ml-6 mt-3 rounded-md border border-neutral-200 bg-neutral-50 p-4">+ <RadioGroup+ value={scope}+ onValueChange={(nextValue) =>+ handleScopeChange(nextValue as WebhookScope)+ }+ className="flex flex-col gap-2"+ disabled={disabled}+ >+ {WEBHOOK_SCOPE_OPTIONS.map((option) => {+ const isSelected = scope === option.value;++ return (+ <div key={option.value}>+ <label+ className={cn(+ "relative flex w-full cursor-pointer items-start gap-3 rounded-md border border-neutral-200 bg-white p-3 text-neutral-600 hover:bg-neutral-50",+ "transition-all duration-150",+ isSelected &&+ "border-black bg-neutral-50 text-neutral-900 ring-1 ring-black",+ disabled && "cursor-not-allowed opacity-60",+ )}+ >+ <RadioGroupItem+ value={option.value}+ id={`scope-${option.value}`}+ className="mt-0.5"+ disabled={disabled}+ />+ <div className="flex grow flex-col text-sm">+ <span className="font-medium">{option.label}</span>+ <span className="text-neutral-500">+ {option.description}+ </span>+ </div>+ <CircleCheckFill+ className={cn(+ "-mr-px -mt-px flex size-4 scale-75 items-center justify-center rounded-full opacity-0 transition-[transform,opacity] duration-150",+ isSelected && "scale-100 opacity-100",+ )}+ />+ </label>++ {isSelected && option.value === "folders" ? (+ <div className="mt-3 pl-7">+ <h3 className="text-sm font-medium text-neutral-900">+ Included folders+ </h3>+ <div className="mt-2">+ <FoldersSelector+ selectedFolderIds={folderIds}+ setSelectedFolderIds={(ids) =>+ onChange({ ...value, folderIds: ids })+ }+ disabled={disabled}+ />+ </div>+ </div>+ ) : null}++ {isSelected && option.value === "links" ? (+ <div className="mt-3 pl-7">+ <h3 className="text-sm font-medium text-neutral-900">+ Included links+ </h3>+ <div className="mt-2">+ <LinksSelector+ selectedLinkIds={linkIds}+ setSelectedLinkIds={(ids) =>+ onChange({ ...value, linkIds: ids })+ }+ disabled={disabled}+ />+ </div>+ </div>+ ) : null}+ </div>+ );+ })}+ </RadioGroup>+ </div>+ ) : null}+ </div>+ ))}+ </div>+ );+}